code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ package org.ws4d.coap.connection; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.HashMap; import java.util.PriorityQueue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.AbstractCoapMessage; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapPacketType; import org.ws4d.coap.tools.TimeoutHashMap; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Nico Laum <nico.laum@uni-rostock.de> */ public class BasicCoapSocketHandler implements CoapSocketHandler { /* the socket handler has its own logger * TODO: implement different socket handler for client and server channels */ private final static Logger logger = Logger.getLogger(BasicCoapSocketHandler.class); protected WorkerThread workerThread = null; protected HashMap<ChannelKey, CoapClientChannel> clientChannels = new HashMap<ChannelKey, CoapClientChannel>(); protected HashMap<ChannelKey, CoapServerChannel> serverChannels = new HashMap<ChannelKey, CoapServerChannel>(); private CoapChannelManager channelManager = null; private DatagramChannel dgramChannel = null; public static final int UDP_BUFFER_SIZE = 66000; // max UDP size = 65535 byte[] sendBuffer = new byte[UDP_BUFFER_SIZE]; private int localPort; public BasicCoapSocketHandler(CoapChannelManager channelManager, int port) throws IOException { logger.addAppender(new ConsoleAppender(new SimpleLayout())); // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: logger.setLevel(Level.WARN); this.channelManager = channelManager; dgramChannel = DatagramChannel.open(); dgramChannel.socket().bind(new InetSocketAddress(port)); //port can be 0, then a free port is chosen this.localPort = dgramChannel.socket().getLocalPort(); dgramChannel.configureBlocking(false); workerThread = new WorkerThread(); workerThread.start(); } public BasicCoapSocketHandler(CoapChannelManager channelManager) throws IOException { this(channelManager, 0); } protected class WorkerThread extends Thread { Selector selector = null; /* contains all received message keys of a remote (message id generated by the remote) to detect duplications */ TimeoutHashMap<MessageKey, Boolean> duplicateRemoteMap = new TimeoutHashMap<MessageKey, Boolean>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* contains all received message keys of the host (message id generated by the host) to detect duplications */ TimeoutHashMap<Integer, Boolean> duplicateHostMap = new TimeoutHashMap<Integer, Boolean>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* contains all messages that (possibly) needs to be retransmitted (ACK, RST)*/ TimeoutHashMap<MessageKey, CoapMessage> retransMsgMap = new TimeoutHashMap<MessageKey, CoapMessage>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* contains all messages that are not confirmed yet (CON), * MessageID is always generated by Host and therefore unique */ TimeoutHashMap<Integer, CoapMessage> timeoutConMsgMap = new TimeoutHashMap<Integer, CoapMessage>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS); /* this queue handles the timeout objects in the right order*/ private PriorityQueue<TimeoutObject<Integer>> timeoutQueue = new PriorityQueue<TimeoutObject<Integer>>(); public ConcurrentLinkedQueue<CoapMessage> sendBuffer = new ConcurrentLinkedQueue<CoapMessage>(); /* Contains all sent messages sorted by message ID */ long startTime; static final int POLLING_INTERVALL = 10000; ByteBuffer dgramBuffer; public WorkerThread() { dgramBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE); startTime = System.currentTimeMillis(); try { selector = Selector.open(); dgramChannel.register(selector, SelectionKey.OP_READ); } catch (IOException e1) { e1.printStackTrace(); } } public void close() { if (clientChannels != null) clientChannels.clear(); if (serverChannels != null) serverChannels.clear(); try { dgramChannel.close(); } catch (IOException e) { e.printStackTrace(); } /* TODO: wake up thread and kill it*/ } @Override public void run() { logger.log(Level.INFO, "Receive Thread started."); long waitFor = POLLING_INTERVALL; InetSocketAddress addr = null; while (dgramChannel != null) { /* send all messages in the send buffer */ sendBufferedMessages(); /* handle incoming packets */ dgramBuffer.clear(); try { addr = (InetSocketAddress) dgramChannel.receive(dgramBuffer); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (addr != null){ logger.log(Level.INFO, "handle incomming msg"); handleIncommingMessage(dgramBuffer, addr); } /* handle timeouts */ waitFor = handleTimeouts(); /* TODO: find a good strategy when to update the timeout maps */ duplicateRemoteMap.update(); duplicateHostMap.update(); retransMsgMap.update(); timeoutConMsgMap.update(); /* wait until * 1. selector.wakeup() is called by sendMessage() * 2. incomming packet * 3. timeout */ try { /*FIXME: don't make a select, when something is in the sendQueue, otherwise the packet will be sent after some delay * move this check and the select to a critical section */ selector.select(waitFor); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } protected synchronized void addMessageToSendBuffer(CoapMessage msg){ sendBuffer.add(msg); /* send immediately */ selector.wakeup(); } private void sendBufferedMessages(){ CoapMessage msg = sendBuffer.poll(); while(msg != null){ sendUdpMsg(msg); msg = sendBuffer.poll(); } } private void handleIncommingMessage(ByteBuffer buffer, InetSocketAddress addr) { CoapMessage msg; try { msg = AbstractCoapMessage.parseMessage(buffer.array(), buffer.position()); } catch (Exception e) { logger.warn("Received invalid message: message dropped!"); e.printStackTrace(); return; } CoapPacketType packetType = msg.getPacketType(); int msgId = msg.getMessageID(); MessageKey msgKey = new MessageKey(msgId, addr.getAddress(), addr.getPort()); if (msg.isRequest()){ /* --- INCOMING REQUEST: This is an incoming client request with a message key generated by the remote client*/ if (packetType == CoapPacketType.ACK || packetType == CoapPacketType.RST){ logger.warn("Invalid Packet Type: Request can not be in a ACK or a RST packet"); return; } /* check for duplicates and retransmit the response if a duplication is detected */ if (isRemoteDuplicate(msgKey)){ retransmitRemoteDuplicate(msgKey); return; } /* find or create server channel and handle incoming message */ CoapServerChannel channel = serverChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ /*no server channel found -> create*/ channel = channelManager.createServerChannel(BasicCoapSocketHandler.this, msg, addr.getAddress(), addr.getPort()); if (channel != null){ /* add the new channel to the channel map */ addServerChannel(channel); logger.info("Created new server channel."); } else { /* create failed -> server doesn't accept the connection --> send RST*/ CoapChannel fakeChannel = new BasicCoapServerChannel(BasicCoapSocketHandler.this, null, addr.getAddress(), addr.getPort()); CoapEmptyMessage rstMsg = new CoapEmptyMessage(CoapPacketType.RST, msgId); rstMsg.setChannel(fakeChannel); sendMessage(rstMsg); return; } } msg.setChannel(channel); channel.handleMessage(msg); return; } else if (msg.isResponse()){ /* --- INCOMING RESPONSE: This is an incoming server response (message ID generated by host) * or a separate server response (message ID generated by remote)*/ if (packetType == CoapPacketType.RST){ logger.warn("Invalid Packet Type: RST packet must be empty"); return; } /* check for separate response */ if (packetType == CoapPacketType.CON){ /* This is a separate response, the message ID is generated by the remote */ if (isRemoteDuplicate(msgKey)){ retransmitRemoteDuplicate(msgKey); return; } /* This is a separate Response */ CoapClientChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ logger.warn("Could not find channel of incomming separat response: message dropped"); return; } msg.setChannel(channel); channel.handleMessage(msg); return; } /* normal response (ACK or NON), message id was generated by host */ if (isHostDuplicate(msgId)){ /* drop duplicate responses */ return; } /* confirm the request*/ /* confirm message by removing it from the non confirmedMsgMap*/ /* Corresponding to the spec the server should be aware of a NON as answer to a CON*/ timeoutConMsgMap.remove(msgId); CoapClientChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ logger.warn("Could not find channel of incomming response: message dropped"); return; } msg.setChannel(channel); channel.handleMessage(msg); return; } else if (msg.isEmpty()){ if (packetType == CoapPacketType.CON || packetType == CoapPacketType.NON){ /* TODO: is this always true? */ logger.warn("Invalid Packet Type: CON or NON packets cannot be empty"); return; } /* ACK or RST, Message Id was generated by the host*/ if (isHostDuplicate(msgId)){ /* drop duplicate responses */ return; } /* confirm */ timeoutConMsgMap.remove(msgId); /* get channel */ /* This can be an ACK/RST for a client or a server channel */ CoapChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); if (channel == null){ channel = serverChannels.get(new ChannelKey(addr.getAddress(), addr.getPort())); } if (channel == null){ logger.warn("Could not find channel of incomming response: message dropped"); return; } msg.setChannel(channel); if (packetType == CoapPacketType.ACK ){ /* separate response ACK */ channel.handleMessage(msg); return; } if (packetType == CoapPacketType.RST ){ /* connection closed by remote */ channel.handleMessage(msg); return; } } else { logger.error("Invalid Message Type: not a request, not a response, not empty"); } } private long handleTimeouts(){ long nextTimeout = POLLING_INTERVALL; while (true){ TimeoutObject<Integer> tObj = timeoutQueue.peek(); if (tObj == null){ /* timeout queue is empty */ nextTimeout = POLLING_INTERVALL; break; } nextTimeout = tObj.expires - System.currentTimeMillis(); if (nextTimeout > 0){ /* timeout not expired */ break; } /* timeout expired, sendMessage will send the message and create a new timeout * if the message was already confirmed, nonConfirmedMsgMap.get() will return null */ timeoutQueue.poll(); Integer msgId = tObj.object; /* retransmit message after expired timeout*/ sendUdpMsg((CoapMessage) timeoutConMsgMap.get(msgId)); } return nextTimeout; } private boolean isRemoteDuplicate(MessageKey msgKey){ if (duplicateRemoteMap.get(msgKey) != null){ logger.info("Detected duplicate message"); return true; } return false; } private void retransmitRemoteDuplicate(MessageKey msgKey){ CoapMessage retransMsg = (CoapMessage) retransMsgMap.get(msgKey); if (retransMsg == null){ logger.warn("Detected duplicate message but no response could be found"); } else { sendUdpMsg(retransMsg); } } private boolean isHostDuplicate(int msgId){ if (duplicateHostMap.get(msgId) != null){ logger.info("Detected duplicate message"); return true; } return false; } private void sendUdpMsg(CoapMessage msg) { if (msg == null){ return; } CoapPacketType packetType = msg.getPacketType(); InetAddress inetAddr = msg.getChannel().getRemoteAddress(); int port = msg.getChannel().getRemotePort(); int msgId = msg.getMessageID(); if (packetType == CoapPacketType.CON){ /* in case of a CON this is a Request * requests must be added to the timeout queue * except this was the last retransmission */ if(msg.maxRetransReached()){ /* the connection is broken */ timeoutConMsgMap.remove(msgId); msg.getChannel().lostConnection(true, false); return; } msg.incRetransCounterAndTimeout(); timeoutConMsgMap.put(msgId, msg); TimeoutObject<Integer> tObj = new TimeoutObject<Integer>(msgId, msg.getTimeout() + System.currentTimeMillis()); timeoutQueue.add(tObj); } if (packetType == CoapPacketType.ACK || packetType == CoapPacketType.RST){ /* save this type of messages for a possible retransmission */ retransMsgMap.put(new MessageKey(msgId, inetAddr, port), msg); } /* Nothing to do for NON*/ /* send message*/ ByteBuffer buf = ByteBuffer.wrap(msg.serialize()); /*TODO: check if serialization could fail... then do not put it to any Map!*/ try { dgramChannel.send(buf, new InetSocketAddress(inetAddr, port)); logger.log(Level.INFO, "Send Msg with ID: " + msg.getMessageID()); } catch (IOException e) { e.printStackTrace(); logger.error("Send UDP message failed"); } } } private class MessageKey{ public int msgID; public InetAddress inetAddr; public int port; public MessageKey(int msgID, InetAddress inetAddr, int port) { super(); this.msgID = msgID; this.inetAddr = inetAddr; this.port = port; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((inetAddr == null) ? 0 : inetAddr.hashCode()); result = prime * result + msgID; result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MessageKey other = (MessageKey) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (inetAddr == null) { if (other.inetAddr != null) return false; } else if (!inetAddr.equals(other.inetAddr)) return false; if (msgID != other.msgID) return false; if (port != other.port) return false; return true; } private BasicCoapSocketHandler getOuterType() { return BasicCoapSocketHandler.this; } } private class TimeoutObject<T> implements Comparable<TimeoutObject>{ private long expires; private T object; public TimeoutObject(T object, long expires) { this.expires = expires; this.object = object; } public T getObject() { return object; } public int compareTo(TimeoutObject o){ return (int) (this.expires - o.expires); } } private void addClientChannel(CoapClientChannel channel) { clientChannels.put(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()), channel); } private void addServerChannel(CoapServerChannel channel) { serverChannels.put(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()), channel); } @Override public int getLocalPort() { return localPort; } @Override public void removeClientChannel(CoapClientChannel channel) { clientChannels.remove(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort())); } @Override public void removeServerChannel(CoapServerChannel channel) { serverChannels.remove(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort())); } @Override public void close() { workerThread.close(); } @Override public void sendMessage(CoapMessage message) { if (workerThread != null) { workerThread.addMessageToSendBuffer(message); } } @Override public CoapClientChannel connect(CoapClient client, InetAddress remoteAddress, int remotePort) { if (client == null){ return null; } if (clientChannels.containsKey(new ChannelKey(remoteAddress, remotePort))){ /* channel already exists */ logger.warn("Cannot connect: Client channel already exists"); return null; } CoapClientChannel channel = new BasicCoapClientChannel(this, client, remoteAddress, remotePort); addClientChannel(channel); return channel; } @Override public CoapChannelManager getChannelManager() { return this.channelManager; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapSocketHandler.java
Java
asf20
18,830
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ package org.ws4d.coap.connection; import java.io.IOException; import java.net.InetAddress; import java.util.HashMap; import java.util.Random; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.Constants; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.BasicCoapRequest; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapChannelManager implements CoapChannelManager { // global message id private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class); private int globalMessageId; private static BasicCoapChannelManager instance; private HashMap<Integer, SocketInformation> socketMap = new HashMap<Integer, SocketInformation>(); CoapServer serverListener = null; private BasicCoapChannelManager() { logger.addAppender(new ConsoleAppender(new SimpleLayout())); // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: logger.setLevel(Level.WARN); initRandom(); } public synchronized static CoapChannelManager getInstance() { if (instance == null) { instance = new BasicCoapChannelManager(); } return instance; } /** * Creates a new server channel */ @Override public synchronized CoapServerChannel createServerChannel(CoapSocketHandler socketHandler, CoapMessage message, InetAddress addr, int port){ SocketInformation socketInfo = socketMap.get(socketHandler.getLocalPort()); if (socketInfo.serverListener == null) { /* this is not a server socket */ throw new IllegalStateException("Invalid server socket"); } if (!message.isRequest()){ throw new IllegalStateException("Incomming message is not a request message"); } CoapServer server = socketInfo.serverListener.onAccept((BasicCoapRequest) message); if (server == null){ /* Server rejected channel */ return null; } CoapServerChannel newChannel= new BasicCoapServerChannel( socketHandler, server, addr, port); return newChannel; } /** * Creates a new, global message id for a new COAP message */ @Override public synchronized int getNewMessageID() { if (globalMessageId < Constants.MESSAGE_ID_MAX) { ++globalMessageId; } else globalMessageId = Constants.MESSAGE_ID_MIN; return globalMessageId; } @Override public synchronized void initRandom() { // generate random 16 bit messageId Random random = new Random(); globalMessageId = random.nextInt(Constants.MESSAGE_ID_MAX + 1); } @Override public void createServerListener(CoapServer serverListener, int localPort) { if (!socketMap.containsKey(localPort)) { try { SocketInformation socketInfo = new SocketInformation(new BasicCoapSocketHandler(this, localPort), serverListener); socketMap.put(localPort, socketInfo); } catch (IOException e) { e.printStackTrace(); } } else { /*TODO: raise exception: address already in use */ throw new IllegalStateException(); } } @Override public CoapClientChannel connect(CoapClient client, InetAddress addr, int port) { CoapSocketHandler socketHandler = null; try { socketHandler = new BasicCoapSocketHandler(this); SocketInformation sockInfo = new SocketInformation(socketHandler, null); socketMap.put(socketHandler.getLocalPort(), sockInfo); return socketHandler.connect(client, addr, port); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } private class SocketInformation { public CoapSocketHandler socketHandler = null; public CoapServer serverListener = null; public SocketInformation(CoapSocketHandler socketHandler, CoapServer serverListener) { super(); this.socketHandler = socketHandler; this.serverListener = serverListener; } } @Override public void setMessageId(int globalMessageId) { this.globalMessageId = globalMessageId; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapChannelManager.java
Java
asf20
5,219
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ package org.ws4d.coap.connection; import java.net.InetAddress; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public abstract class BasicCoapChannel implements CoapChannel { /* use the logger of the channel manager */ private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class); protected CoapSocketHandler socketHandler = null; protected CoapChannelManager channelManager = null; protected InetAddress remoteAddress; protected int remotePort; protected int localPort; CoapBlockSize maxReceiveBlocksize = null; //null means no block option CoapBlockSize maxSendBlocksize = null; //null means no block option public BasicCoapChannel(CoapSocketHandler socketHandler, InetAddress remoteAddress, int remotePort) { this.socketHandler = socketHandler; channelManager = socketHandler.getChannelManager(); this.remoteAddress = remoteAddress; this.remotePort = remotePort; this.localPort = socketHandler.getLocalPort(); //FIXME:can be 0 when socketHandler is not yet ready } @Override public void sendMessage(CoapMessage msg) { msg.setChannel(this); socketHandler.sendMessage(msg); } @Override public CoapBlockSize getMaxReceiveBlocksize() { return maxReceiveBlocksize; } @Override public void setMaxReceiveBlocksize(CoapBlockSize maxReceiveBlocksize) { this.maxReceiveBlocksize = maxReceiveBlocksize; } @Override public CoapBlockSize getMaxSendBlocksize() { return maxSendBlocksize; } @Override public void setMaxSendBlocksize(CoapBlockSize maxSendBlocksize) { this.maxSendBlocksize = maxSendBlocksize; } @Override public InetAddress getRemoteAddress() { return remoteAddress; } @Override public int getRemotePort() { return remotePort; } /*A channel is identified (and therefore unique) by its remote address, remote port and the local port * TODO: identify channel also by a token */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + localPort; result = prime * result + ((remoteAddress == null) ? 0 : remoteAddress.hashCode()); result = prime * result + remotePort; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BasicCoapChannel other = (BasicCoapChannel) obj; if (localPort != other.localPort) return false; if (remoteAddress == null) { if (other.remoteAddress != null) return false; } else if (!remoteAddress.equals(other.remoteAddress)) return false; if (remotePort != other.remotePort) return false; return true; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapChannel.java
Java
asf20
3,897
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ package org.ws4d.coap.connection; import java.io.ByteArrayOutputStream; import java.net.InetAddress; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.BasicCoapRequest; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapBlockOption; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapPacketType; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapClientChannel extends BasicCoapChannel implements CoapClientChannel { CoapClient client = null; ClientBlockContext blockContext = null; CoapRequest lastRequest = null; Object trigger = null; public BasicCoapClientChannel(CoapSocketHandler socketHandler, CoapClient client, InetAddress remoteAddress, int remotePort) { super(socketHandler, remoteAddress, remotePort); this.client = client; } @Override public void close() { socketHandler.removeClientChannel(this); } @Override public void handleMessage(CoapMessage message) { if (message.isRequest()){ /* this is a client channel, no requests allowed */ message.getChannel().sendMessage(new CoapEmptyMessage(CoapPacketType.RST, message.getMessageID())); return; } if (message.isEmpty() && message.getPacketType() == CoapPacketType.ACK){ /* this is the ACK of a separate response */ //TODO: implement a handler or listener, that informs a client when a sep. resp. ack was received return; } if (message.getPacketType() == CoapPacketType.CON) { /* this is a separate response */ /* send ACK */ this.sendMessage(new CoapEmptyMessage(CoapPacketType.ACK, message.getMessageID())); } /* check for blockwise transfer */ CoapBlockOption block2 = message.getBlock2(); if (blockContext == null && block2 != null){ /* initiate blockwise transfer */ blockContext = new ClientBlockContext(block2, maxReceiveBlocksize); blockContext.setFirstRequest(lastRequest); blockContext.setFirstResponse((CoapResponse) message); } if (blockContext!= null){ /*blocking option*/ if (!blockContext.addBlock(message, block2)){ /*this was not a correct block*/ /* TODO: implement either a RST or ignore this packet */ } if (!blockContext.isFinished()){ /* TODO: implement a counter to avoid an infinity req/resp loop: * if the same block is received more than x times -> rst the connection * implement maxPayloadSize to avoid an infinity payload */ CoapBlockOption newBlock = blockContext.getNextBlock(); if (lastRequest == null){ /*TODO: this should never happen*/ System.out.println("ERROR: client channel: lastRequest == null"); } else { /* create a new request for the next block */ BasicCoapRequest request = new BasicCoapRequest(lastRequest.getPacketType(), lastRequest.getRequestCode(), channelManager.getNewMessageID()); request.copyHeaderOptions((BasicCoapRequest) blockContext.getFirstRequest()); request.setBlock2(newBlock); sendMessage(request); } /* TODO: implement handler, inform the client that a block (but not the complete message) was received*/ return; } /* blockwise transfer finished */ message.setPayload(blockContext.getPayload()); /* TODO: give the payload separately and leave the original message as they is*/ } /* normal or separate response */ client.onResponse(this, (BasicCoapResponse) message); } @Override public void lostConnection(boolean notReachable, boolean resetByServer) { client.onConnectionFailed(this, notReachable, resetByServer); } @Override public BasicCoapRequest createRequest(boolean reliable, CoapRequestCode requestCode) { BasicCoapRequest msg = new BasicCoapRequest( reliable ? CoapPacketType.CON : CoapPacketType.NON, requestCode, channelManager.getNewMessageID()); msg.setChannel(this); return msg; } @Override public void sendMessage(CoapMessage msg) { super.sendMessage(msg); //TODO: check lastRequest = (CoapRequest) msg; } // public DefaultCoapClientChannel(CoapChannelManager channelManager) { // super(channelManager); // } // // @Override // public void connect(String remoteHost, int remotePort) { // socket = null; // if (remoteHost!=null && remotePort!=-1) { // try { // socket = new DatagramSocket(); // } catch (SocketException e) { // e.printStackTrace(); // } // } // // try { // InetAddress address = InetAddress.getByName(remoteHost); // socket.connect(address, remotePort); // super.establish(socket); // } catch (UnknownHostException e) { // e.printStackTrace(); // } // } private class ClientBlockContext{ ByteArrayOutputStream payload = new ByteArrayOutputStream(); boolean finished = false; CoapBlockSize blockSize; //null means no block option CoapRequest request; CoapResponse response; public ClientBlockContext(CoapBlockOption blockOption, CoapBlockSize maxBlocksize) { /* determine the right blocksize (min of remote and max)*/ if (maxBlocksize == null){ blockSize = blockOption.getBlockSize(); } else { int max = maxBlocksize.getSize(); int remote = blockOption.getBlockSize().getSize(); if (remote < max){ blockSize = blockOption.getBlockSize(); } else { blockSize = maxBlocksize; } } } public byte[] getPayload() { return payload.toByteArray(); } public boolean addBlock(CoapMessage msg, CoapBlockOption block){ int blockPos = block.getBytePosition(); int blockLength = msg.getPayloadLength(); int bufSize = payload.size(); /*TODO: check if payload length = blocksize (except for the last block)*/ if (blockPos > bufSize){ /* data is missing before this block */ return false; } else if ((blockPos + blockLength) <= bufSize){ /* data already received */ return false; } int offset = bufSize - blockPos; payload.write(msg.getPayload(), offset, blockLength - offset); if (block.isLast()){ /* was this the last block */ finished = true; } return true; } public CoapBlockOption getNextBlock() { int num = payload.size() / blockSize.getSize(); //ignore the rest (no rest should be there) return new CoapBlockOption(num, false, blockSize); } public boolean isFinished() { return finished; } public CoapRequest getFirstRequest() { return request; } public void setFirstRequest(CoapRequest request) { this.request = request; } public CoapResponse getFirstResponse() { return response; } public void setFirstResponse(CoapResponse response) { this.response = response; } } @Override public void setTrigger(Object o) { trigger = o; } @Override public Object getTrigger() { return trigger; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapClientChannel.java
Java
asf20
8,128
package org.ws4d.coap.connection; import java.net.InetAddress; public class ChannelKey { public InetAddress inetAddr; public int port; public ChannelKey(InetAddress inetAddr, int port) { this.inetAddr = inetAddr; this.port = port; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((inetAddr == null) ? 0 : inetAddr.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ChannelKey other = (ChannelKey) obj; if (inetAddr == null) { if (other.inetAddr != null) return false; } else if (!inetAddr.equals(other.inetAddr)) return false; if (port != other.port) return false; return true; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/connection/ChannelKey.java
Java
asf20
913
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ package org.ws4d.coap.messages; /** * Type-safe class for CoapPacketTypes * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Sebastian Unger <sebastian.unger@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapPacketType { CON(0x00), NON(0x01), ACK(0x02), RST(0x03); private int packetType; CoapPacketType(int packetType) { if (packetType >= 0x00 && packetType <= 0x03){ this.packetType = packetType; } else { throw new IllegalStateException("Unknown CoAP Packet Type"); } } public static CoapPacketType getPacketType(int packetType) { if (packetType == 0x00) return CON; else if (packetType == 0x01) return NON; else if (packetType == 0x02) return ACK; else if (packetType == 0x03) return RST; else throw new IllegalStateException("Unknown CoAP Packet Type"); } public int getValue() { return packetType; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/messages/CoapPacketType.java
Java
asf20
1,739
package org.ws4d.coap.messages; import java.io.UnsupportedEncodingException; import java.util.Vector; import org.ws4d.coap.interfaces.CoapRequest; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapRequest extends AbstractCoapMessage implements CoapRequest { CoapRequestCode requestCode; public BasicCoapRequest(byte[] bytes, int length) { /* length ought to be provided by UDP header */ this(bytes, length, 0); } public BasicCoapRequest(byte[] bytes, int length, int offset) { serialize(bytes, length, offset); /* check if request code is valid, this function throws an error in case of an invalid argument */ requestCode = CoapRequestCode.parseRequestCode(this.messageCodeValue); //TODO: check integrity of header options } public BasicCoapRequest(CoapPacketType packetType, CoapRequestCode requestCode, int messageId) { this.version = 1; this.packetType = packetType; this.requestCode = requestCode; this.messageCodeValue = requestCode.getValue(); this.messageId = messageId; } @Override public void setToken(byte[] token){ /* this function is only public for a request*/ super.setToken(token); } @Override public CoapRequestCode getRequestCode() { return requestCode; } @Override public void setUriHost(String host) { if (host == null) return; if (options.optionExists(CoapHeaderOptionType.Uri_Host)){ throw new IllegalArgumentException("Uri-Host option already exists"); } if (host.length() < 1 || host.length() > CoapHeaderOption.MAX_LENGTH){ throw new IllegalArgumentException("Invalid Uri-Host option length"); } /*TODO: check if host is a valid address */ options.addOption(CoapHeaderOptionType.Uri_Host, host.getBytes()); } @Override public void setUriPort(int port) { if (port < 0) return; if (options.optionExists(CoapHeaderOptionType.Uri_Port)){ throw new IllegalArgumentException("Uri-Port option already exists"); } byte[] value = long2CoapUint(port); if(value.length < 0 || value.length > 2){ throw new IllegalStateException("Illegal Uri-Port length"); } options.addOption(new CoapHeaderOption(CoapHeaderOptionType.Uri_Port, value)); } @Override public void setUriPath(String path) { if (path == null) return; if (path.length() > CoapHeaderOption.MAX_LENGTH ){ throw new IllegalArgumentException("Uri-Path option too long"); } /* delete old options if present */ options.removeOption(CoapHeaderOptionType.Uri_Path); /*create substrings */ String[] pathElements = path.split("/"); /* add a Uri Path option for each part */ for (String element : pathElements) { /* check length */ if(element.length() < 0 || element.length() > CoapHeaderOption.MAX_LENGTH){ throw new IllegalArgumentException("Invalid Uri-Path"); } else if (element.length() > 0){ /* ignore empty substrings */ options.addOption(CoapHeaderOptionType.Uri_Path, element.getBytes()); } } } @Override public void setUriQuery(String query) { if (query == null) return; if (query.length() > CoapHeaderOption.MAX_LENGTH ){ throw new IllegalArgumentException("Uri-Query option too long"); } /* delete old options if present */ options.removeOption(CoapHeaderOptionType.Uri_Query); /*create substrings */ String[] pathElements = query.split("&"); /* add a Uri Path option for each part */ for (String element : pathElements) { /* check length */ if(element.length() < 0 || element.length() > CoapHeaderOption.MAX_LENGTH){ throw new IllegalArgumentException("Invalid Uri-Path"); } else if (element.length() > 0){ /* ignore empty substrings */ options.addOption(CoapHeaderOptionType.Uri_Query, element.getBytes()); } } } @Override public void setProxyUri(String proxyUri) { if (proxyUri == null) return; if (options.optionExists(CoapHeaderOptionType.Proxy_Uri)){ throw new IllegalArgumentException("Proxy Uri already exists"); } if (proxyUri.length() < 1){ throw new IllegalArgumentException("Proxy Uri must be at least one byte long"); } if (proxyUri.length() > CoapHeaderOption.MAX_LENGTH ){ throw new IllegalArgumentException("Proxy Uri longer then 270 bytes are not supported yet (to be implemented)"); } options.addOption(CoapHeaderOptionType.Proxy_Uri, proxyUri.getBytes()); } @Override public Vector<String> getUriQuery(){ Vector<String> queryList = new Vector<String>(); for (CoapHeaderOption option : options) { if(option.getOptionType() == CoapHeaderOptionType.Uri_Query){ queryList.add(new String(option.getOptionData())); } } return queryList; } @Override public String getUriHost(){ return new String(options.getOption(CoapHeaderOptionType.Uri_Host).getOptionData()); } @Override public int getUriPort(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Uri_Port); if (option == null){ return -1; //TODO: return default Coap Port? } byte[] value = option.getOptionData(); if(value.length < 0 || value.length > 2){ /* should never happen because this is an internal variable and should be checked during serialization */ throw new IllegalStateException("Illegal Uri-Port Option length"); } /* checked length -> cast is safe*/ return (int)coapUint2Long(options.getOption(CoapHeaderOptionType.Uri_Port).getOptionData()); } @Override public String getUriPath() { if (options.getOption(CoapHeaderOptionType.Uri_Path) == null){ return null; } StringBuilder uriPathBuilder = new StringBuilder(); for (CoapHeaderOption option : options) { if (option.getOptionType() == CoapHeaderOptionType.Uri_Path) { String uriPathElement; try { uriPathElement = new String(option.getOptionData(), "UTF-8"); uriPathBuilder.append("/"); uriPathBuilder.append(uriPathElement); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Invalid Encoding"); } } } return uriPathBuilder.toString(); } @Override public void addAccept(CoapMediaType mediaType){ options.addOption(CoapHeaderOptionType.Accept, long2CoapUint(mediaType.getValue())); } @Override public Vector<CoapMediaType> getAccept(CoapMediaType mediaType){ if (options.getOption(CoapHeaderOptionType.Accept) == null){ return null; } Vector<CoapMediaType> acceptList = new Vector<CoapMediaType>(); for (CoapHeaderOption option : options) { if (option.getOptionType() == CoapHeaderOptionType.Accept) { CoapMediaType accept = CoapMediaType.parse((int)coapUint2Long(option.optionData)); // if (accept != CoapMediaType.UNKNOWN){ /* add also UNKNOWN types to list */ acceptList.add(accept); // } } } return acceptList; } @Override public String getProxyUri(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Proxy_Uri); if (option == null) return null; return new String(option.getOptionData()); } @Override public void addETag(byte[] etag) { if (etag == null){ throw new IllegalArgumentException("etag MUST NOT be null"); } if (etag.length < 1 || etag.length > 8){ throw new IllegalArgumentException("Invalid etag length"); } options.addOption(CoapHeaderOptionType.Etag, etag); } @Override public Vector<byte[]> getETag() { if (options.getOption(CoapHeaderOptionType.Etag) == null){ return null; } Vector<byte[]> etagList = new Vector<byte[]>(); for (CoapHeaderOption option : options) { if (option.getOptionType() == CoapHeaderOptionType.Etag) { byte[] data = option.getOptionData(); if (data.length >= 1 && data.length <= 8){ etagList.add(option.getOptionData()); } } } return etagList; } @Override public boolean isRequest() { return true; } @Override public boolean isResponse() { return false; } @Override public boolean isEmpty() { return false; } @Override public String toString() { return packetType.toString() + ", " + requestCode.toString() + ", MsgId: " + getMessageID() +", #Options: " + options.getOptionCount(); } @Override public void setRequestCode(CoapRequestCode requestCode) { this.requestCode = requestCode; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/messages/BasicCoapRequest.java
Java
asf20
8,398
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ /* WS4D Java CoAP Implementation * (c) 2011 WS4D.org * * written by Sebastian Unger */ package org.ws4d.coap.messages; import java.nio.ByteBuffer; import java.util.Collections; import java.util.Iterator; import java.util.Random; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapMessage; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public abstract class AbstractCoapMessage implements CoapMessage { /* use the logger of the channel manager */ private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class); protected static final int HEADER_LENGTH = 4; /* Header */ protected int version; protected CoapPacketType packetType; protected int messageCodeValue; //protected int optionCount; protected int messageId; /* Options */ protected CoapHeaderOptions options = new CoapHeaderOptions(); /* Payload */ protected byte[] payload = null; protected int payloadLength = 0; /* corresponding channel */ CoapChannel channel = null; /* Retransmission State */ int timeout = 0; int retransmissionCounter = 0; protected void serialize(byte[] bytes, int length, int offset){ /* check length to avoid buffer overflow exceptions */ this.version = 1; this.packetType = (CoapPacketType.getPacketType((bytes[offset + 0] & 0x30) >> 4)); int optionCount = bytes[offset + 0] & 0x0F; this.messageCodeValue = (bytes[offset + 1] & 0xFF); this.messageId = ((bytes[offset + 2] << 8) & 0xFF00) + (bytes[offset + 3] & 0xFF); /* serialize options */ this.options = new CoapHeaderOptions(bytes, offset + HEADER_LENGTH, optionCount); /* get and check payload length */ payloadLength = length - HEADER_LENGTH - options.getDeserializedLength(); if (payloadLength < 0){ throw new IllegalStateException("Invaldid CoAP Message (payload length negative)"); } /* copy payload */ int payloadOffset = offset + HEADER_LENGTH + options.getDeserializedLength(); payload = new byte[payloadLength]; for (int i = 0; i < payloadLength; i++){ payload[i] = bytes[i + payloadOffset]; } } /* TODO: this function should be in another class */ public static CoapMessage parseMessage(byte[] bytes, int length){ return parseMessage(bytes, length, 0); } public static CoapMessage parseMessage(byte[] bytes, int length, int offset){ /* we "peek" the header to determine the kind of message * TODO: duplicate Code */ int messageCodeValue = (bytes[offset + 1] & 0xFF); if (messageCodeValue == 0){ return new CoapEmptyMessage(bytes, length, offset); } else if (messageCodeValue >= 0 && messageCodeValue <= 31 ){ return new BasicCoapRequest(bytes, length, offset); } else if (messageCodeValue >= 64 && messageCodeValue <= 191){ return new BasicCoapResponse(bytes, length, offset); } else { throw new IllegalArgumentException("unknown CoAP message"); } } public int getVersion() { return version; } @Override public int getMessageCodeValue() { return messageCodeValue; } @Override public CoapPacketType getPacketType() { return packetType; } public byte[] getPayload() { return payload; } public int getPayloadLength() { return payloadLength; } @Override public int getMessageID() { return messageId; } @Override public void setMessageID(int messageId) { this.messageId = messageId; } public byte[] serialize() { /* TODO improve memory allocation */ /* serialize header options first to get the length*/ int optionsLength = 0; byte[] optionsArray = null; if (options != null) { optionsArray = this.options.serialize(); optionsLength = this.options.getSerializedLength(); } /* allocate memory for the complete packet */ int length = HEADER_LENGTH + optionsLength + payloadLength; byte[] serializedPacket = new byte[length]; /* serialize header */ serializedPacket[0] = (byte) ((this.version & 0x03) << 6); serializedPacket[0] |= (byte) ((this.packetType.getValue() & 0x03) << 4); serializedPacket[0] |= (byte) (options.getOptionCount() & 0x0F); serializedPacket[1] = (byte) (this.getMessageCodeValue() & 0xFF); serializedPacket[2] = (byte) ((this.messageId >> 8) & 0xFF); serializedPacket[3] = (byte) (this.messageId & 0xFF); /* copy serialized options to the final array */ int offset = HEADER_LENGTH; if (options != null) { for (int i = 0; i < optionsLength; i++) serializedPacket[i + offset] = optionsArray[i]; } /* copy payload to the final array */ offset = HEADER_LENGTH + optionsLength; for (int i = 0; i < this.payloadLength; i++) { serializedPacket[i + offset] = payload[i]; } return serializedPacket; } public void setPayload(byte[] payload) { this.payload = payload; if (payload!=null) this.payloadLength = payload.length; else this.payloadLength = 0; } public void setPayload(char[] payload) { this.payload = new byte[payload.length]; for (int i = 0; i < payload.length; i++) { this.payload[i] = (byte) payload[i]; } this.payloadLength = payload.length; } public void setPayload(String payload) { setPayload(payload.toCharArray()); } @Override public void setContentType(CoapMediaType mediaType){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Content_Type); if (option != null){ /* content Type MUST only exists once */ throw new IllegalStateException("added content option twice"); } if ( mediaType == CoapMediaType.UNKNOWN){ throw new IllegalStateException("unknown content type"); } /* convert value */ byte[] data = long2CoapUint(mediaType.getValue()); /* no need to check result, mediaType is safe */ /* add option to Coap Header*/ options.addOption(new CoapHeaderOption(CoapHeaderOptionType.Content_Type, data)); } @Override public CoapMediaType getContentType(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Content_Type); if (option == null){ /* not content type TODO: return UNKNOWN ?*/ return null; } /* no need to check length, CoapMediaType parse function will do*/ int mediaTypeCode = (int) coapUint2Long(options.getOption(CoapHeaderOptionType.Content_Type).getOptionData()); return CoapMediaType.parse(mediaTypeCode); } @Override public byte[] getToken(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Token); if (option == null){ return null; } return option.getOptionData(); } protected void setToken(byte[] token){ if (token == null){ return; } if (token.length < 1 || token.length > 8){ throw new IllegalArgumentException("Invalid Token Length"); } options.addOption(CoapHeaderOptionType.Token, token); } @Override public CoapBlockOption getBlock1(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block1); if (option == null){ return null; } CoapBlockOption blockOpt = new CoapBlockOption(option.getOptionData()); return blockOpt; } @Override public void setBlock1(CoapBlockOption blockOption){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block1); if (option != null){ //option already exists options.removeOption(CoapHeaderOptionType.Block1); } options.addOption(CoapHeaderOptionType.Block1, blockOption.getBytes()); } @Override public CoapBlockOption getBlock2(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block2); if (option == null){ return null; } CoapBlockOption blockOpt = new CoapBlockOption(option.getOptionData()); return blockOpt; } @Override public void setBlock2(CoapBlockOption blockOption){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block2); if (option != null){ //option already exists options.removeOption(CoapHeaderOptionType.Block2); } options.addOption(CoapHeaderOptionType.Block2, blockOption.getBytes()); } @Override public Integer getObserveOption() { CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Observe); if (option == null){ return null; } byte[] data = option.getOptionData(); if (data.length < 0 || data.length > 2){ logger.warn("invalid observe option length, return null"); return null; } return (int) AbstractCoapMessage.coapUint2Long(data); } @Override public void setObserveOption(int sequenceNumber) { CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Observe); if (option != null){ options.removeOption(CoapHeaderOptionType.Observe); } byte[] data = long2CoapUint(sequenceNumber); if (data.length < 0 || data.length > 2){ throw new IllegalArgumentException("invalid observe option length"); } options.addOption(CoapHeaderOptionType.Observe, data); } public void copyHeaderOptions(AbstractCoapMessage origin){ options.removeAll(); options.copyFrom(origin.options); } public void removeOption(CoapHeaderOptionType optionType){ options.removeOption(optionType); } @Override public CoapChannel getChannel() { return channel; } @Override public void setChannel(CoapChannel channel) { this.channel = channel; } @Override public int getTimeout() { if (timeout == 0) { Random random = new Random(); timeout = RESPONSE_TIMEOUT_MS + random.nextInt((int) (RESPONSE_TIMEOUT_MS * RESPONSE_RANDOM_FACTOR) - RESPONSE_TIMEOUT_MS); } return timeout; } @Override public boolean maxRetransReached() { if (retransmissionCounter < MAX_RETRANSMIT) { return false; } return true; } @Override public void incRetransCounterAndTimeout() { /*TODO: Rename*/ retransmissionCounter += 1; timeout *= 2; } @Override public boolean isReliable() { if (packetType == CoapPacketType.NON){ return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((channel == null) ? 0 : channel.hashCode()); result = prime * result + getMessageID(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractCoapMessage other = (AbstractCoapMessage) obj; if (channel == null) { if (other.channel != null) return false; } else if (!channel.equals(other.channel)) return false; if (getMessageID() != other.getMessageID()) return false; return true; } protected static long coapUint2Long(byte[] data){ /* avoid buffer overflow */ if(data.length > 8){ return -1; } /* fill with leading zeros */ byte[] tmp = new byte[8]; for (int i = 0; i < data.length; i++) { tmp[i + 8 - data.length] = data[i]; } /* convert to long */ ByteBuffer buf = ByteBuffer.wrap(tmp); /* byte buffer contains 8 bytes */ return buf.getLong(); } protected static byte[] long2CoapUint(long value){ /* only unsigned values supported */ if (value < 0){ return null; } /* a zero length value implies zero */ if (value == 0){ return new byte[0]; } /* convert long to byte array with a fixed length of 8 byte*/ ByteBuffer buf = ByteBuffer.allocate(8); buf.putLong(value); byte[] tmp = buf.array(); /* remove leading zeros */ int leadingZeros = 0; for (int i = 0; i < tmp.length; i++) { if (tmp[i] == 0){ leadingZeros = i+1; } else { break; } } /* copy to byte array without leading zeros */ byte[] result = new byte[8 - leadingZeros]; for (int i = 0; i < result.length; i++) { result[i] = tmp[i + leadingZeros]; } return result; } public enum CoapHeaderOptionType { UNKNOWN(-1), Content_Type (1), Max_Age (2), Proxy_Uri(3), Etag (4), Uri_Host (5), Location_Path (6), Uri_Port (7), Location_Query (8), Uri_Path (9), Observe (10), Token (11), Accept (12), If_Match (13), Uri_Query (15), If_None_Match (21), Block1 (19), Block2 (17); int value; CoapHeaderOptionType(int optionValue){ value = optionValue; } public static CoapHeaderOptionType parse(int optionTypeValue){ switch(optionTypeValue){ case 1: return Content_Type; case 2: return Max_Age; case 3: return Proxy_Uri; case 4: return Etag; case 5: return Uri_Host; case 6: return Location_Path; case 7: return Uri_Port; case 8: return Location_Query; case 9: return Uri_Path; case 10: return Observe; case 11:return Token; case 12:return Accept; case 13:return If_Match; case 15:return Uri_Query; case 21:return If_None_Match; case 19:return Block1; case 17:return Block2; default: return UNKNOWN; } } public int getValue(){ return value; } /* TODO: implement validity checks */ /*TODO: implement isCritical(int optionTypeValue), isElective()*/ } protected class CoapHeaderOption implements Comparable<CoapHeaderOption> { CoapHeaderOptionType optionType; int optionTypeValue; /* integer representation of optionType*/ byte[] optionData; int shortLength; int longLength; int deserializedLength; static final int MAX_LENGTH = 270; public int getDeserializedLength() { return deserializedLength; } public CoapHeaderOption(CoapHeaderOptionType optionType, byte[] value) { if (optionType == CoapHeaderOptionType.UNKNOWN){ /*TODO: implement check if it is a critical option */ throw new IllegalStateException("Unknown header option"); } if (value == null){ throw new IllegalArgumentException("Header option value MUST NOT be null"); } this.optionTypeValue = optionType.getValue(); this.optionData = value; if (value.length < 15) { shortLength = value.length; longLength = 0; } else { shortLength = 15; longLength = value.length - shortLength; } } public CoapHeaderOption(byte[] bytes, int offset, int lastOptionNumber){ int headerLength; /* parse option type */ optionTypeValue = ((bytes[offset] & 0xF0) >> 4) + lastOptionNumber; optionType = CoapHeaderOptionType.parse(optionTypeValue); if (optionType == CoapHeaderOptionType.UNKNOWN){ if (optionTypeValue % 14 == 0){ /* no-op: no operation for deltas > 14 */ } else { /*TODO: implement check if it is a critical option */ throw new IllegalArgumentException("Unknown header option"); } } /* parse length */ if ((bytes[offset] & 0x0F) < 15) { shortLength = bytes[offset] & 0x0F; longLength = 0; headerLength = 1; } else { shortLength = 15; longLength = bytes[offset + 1]; headerLength = 2; /* additional length byte */ } /* copy value */ optionData = new byte[shortLength + longLength]; for (int i = 0; i < shortLength + longLength; i++){ optionData[i] = bytes[i + headerLength + offset]; } deserializedLength += headerLength + shortLength + longLength; } @Override public int compareTo(CoapHeaderOption option) { /* compare function for sorting * TODO: check what happens in case of equal option values * IMPORTANT: order must be the same for e.g., URI path*/ if (this.optionTypeValue != option.optionTypeValue) return this.optionTypeValue < option.optionTypeValue ? -1 : 1; else return 0; } public boolean hasLongLength(){ if (shortLength == 15){ return true; } else return false; } public int getLongLength() { return longLength; } public int getShortLength() { return shortLength; } public int getOptionTypeValue() { return optionTypeValue; } public byte[] getOptionData() { return optionData; } public int getSerializeLength(){ if (hasLongLength()){ return optionData.length + 2; } else { return optionData.length + 1; } } @Override public String toString() { char[] printableOptionValue = new char[optionData.length]; for (int i = 0; i < optionData.length; i++) printableOptionValue[i] = (char) optionData[i]; return "Option Number: " + " (" + optionTypeValue + ")" + ", Option Value: " + String.copyValueOf(printableOptionValue); } public CoapHeaderOptionType getOptionType() { return optionType; } } protected class CoapHeaderOptions implements Iterable<CoapHeaderOption>{ private Vector<CoapHeaderOption> headerOptions = new Vector<CoapHeaderOption>(); private int deserializedLength; private int serializedLength = 0; public CoapHeaderOptions(byte[] bytes, int option_count){ this(bytes, option_count, option_count); } public CoapHeaderOptions(byte[] bytes, int offset, int optionCount){ /* note: we only receive deltas and never concrete numbers */ /* TODO: check integrity */ deserializedLength = 0; int lastOptionNumber = 0; int optionOffset = offset; for (int i = 0; i < optionCount; i++) { CoapHeaderOption option = new CoapHeaderOption(bytes, optionOffset, lastOptionNumber); lastOptionNumber = option.getOptionTypeValue(); deserializedLength += option.getDeserializedLength(); optionOffset += option.getDeserializedLength(); addOption(option); } } public CoapHeaderOptions() { /* creates empty header options */ } public CoapHeaderOption getOption(int optionNumber) { for (CoapHeaderOption headerOption : headerOptions) { if (headerOption.getOptionTypeValue() == optionNumber) { return headerOption; } } return null; } public CoapHeaderOption getOption(CoapHeaderOptionType optionType) { for (CoapHeaderOption headerOption : headerOptions) { if (headerOption.getOptionType() == optionType) { return headerOption; } } return null; } public boolean optionExists(CoapHeaderOptionType optionType) { CoapHeaderOption option = getOption(optionType); if (option == null){ return false; } else return true; } public void addOption(CoapHeaderOption option) { headerOptions.add(option); /*TODO: only sort when options are serialized*/ Collections.sort(headerOptions); } public void addOption(CoapHeaderOptionType optionType, byte[] value){ addOption(new CoapHeaderOption(optionType, value)); } public void removeOption(CoapHeaderOptionType optionType){ CoapHeaderOption headerOption; // get elements of Vector /* note: iterating over and changing a vector at the same time is not allowed */ int i = 0; while (i < headerOptions.size()){ headerOption = headerOptions.get(i); if (headerOption.getOptionType() == optionType) { headerOptions.remove(i); } else { /* only increase when no element was removed*/ i++; } } Collections.sort(headerOptions); } public void removeAll(){ headerOptions.clear(); } public void copyFrom(CoapHeaderOptions origin){ for (CoapHeaderOption option : origin) { addOption(option); } } public int getOptionCount() { return headerOptions.size(); } public byte[] serialize() { /* options are serialized here to be more efficient (only one byte array necessary)*/ int length = 0; /* calculate the overall length first */ for (CoapHeaderOption option : headerOptions) { length += option.getSerializeLength(); } byte[] data = new byte[length]; int arrayIndex = 0; int lastOptionNumber = 0; /* let's keep track of this */ for (CoapHeaderOption headerOption : headerOptions) { /* TODO: move the serialization implementation to CoapHeaderOption */ int optionDelta = headerOption.getOptionTypeValue() - lastOptionNumber; lastOptionNumber = headerOption.getOptionTypeValue(); // set length(s) data[arrayIndex++] = (byte) (((optionDelta & 0x0F) << 4) | (headerOption.getShortLength() & 0x0F)); if (headerOption.hasLongLength()) { data[arrayIndex++] = (byte) (headerOption.getLongLength() & 0xFF); } // copy option value byte[] value = headerOption.getOptionData(); for (int i = 0; i < value.length; i++) { data[arrayIndex++] = value[i]; } } serializedLength = length; return data; } public int getDeserializedLength(){ return deserializedLength; } public int getSerializedLength() { return serializedLength; } @Override public Iterator<CoapHeaderOption> iterator() { return headerOptions.iterator(); } @Override public String toString() { String result = "\tOptions:\n"; for (CoapHeaderOption option : headerOptions) { result += "\t\t" + option.toString() + "\n"; } return result; } } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/messages/AbstractCoapMessage.java
Java
asf20
23,178
package org.ws4d.coap.messages; import org.ws4d.coap.interfaces.CoapResponse; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapResponse extends AbstractCoapMessage implements CoapResponse { CoapResponseCode responseCode; public BasicCoapResponse(byte[] bytes, int length){ this(bytes, length, 0); } public BasicCoapResponse(byte[] bytes, int length, int offset){ serialize(bytes, length, offset); /* check if response code is valid, this function throws an error in case of an invalid argument */ responseCode = CoapResponseCode.parseResponseCode(this.messageCodeValue); //TODO: check integrity of header options } /* token can be null */ public BasicCoapResponse(CoapPacketType packetType, CoapResponseCode responseCode, int messageId, byte[] requestToken){ this.version = 1; this.packetType = packetType; this.responseCode = responseCode; if (responseCode == CoapResponseCode.UNKNOWN){ throw new IllegalArgumentException("UNKNOWN Response Code not allowed"); } this.messageCodeValue = responseCode.getValue(); this.messageId = messageId; setToken(requestToken); } @Override public CoapResponseCode getResponseCode() { return responseCode; } @Override public void setMaxAge(int maxAge){ if (options.optionExists(CoapHeaderOptionType.Max_Age)){ throw new IllegalStateException("Max Age option already exists"); } if (maxAge < 0){ throw new IllegalStateException("Max Age MUST be an unsigned value"); } options.addOption(CoapHeaderOptionType.Max_Age, long2CoapUint(maxAge)); } @Override public long getMaxAge(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Max_Age); if (option == null){ return -1; } return coapUint2Long((options.getOption(CoapHeaderOptionType.Max_Age).getOptionData())); } @Override public void setETag(byte[] etag){ if (etag == null){ throw new IllegalArgumentException("etag MUST NOT be null"); } if (etag.length < 1 || etag.length > 8){ throw new IllegalArgumentException("Invalid etag length"); } options.addOption(CoapHeaderOptionType.Etag, etag); } @Override public byte[] getETag(){ CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Etag); if (option == null){ return null; } return option.getOptionData(); } @Override public boolean isRequest() { return false; } @Override public boolean isResponse() { return true; } @Override public boolean isEmpty() { return false; } @Override public String toString() { return packetType.toString() + ", " + responseCode.toString() + ", MsgId: " + getMessageID() +", #Options: " + options.getOptionCount(); } @Override public void setResponseCode(CoapResponseCode responseCode) { if (responseCode != CoapResponseCode.UNKNOWN){ this.responseCode = responseCode; this.messageCodeValue = responseCode.getValue(); } } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/messages/BasicCoapResponse.java
Java
asf20
3,042
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapRequestCode { GET(1), POST(2), PUT(3), DELETE(4); private int code; private CoapRequestCode(int code) { this.code = code; } public static CoapRequestCode parseRequestCode(int codeValue){ switch (codeValue) { case 1: return GET; case 2: return POST; case 3: return PUT; case 4: return DELETE; default: throw new IllegalArgumentException("Invalid Request Code"); } } public int getValue() { return code; } @Override public String toString() { switch (this) { case GET: return "GET"; case POST: return "POST"; case PUT: return "PUT"; case DELETE: return "DELETE"; } return null; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/messages/CoapRequestCode.java
Java
asf20
828
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapResponseCode { Created_201(65), Deleted_202(66), Valid_203(67), Changed_204(68), Content_205(69), Bad_Request_400(128), Unauthorized_401(129), Bad_Option_402(130), Forbidden_403(131), Not_Found_404(132), Method_Not_Allowed_405(133), Precondition_Failed_412(140), Request_Entity_To_Large_413(141), Unsupported_Media_Type_415(143), Internal_Server_Error_500(160), Not_Implemented_501(161), Bad_Gateway_502(162), Service_Unavailable_503(163), Gateway_Timeout_504(164), Proxying_Not_Supported_505(165), UNKNOWN(-1); private int code; private CoapResponseCode(int code) { this.code = code; } public static CoapResponseCode parseResponseCode(int codeValue) { switch (codeValue) { /* 32..63: reserved */ /* 64 is not used anymore */ // case 64: // this.code = ResponseCode.OK_200; // break; case 65: return Created_201; case 66: return Deleted_202; case 67: return Valid_203; case 68: return Changed_204; case 69: return Content_205; case 128: return Bad_Request_400; case 129: return Unauthorized_401; case 130: return Bad_Option_402; case 131: return Forbidden_403; case 132: return Not_Found_404; case 133: return Method_Not_Allowed_405; case 140: return Precondition_Failed_412; case 141: return Request_Entity_To_Large_413; case 143: return Unsupported_Media_Type_415; case 160: return Internal_Server_Error_500; case 161: return Not_Implemented_501; case 162: return Bad_Gateway_502; case 163: return Service_Unavailable_503; case 164: return Gateway_Timeout_504; case 165: return Proxying_Not_Supported_505; default: if (codeValue >= 64 && codeValue <= 191) { return UNKNOWN; } else { throw new IllegalArgumentException("Invalid Response Code"); } } } public int getValue() { return code; } @Override public String toString() { switch (this) { case Created_201: return "Created_201"; case Deleted_202: return "Deleted_202"; case Valid_203: return "Valid_203"; case Changed_204: return "Changed_204"; case Content_205: return "Content_205"; case Bad_Request_400: return "Bad_Request_400"; case Unauthorized_401: return "Unauthorized_401"; case Bad_Option_402: return "Bad_Option_402"; case Forbidden_403: return "Forbidden_403"; case Not_Found_404: return "Not_Found_404"; case Method_Not_Allowed_405: return "Method_Not_Allowed_405"; case Precondition_Failed_412: return "Precondition_Failed_412"; case Request_Entity_To_Large_413: return "Request_Entity_To_Large_413"; case Unsupported_Media_Type_415: return "Unsupported_Media_Type_415"; case Internal_Server_Error_500: return "Internal_Server_Error_500"; case Not_Implemented_501: return "Not_Implemented_501"; case Bad_Gateway_502: return "Bad_Gateway_502"; case Service_Unavailable_503: return "Service_Unavailable_503"; case Gateway_Timeout_504: return "Gateway_Timeout_504"; case Proxying_Not_Supported_505: return "Proxying_Not_Supported_505"; default: return "Unknown_Response_Code"; } } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/messages/CoapResponseCode.java
Java
asf20
3,339
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoapEmptyMessage extends AbstractCoapMessage { public CoapEmptyMessage(byte[] bytes, int length){ this(bytes, length, 0); } public CoapEmptyMessage(byte[] bytes, int length, int offset){ serialize(bytes, length, offset); /* check if response code is valid, this function throws an error in case of an invalid argument */ if (this.messageCodeValue != 0){ throw new IllegalArgumentException("Not an empty CoAP message."); } if (length != HEADER_LENGTH){ throw new IllegalArgumentException("Invalid length of an empty message"); } } public CoapEmptyMessage(CoapPacketType packetType, int messageId) { this.version = 1; this.packetType = packetType; this.messageCodeValue = 0; this.messageId = messageId; } @Override public boolean isRequest() { return false; } @Override public boolean isResponse() { return false; } @Override public boolean isEmpty() { return true; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/messages/CoapEmptyMessage.java
Java
asf20
1,047
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoapBlockOption{ private int number; private boolean more; private CoapBlockSize blockSize; public CoapBlockOption(byte[] data){ if (data.length <1 || data.length > 3){ throw new IllegalArgumentException("invalid block option"); } long val = AbstractCoapMessage.coapUint2Long(data); this.blockSize = CoapBlockSize.parse((int) (val & 0x7)); if (blockSize == null){ throw new IllegalArgumentException("invalid block options"); } if ((val & 0x8) == 0){ //more bit not set more = false; } else { more = true; } number = (int) (val >> 4); } public CoapBlockOption(int number, boolean more, CoapBlockSize blockSize){ if (blockSize == null){ throw new IllegalArgumentException(); } if (number < 0 || number > 0xFFFFFF ){ //not an unsigned 20 bit value throw new IllegalArgumentException(); } this.blockSize = blockSize; this.number = number; this.more = more; } public int getNumber() { return number; } public boolean isLast() { return !more; } public CoapBlockSize getBlockSize() { return blockSize; } public int getBytePosition(){ return number << (blockSize.getExponent() + 4); } public byte[] getBytes(){ int value = number << 4; value |= blockSize.getExponent(); if (more){ value |= 0x8; } return AbstractCoapMessage.long2CoapUint(value); } public enum CoapBlockSize { BLOCK_16 (0), BLOCK_32 (1), BLOCK_64 (2), BLOCK_128(3), BLOCK_256 (4), BLOCK_512 (5), BLOCK_1024 (6); int exp; CoapBlockSize(int exponent){ exp = exponent; } public static CoapBlockSize parse(int exponent){ switch(exponent){ case 0: return BLOCK_16; case 1: return BLOCK_32; case 2: return BLOCK_64; case 3: return BLOCK_128; case 4: return BLOCK_256; case 5: return BLOCK_512; case 6: return BLOCK_1024; default : return null; } } public int getExponent(){ return exp; } public int getSize(){ return 1 << (exp+4); } } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/messages/CoapBlockOption.java
Java
asf20
2,341
package org.ws4d.coap.messages; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public enum CoapMediaType { text_plain (0), //text/plain; charset=utf-8 link_format (40), //application/link-format xml(41), //application/xml octet_stream (42), //application/octet-stream exi(47), //application/exi json(50), //application/json UNKNOWN (-1); int mediaType; private CoapMediaType(int mediaType){ this.mediaType = mediaType; } public static CoapMediaType parse(int mediaType){ switch(mediaType){ case 0: return text_plain; case 40:return link_format; case 41:return xml; case 42:return octet_stream; case 47:return exi; case 50:return json; default: return UNKNOWN; } } public int getValue(){ return mediaType; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/messages/CoapMediaType.java
Java
asf20
869
package org.ws4d.coap.rest; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapResource implements CoapResource { /* use the logger of the resource server */ private final static Logger logger = Logger.getLogger(CoapResourceServer.class); private CoapMediaType mediaType; private String path; private byte[] value; ResourceHandler resourceHandler = null; ResourceServer serverListener = null; //could be a list of listener String resourceType = null; HashMap<CoapChannel, CoapRequest> observer = new HashMap<CoapChannel, CoapRequest>(); boolean observable = false; int observeSequenceNumber = 0; //MUST NOT greater than 0xFFFF (2 byte integer) Boolean reliableNotification = null; long expires = -1; //DEFAULT: expires never public BasicCoapResource(String path, byte[] value, CoapMediaType mediaType) { this.path = path; this.value = value; this.mediaType = mediaType; } public void setCoapMediaType(CoapMediaType mediaType) { this.mediaType = mediaType; } @Override public CoapMediaType getCoapMediaType() { return mediaType; } public String getMimeType(){ //TODO: implement return null; } @Override public String getPath() { return path; } @Override public String getShortName() { return null; } @Override public byte[] getValue() { return value; } @Override public byte[] getValue(Vector<String> query) { return value; } public void setValue(byte[] value) { this.value = value; } @Override public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public Boolean getReliableNotification() { return reliableNotification; } /* NULL lets the client decide */ public void setReliableNotification(Boolean reliableNotification) { this.reliableNotification = reliableNotification; } @Override public String toString() { return getPath(); //TODO implement } @Override public void post(byte[] data) { if (resourceHandler != null){ resourceHandler.onPost(data); } return; } @Override public void changed() { if (serverListener != null){ serverListener.resourceChanged(this); } observeSequenceNumber++; if (observeSequenceNumber > 0xFFFF){ observeSequenceNumber = 0; } /* notify all observers */ for (CoapRequest obsRequest : observer.values()) { CoapServerChannel channel = (CoapServerChannel) obsRequest.getChannel(); CoapResponse response; if (reliableNotification == null){ response = channel.createNotification(obsRequest, CoapResponseCode.Content_205, observeSequenceNumber); } else { response = channel.createNotification(obsRequest, CoapResponseCode.Content_205, observeSequenceNumber, reliableNotification); } response.setPayload(getValue()); channel.sendNotification(response); } } public void registerResourceHandler(ResourceHandler handler){ this.resourceHandler = handler; } public void registerServerListener(ResourceServer server){ this.serverListener = server; } public void unregisterServerListener(ResourceServer server){ this.serverListener = null; } @Override public boolean addObserver(CoapRequest request) { observer.put(request.getChannel(), request); return true; } public void removeObserver(CoapChannel channel){ observer.remove(channel); } public boolean isObservable(){ return observable; } public void setObservable(boolean observable) { this.observable = observable; } public int getObserveSequenceNumber(){ return observeSequenceNumber; } @Override public long expires() { return expires; } @Override public boolean isExpired(){ if (expires == -1){ return false; //-1 == never expires } if(expires < System.currentTimeMillis()){ return true; } else { return false; } } public void setExpires(long expires){ this.expires = expires; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/rest/BasicCoapResource.java
Java
asf20
4,441
package org.ws4d.coap.rest; import java.net.URI; /** * A ResourceServer provides network access to resources via a network protocol such as HTTP or CoAP. * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface ResourceServer { /** * * @param resource The resource to be handled. */ /* creates a resource. resource must not exist. if resource exists, false is returned */ public boolean createResource(Resource resource); /* returns the resource at the given path, null if no resource exists*/ public Resource readResource(String path); /* updates a resource. resource must exist. if does not resource exist, false is returned. Resource is NOT created. */ public boolean updateResource(Resource resource); /* deletes resource, returns false is resource does not exist */ public boolean deleteResource(String path); /** * Start the ResourceServer. This usually opens network ports and makes the * resources available through a certain network protocol. */ public void start() throws Exception; /** * Stops the ResourceServer. */ public void stop(); /** * Returns the Host Uri */ public URI getHostUri(); public void resourceChanged(Resource resource); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/rest/ResourceServer.java
Java
asf20
1,366
package org.ws4d.coap.rest; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.util.Enumeration; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.Constants; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoapResourceServer implements CoapServer, ResourceServer { private int port = 0; private final static Logger logger = Logger.getLogger(CoapResourceServer.class); protected HashMap<String, Resource> resources = new HashMap<String, Resource>(); private CoreResource coreResource = new CoreResource(this); public CoapResourceServer(){ logger.addAppender(new ConsoleAppender(new SimpleLayout())); logger.setLevel(Level.WARN); } public HashMap<String, Resource> getResources(){ return resources; } private void addResource(Resource resource){ resource.registerServerListener(this); resources.put(resource.getPath(), resource); coreResource.registerResource(resource); } @Override public boolean createResource(Resource resource) { if (resource==null) return false; if (!resources.containsKey(resource.getPath())) { addResource(resource); logger.info("created ressource: " + resource.getPath()); return true; } else return false; } @Override public boolean updateResource(Resource resource) { if (resource==null) return false; if (resources.containsKey(resource.getPath())) { addResource(resource); logger.info("updated ressource: " + resource.getPath()); return true; } else return false; } @Override public boolean deleteResource(String path) { if (null != resources.remove(path)) { logger.info("deleted ressource: " + path); return true; } else return false; } @Override public final Resource readResource(String path) { logger.info("read ressource: " + path); return resources.get(path); } /*corresponding to the coap spec the put is an update or create (or error)*/ public CoapResponseCode CoapResponseCode(Resource resource) { Resource res = readResource(resource.getPath()); //TODO: check results if (res == null){ createResource(resource); return CoapResponseCode.Created_201; } else { updateResource(resource); return CoapResponseCode.Changed_204; } } @Override public void start() throws Exception { start(Constants.COAP_DEFAULT_PORT); } public void start(int port) throws Exception { resources.put(coreResource.getPath(), coreResource); CoapChannelManager channelManager = BasicCoapChannelManager .getInstance(); this.port = port; channelManager.createServerListener(this, port); } @Override public void stop() { } public int getPort() { return port; } @Override public URI getHostUri() { URI hostUri = null; try { hostUri = new URI("coap://" + this.getLocalIpAddress() + ":" + getPort()); } catch (URISyntaxException e) { e.printStackTrace(); } return hostUri; } @Override public void resourceChanged(Resource resource) { logger.info("Resource changed: " + resource.getPath()); } @Override public CoapServer onAccept(CoapRequest request) { return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { CoapMessage response = null; CoapRequestCode requestCode = request.getRequestCode(); String targetPath = request.getUriPath(); //TODO make this cast safe (send internal server error if it is not a CoapResource) CoapResource resource = (CoapResource) readResource(targetPath); /* TODO: check return values of create, read, update and delete * TODO: implement forbidden * TODO: implement ETag * TODO: implement If-Match... * TODO: check for well known addresses (do not override well known core) * TODO: check that path begins with "/" */ switch (requestCode) { case GET: if (resource != null) { // URI queries Vector<String> uriQueries = request.getUriQuery(); final byte[] responseValue; if (uriQueries != null) { responseValue = resource.getValue(uriQueries); } else { responseValue = resource.getValue(); } response = channel.createResponse(request, CoapResponseCode.Content_205, resource.getCoapMediaType()); response.setPayload(responseValue); if (request.getObserveOption() != null){ /*client wants to observe this resource*/ if (resource.addObserver(request)){ /* successfully added observer */ response.setObserveOption(resource.getObserveSequenceNumber()); } } } else { response = channel.createResponse(request, CoapResponseCode.Not_Found_404); } break; case DELETE: /* CoAP: "A 2.02 (Deleted) response SHOULD be sent on success or in case the resource did not exist before the request.*/ deleteResource(targetPath); response = channel.createResponse(request, CoapResponseCode.Deleted_202); break; case POST: if (resource != null){ resource.post(request.getPayload()); response = channel.createResponse(request, CoapResponseCode.Changed_204); } else { /* if the resource does not exist, a new resource will be created */ createResource(parseRequest(request)); response = channel.createResponse(request, CoapResponseCode.Created_201); } break; case PUT: if (resource == null){ /* create*/ createResource(parseRequest(request)); response = channel.createResponse(request,CoapResponseCode.Created_201); } else { /*update*/ updateResource(parseRequest(request)); response = channel.createResponse(request, CoapResponseCode.Changed_204); } break; default: response = channel.createResponse(request, CoapResponseCode.Bad_Request_400); break; } channel.sendMessage(response); } private CoapResource parseRequest(CoapRequest request) { CoapResource resource = new BasicCoapResource(request.getUriPath(), request.getPayload(), request.getContentType()); // TODO add content type return resource; } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { logger.error("Separate response failed but server never used separate responses"); } protected String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf .getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { } return null; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/rest/CoapResourceServer.java
Java
asf20
7,607
package org.ws4d.coap.rest; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.messages.CoapMediaType; /** * Well-Known CoRE support (draft-ietf-core-link-format-05) * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class CoreResource implements CoapResource { /* use the logger of the resource server */ private final static Logger logger = Logger.getLogger(CoapResourceServer.class); private final static String uriPath = "/.well-known/core"; private HashMap<Resource, String> coreStrings = new HashMap<Resource, String>(); ResourceServer serverListener = null; CoapResourceServer server = null; public CoreResource (CoapResourceServer server){ this.server = server; } /*Hide*/ @SuppressWarnings("unused") private CoreResource (){ } @Override public String getMimeType() { return null; } @Override public String getPath() { return uriPath; } @Override public String getShortName() { return getPath(); } @Override public byte[] getValue() { return buildCoreString(null).getBytes(); } public void registerResource(Resource resource) { if (resource != null) { StringBuilder coreLine = new StringBuilder(); coreLine.append("<"); coreLine.append(resource.getPath()); coreLine.append(">"); // coreLine.append(";ct=???"); coreLine.append(";rt=\"" + resource.getResourceType() + "\""); // coreLine.append(";if=\"observations\""); coreStrings.put(resource, coreLine.toString()); } } private String buildCoreString(String resourceType) { /* TODO: implement filtering also with ct and if*/ HashMap<String, Resource> resources = server.getResources(); StringBuilder returnString = new StringBuilder(); for (Resource resource : resources.values()){ if (resourceType == null || resource.getResourceType() == resourceType) { returnString.append("<"); returnString.append(resource.getPath()); returnString.append(">"); // coreLine.append(";ct=???"); if (resource.getResourceType() != null) { returnString.append(";rt=\"" + resource.getResourceType() + "\""); } // coreLine.append(";if=\"observations\""); returnString.append(","); } } return returnString.toString(); } @Override public byte[] getValue(Vector<String> queries) { for (String query : queries) { if (query.startsWith("rt=")) return buildCoreString(query.substring(3)).getBytes(); } return getValue(); } @Override public String getResourceType() { // TODO implement return null; } @Override public CoapMediaType getCoapMediaType() { return CoapMediaType.link_format; } @Override public void post(byte[] data) { /* nothing happens in case of a post */ return; } @Override public void changed() { } @Override public void registerServerListener(ResourceServer server) { this.serverListener = server; } @Override public void unregisterServerListener(ResourceServer server) { this.serverListener = null; } @Override public boolean addObserver(CoapRequest request) { // TODO: implement. Is this resource observeable? (should) return false; } @Override public void removeObserver(CoapChannel channel) { // TODO: implement. Is this resource observeable? (should) } @Override public boolean isObservable() { return false; } public int getObserveSequenceNumber(){ return 0; } @Override public long expires() { /* expires never */ return -1; } @Override public boolean isExpired() { return false; } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/rest/CoreResource.java
Java
asf20
3,985
package org.ws4d.coap.rest; import java.util.Vector; /** * A resource known from the REST architecture style. A resource has a type, * name and data associated with it. * * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public interface Resource { /** * Get the MIME Type of the resource (e.g., "application/xml") * @return The MIME Type of this resource as String. */ public String getMimeType(); /** * Get the unique name of this resource * @return The unique name of the resource. */ public String getPath(); public String getShortName(); public byte[] getValue(); public byte[] getValue(Vector<String> query); //TODO: bad api: no return value public void post(byte[] data); public String getResourceType(); public void registerServerListener(ResourceServer server); public void unregisterServerListener(ResourceServer server); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/rest/Resource.java
Java
asf20
1,011
package org.ws4d.coap.rest; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface ResourceHandler { public void onPost(byte[] data); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/rest/ResourceHandler.java
Java
asf20
181
package org.ws4d.coap.rest; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.messages.CoapMediaType; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapResource extends Resource { /* returns the CoAP Media Type */ public CoapMediaType getCoapMediaType(); /* called by the application, when the resource state changed -> used for observation */ public void changed(); /* called by the server to register a new observer, returns false if resource is not observable */ public boolean addObserver(CoapRequest request); /* removes an observer from the list */ public void removeObserver(CoapChannel channel); /* returns if the resource is observable */ public boolean isObservable(); /* returns if the resource is observable */ public int getObserveSequenceNumber(); /* returns the unix time when resource expires, -1 for never */ public long expires(); public boolean isExpired(); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/rest/CoapResource.java
Java
asf20
1,070
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ package org.ws4d.coap; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public final class Constants { public final static int MESSAGE_ID_MIN = 0; public final static int MESSAGE_ID_MAX = 65535; public final static int COAP_MESSAGE_SIZE_MAX = 1152; public final static int COAP_DEFAULT_PORT = 5683; public final static int COAP_DEFAULT_MAX_AGE_S = 60; public final static int COAP_DEFAULT_MAX_AGE_MS = COAP_DEFAULT_MAX_AGE_S * 1000; }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/Constants.java
Java
asf20
1,164
#!/bin/bash # run "./runTests.sh" for verbose output # for short output, run # ./runTests.sh | grep FAILED # ./runTests.sh | grep PASSED #master branch SERVER_CLASS="org.ws4d.coap.test.PlugtestServer" CLIENT_CLASS="org.ws4d.coap.test.PlugtestClient" CLASSPATH="bin/:../ws4d-jcoap/bin" LOG_DIR="log" REF_LOG_DIR="logref" EXEC_SERVER="" EXEC_CLIENT="" build_exec_string() { TEST=$1 EXEC_SERVER="java -cp $CLASSPATH $SERVER_CLASS $TEST > $LOG_DIR/${TEST}_SERVER.txt &" EXEC_CLIENT="java -cp $CLASSPATH $CLIENT_CLASS $TEST > $LOG_DIR/${TEST}_CLIENT.txt &" } run_test() { TEST=$1 echo "Running Test $TEST" build_exec_string $TEST eval $EXEC_SERVER eval $EXEC_CLIENT sleep 3 killall java >/dev/null 2>/dev/null sleep 1 diff -i -b -B -q $LOG_DIR/${TEST}_SERVER.txt $REF_LOG_DIR/${TEST}_SERVER.txt if [ ! $? -eq 0 ] then echo "FAILED Server $TEST" else echo "PASSED Server $TEST" fi diff -i -b -B -q $LOG_DIR/${TEST}_CLIENT.txt $REF_LOG_DIR/${TEST}_CLIENT.txt if [ ! $? -eq 0 ] then echo "FAILED Client $TEST" else echo "PASSED Client $TEST" fi } killall java >/dev/null 2>/dev/null sleep 1 mkdir -p $LOG_DIR # CoAP CORE Tests for i in 1 2 3 4 5 6 7 8 9 do run_test TD_COAP_CORE_0$i done for i in 10 11 12 13 14 15 16 do run_test TD_COAP_CORE_$i done # CoAP Link Tests #for i in 1 2 #do # run_test TD_COAP_LINK_0$i #done # CoAP Block Tests #for i in 1 2 3 4 #do # run_test TD_COAP_BLOCK_0$i #done # CoAP Observation Tests #for i in 1 2 3 4 5 #do # run_test TD_COAP_OBS_0$i #done
1060413246zhaohong-
ws4d-jcoap-plugtest/runTests.sh
Shell
asf20
1,550
/** * Server Application for Plugtest 2012, Paris, France * * Execute with argument Identifier (e.g., TD_COAP_CORE_01) */ package org.ws4d.coap.test; import java.util.logging.Level; import java.util.logging.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.rest.CoapResourceServer; import org.ws4d.coap.test.resources.LongPathResource; import org.ws4d.coap.test.resources.QueryResource; import org.ws4d.coap.test.resources.TestResource; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class PlugtestServer { private static PlugtestServer plugtestServer; private CoapResourceServer resourceServer; private static Logger logger = Logger .getLogger(BasicCoapSocketHandler.class.getName()); /** * @param args */ public static void main(String[] args) { if (args.length > 1 || args.length < 1) { System.err.println("illegal number of arguments"); System.exit(1); } logger.setLevel(Level.WARNING); plugtestServer = new PlugtestServer(); plugtestServer.start(args[0]); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("PlugtestServer is now stopping."); System.out.println("===END==="); } }); } public void start(String testId) { System.out.println("===Run Test Server: " + testId + "==="); init(); if (testId.equals("TD_COAP_CORE_01")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_02")) { /* Nothing to setup, POST creates new resource */ run(); } else if (testId.equals("TD_COAP_CORE_03")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_04")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_05")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_06")) { /* Nothing to setup, POST creates new resource */ run(); } else if (testId.equals("TD_COAP_CORE_07")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_08")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_09")) { /* * === SPECIAL CASE: Separate Response: for these tests we cannot * use the resource server */ PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer(); server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS); } else if (testId.equals("TD_COAP_CORE_10")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_11")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_12")) { resourceServer.createResource(new LongPathResource()); run(); } else if (testId.equals("TD_COAP_CORE_13")) { resourceServer.createResource(new QueryResource()); run(); } else if (testId.equals("TD_COAP_CORE_14")) { resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_CORE_15")) { /* * === SPECIAL CASE: Separate Response: for these tests we cannot * use the resource server */ PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer(); server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS); } else if (testId.equals("TD_COAP_CORE_16")) { /* * === SPECIAL CASE: Separate Response: for these tests we cannot * use the resource server */ PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer(); server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS); } else if (testId.equals("TD_COAP_LINK_01")) { resourceServer.createResource(new LongPathResource()); resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_LINK_02")) { resourceServer.createResource(new LongPathResource()); resourceServer.createResource(new TestResource()); run(); } else if (testId.equals("TD_COAP_BLOCK_01")) { } else if (testId.equals("TD_COAP_BLOCK_02")) { } else if (testId.equals("TD_COAP_BLOCK_03")) { } else if (testId.equals("TD_COAP_BLOCK_04")) { } else if (testId.equals("TD_COAP_OBS_01")) { } else if (testId.equals("TD_COAP_OBS_02")) { } else if (testId.equals("TD_COAP_OBS_03")) { } else if (testId.equals("TD_COAP_OBS_04")) { } else if (testId.equals("TD_COAP_OBS_05")) { } else { System.out.println("unknown test case"); System.exit(-1); } } private void init() { BasicCoapChannelManager.getInstance().setMessageId(2000); if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); } private void run() { try { resourceServer.start(); } catch (Exception e) { e.printStackTrace(); } } }
1060413246zhaohong-
ws4d-jcoap-plugtest/src/org/ws4d/coap/test/PlugtestServer.java
Java
asf20
5,128
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ package org.ws4d.coap.test; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; public class PlugtestSeparateResponseCoapServer implements CoapServer { private static final int PORT = 5683; static int counter = 0; CoapResponse response = null; CoapServerChannel channel = null; int separateResponseTimeMs = 4000; public void start(int separateResponseTimeMs){ CoapChannelManager channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(this, PORT); this.separateResponseTimeMs = separateResponseTimeMs; } @Override public CoapServer onAccept(CoapRequest request) { System.out.println("Accept connection..."); return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { System.out.println("Received message: " + request.toString()); this.channel = channel; response = channel.createSeparateResponse(request, CoapResponseCode.Content_205); (new Thread( new SendDelayedResponse())).start(); } public class SendDelayedResponse implements Runnable { public void run() { response.setContentType(CoapMediaType.text_plain); response.setPayload("payload...".getBytes()); try { Thread.sleep(separateResponseTimeMs); } catch (InterruptedException e) { e.printStackTrace(); } channel.sendSeparateResponse(response); System.out.println("Send separate Response: " + response.toString()); } } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { System.out.println("Separate Response failed"); } }
1060413246zhaohong-
ws4d-jcoap-plugtest/src/org/ws4d/coap/test/PlugtestSeparateResponseCoapServer.java
Java
asf20
2,650
/** * Server Application for Plugtest 2012, Paris, France * * Execute with argument Identifier (e.g., TD_COAP_CORE_01) */ package org.ws4d.coap.test; import java.util.logging.Level; import java.util.logging.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.rest.CoapResourceServer; import org.ws4d.coap.test.resources.LongPathResource; import org.ws4d.coap.test.resources.QueryResource; import org.ws4d.coap.test.resources.TestResource; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class CompletePlugtestServer { private static CompletePlugtestServer plugtestServer; private CoapResourceServer resourceServer; private static Logger logger = Logger .getLogger(BasicCoapSocketHandler.class.getName()); /** * @param args */ public static void main(String[] args) { logger.setLevel(Level.WARNING); plugtestServer = new CompletePlugtestServer(); plugtestServer.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("PlugtestServer is now stopping."); System.out.println("===END==="); } }); } public void start() { System.out.println("===Run Test Server ==="); init(); resourceServer.createResource(new TestResource()); resourceServer.createResource(new LongPathResource()); resourceServer.createResource(new QueryResource()); run(); } private void init() { BasicCoapChannelManager.getInstance().setMessageId(2000); if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); } private void run() { try { resourceServer.start(); } catch (Exception e) { e.printStackTrace(); } } }
1060413246zhaohong-
ws4d-jcoap-plugtest/src/org/ws4d/coap/test/CompletePlugtestServer.java
Java
asf20
1,894
/** * Client Application for Plugtest 2012, Paris, France * * Execute with argument Identifier (e.g., TD_COAP_CORE_01) */ package org.ws4d.coap.test; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.connection.BasicCoapSocketHandler; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Nico Laum <nico.laum@uni-rostock.de> * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class PlugtestClient implements CoapClient{ CoapChannelManager channelManager = null; CoapClientChannel clientChannel = null; CoapRequest request = null; private static Logger logger = Logger.getLogger(BasicCoapSocketHandler.class.getName()); boolean exitAfterResponse = true; String serverAddress = null; int serverPort = 0; String filter = null; public static void main(String[] args) { if (args.length > 4 || args.length < 4) { System.err.println("illegal number of arguments"); System.exit(1); } logger.setLevel(Level.WARNING); PlugtestClient client = new PlugtestClient(); client.start(args[0], Integer.parseInt(args[1]), args[2], args[3]); } public void start(String serverAddress, int serverPort, String testcase, String filter){ System.out.println("===START=== (Run Test Client: " + testcase + ")"); String testId = testcase; this.serverAddress = serverAddress; this.serverPort = serverPort; this.filter = filter; if (testId.equals("TD_COAP_CORE_01")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_02")) { init(true, CoapRequestCode.POST); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_03")) { init(true, CoapRequestCode.PUT); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_04")) { init(true, CoapRequestCode.DELETE); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_05")) { init(false, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_06")) { init(false, CoapRequestCode.POST); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_07")) { init(false, CoapRequestCode.PUT); request.setUriPath("/test"); request.setPayload("Content of new resource /test"); request.setContentType(CoapMediaType.text_plain); } else if (testId.equals("TD_COAP_CORE_08")) { init(false, CoapRequestCode.DELETE); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_09")) { init(true, CoapRequestCode.GET); request.setUriPath("/separate"); } else if (testId.equals("TD_COAP_CORE_10")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); request.setToken("AABBCCDD".getBytes()); } else if (testId.equals("TD_COAP_CORE_11")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_12")) { init(true, CoapRequestCode.GET); request.setUriPath("/seg1/seg2/seg3"); } else if (testId.equals("TD_COAP_CORE_13")) { init(true, CoapRequestCode.GET); request.setUriPath("/query"); request.setUriQuery("first=1&second=2&third=3"); } else if (testId.equals("TD_COAP_CORE_14")) { init(true, CoapRequestCode.GET); request.setUriPath("/test"); } else if (testId.equals("TD_COAP_CORE_15")) { init(true, CoapRequestCode.GET); request.setUriPath("/separate"); } else if (testId.equals("TD_COAP_CORE_16")) { init(false, CoapRequestCode.GET); request.setUriPath("/separate"); } else if (testId.equals("TD_COAP_LINK_01")) { init(false, CoapRequestCode.GET); request.setUriPath("/.well-known/core"); } else if (testId.equals("TD_COAP_LINK_02")) { init(false, CoapRequestCode.GET); request.setUriPath("/.well-known/core"); request.setUriQuery("rt=" + this.filter); } else { System.out.println("===Failure=== (unknown test case)"); System.exit(-1); } run(); } public void init(boolean reliable, CoapRequestCode requestCode) { channelManager = BasicCoapChannelManager.getInstance(); channelManager.setMessageId(1000); try { clientChannel = channelManager.connect(this, InetAddress.getByName(this.serverAddress), this.serverPort); if (clientChannel == null){ System.out.println("Connect failed."); System.exit(-1); } request = clientChannel.createRequest(reliable, requestCode); } catch (UnknownHostException e) { e.printStackTrace(); System.exit(-1); } } public void run() { if(request.getPayload() != null){ System.out.println("Send Request: " + request.toString() + " (" + new String(request.getPayload()) +")"); }else { System.out.println("Send Request: " + request.toString()); } clientChannel.sendMessage(request); } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { System.out.println("Connection Failed"); System.exit(-1); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { if (response.getPayload() != null){ System.out.println("Response: " + response.toString() + " (" + new String(response.getPayload()) +")"); } else { System.out.println("Response: " + response.toString()); } if (exitAfterResponse){ System.out.println("===END==="); System.exit(0); } } public class WaitAndExit implements Runnable { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("===END==="); System.exit(0); } } }
1060413246zhaohong-
ws4d-jcoap-plugtest/src/org/ws4d/coap/test/PlugtestClient.java
Java
asf20
6,486
package org.ws4d.coap.client; import java.net.InetAddress; import java.net.UnknownHostException; import org.ws4d.coap.Constants; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapBlockClient implements CoapClient { private static final String SERVER_ADDRESS = "129.132.15.80"; private static final int PORT = Constants.COAP_DEFAULT_PORT; static int counter = 0; CoapChannelManager channelManager = null; CoapClientChannel clientChannel = null; public static void main(String[] args) { System.out.println("Start CoAP Client"); BasicCoapBlockClient client = new BasicCoapBlockClient(); client.channelManager = BasicCoapChannelManager.getInstance(); client.runTestClient(); } public void runTestClient(){ try { clientChannel = channelManager.connect(this, InetAddress.getByName(SERVER_ADDRESS), PORT); CoapRequest coapRequest = clientChannel.createRequest(true, CoapRequestCode.GET); coapRequest.setUriPath("/large"); clientChannel.setMaxReceiveBlocksize(CoapBlockSize.BLOCK_64); clientChannel.sendMessage(coapRequest); System.out.println("Sent Request"); } catch (UnknownHostException e) { e.printStackTrace(); } } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { System.out.println("Connection Failed"); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { System.out.println("Received response"); System.out.println(response.toString()); System.out.println(new String(response.getPayload())); } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/client/BasicCoapBlockClient.java
Java
asf20
2,187
package org.ws4d.coap.client; import java.net.InetAddress; import java.net.UnknownHostException; import org.ws4d.coap.Constants; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapClient; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapClient implements CoapClient { private static final String SERVER_ADDRESS = "localhost"; private static final int PORT = Constants.COAP_DEFAULT_PORT; static int counter = 0; CoapChannelManager channelManager = null; CoapClientChannel clientChannel = null; public static void main(String[] args) { System.out.println("Start CoAP Client"); BasicCoapClient client = new BasicCoapClient(); client.channelManager = BasicCoapChannelManager.getInstance(); client.runTestClient(); } public void runTestClient(){ try { clientChannel = channelManager.connect(this, InetAddress.getByName(SERVER_ADDRESS), PORT); CoapRequest coapRequest = clientChannel.createRequest(true, CoapRequestCode.GET); // coapRequest.setContentType(CoapMediaType.octet_stream); // coapRequest.setToken("ABCD".getBytes()); // coapRequest.setUriHost("123.123.123.123"); // coapRequest.setUriPort(1234); // coapRequest.setUriPath("/sub1/sub2/sub3/"); // coapRequest.setUriQuery("a=1&b=2&c=3"); // coapRequest.setProxyUri("http://proxy.org:1234/proxytest"); clientChannel.sendMessage(coapRequest); System.out.println("Sent Request"); } catch (UnknownHostException e) { e.printStackTrace(); } } @Override public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) { System.out.println("Connection Failed"); } @Override public void onResponse(CoapClientChannel channel, CoapResponse response) { System.out.println("Received response"); } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/client/BasicCoapClient.java
Java
asf20
2,242
package org.ws4d.coap.udp; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class UDPRelay { public static final int SERVER_PORT = 6000; public static final int CLIENT_PORT = 8000; public static final int UDP_BUFFER_SIZE = 66000; // max UDP size = 65535 public static void main(String[] args) { if (args.length < 2){ System.out.println("expected parameter: server host and port, e.g. 192.168.1.1 1234"); System.exit(-1); } UDPRelay relay = new UDPRelay(); relay.run(new InetSocketAddress(args[0], Integer.parseInt(args[1]))); } private DatagramChannel serverChannel = null; private DatagramChannel clientChannel = null; ByteBuffer serverBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE); ByteBuffer clientBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE); Selector selector = null; InetSocketAddress clientAddr = null; public void run(InetSocketAddress serverAddr) { try { serverChannel = DatagramChannel.open(); serverChannel.socket().bind(new InetSocketAddress(SERVER_PORT)); serverChannel.configureBlocking(false); serverChannel.connect(serverAddr); clientChannel = DatagramChannel.open(); clientChannel.socket().bind(new InetSocketAddress(CLIENT_PORT)); clientChannel.configureBlocking(false); try { selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_READ); clientChannel.register(selector, SelectionKey.OP_READ); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); System.out.println("Initialization failed, Shut down"); System.exit(-1); } System.out.println("Start UDP Realy on Server Port " + SERVER_PORT + " and Client Port " + CLIENT_PORT); int serverLen = 0; while (true) { /* Receive Packets */ InetSocketAddress tempClientAddr = null; try { clientBuffer.clear(); tempClientAddr = (InetSocketAddress) clientChannel.receive(clientBuffer); clientBuffer.flip(); serverBuffer.clear(); serverLen = serverChannel.read(serverBuffer); serverBuffer.flip(); } catch (IOException e1) { e1.printStackTrace(); System.out.println("Read failed"); } /* forward/send packets client -> server*/ if (tempClientAddr != null) { /* the client address is obtained automatically by the first request of the client * clientAddr is the last known valid address of the client */ clientAddr = tempClientAddr; try { serverChannel.write(clientBuffer); System.out.println("Forwarded Message client ("+clientAddr.getHostName()+" "+clientAddr.getPort() + ") -> server (" + serverAddr.getHostName()+" " + serverAddr.getPort() + "): " + clientBuffer.limit() + " bytes"); } catch (IOException e) { e.printStackTrace(); System.out.println("Send failed"); } } /* forward/send packets server -> client*/ if (serverLen > 0) { try { clientChannel.send(serverBuffer, clientAddr); System.out.println("Forwarded Message server ("+serverAddr.getHostName()+" "+serverAddr.getPort() + ") -> client (" + clientAddr.getHostName()+" " + clientAddr.getPort() + "): " + serverBuffer.limit() + " bytes"); } catch (IOException e) { e.printStackTrace(); System.out.println("Send failed"); } } /* Select */ try { selector.select(2000); } catch (IOException e) { e.printStackTrace(); System.out.println("select failed"); } } } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/udp/UDPRelay.java
Java
asf20
3,828
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ package org.ws4d.coap.server; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapServer implements CoapServer { private static final int PORT = 5683; static int counter = 0; public static void main(String[] args) { System.out.println("Start CoAP Server on port " + PORT); BasicCoapServer server = new BasicCoapServer(); CoapChannelManager channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(server, PORT); } @Override public CoapServer onAccept(CoapRequest request) { System.out.println("Accept connection..."); return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { System.out.println("Received message: " + request.toString()+ " URI: " + request.getUriPath()); CoapMessage response = channel.createResponse(request, CoapResponseCode.Content_205); response.setContentType(CoapMediaType.text_plain); response.setPayload("payload...".getBytes()); if (request.getObserveOption() != null){ System.out.println("Client wants to observe this resource."); } response.setObserveOption(1); channel.sendMessage(response); } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { System.out.println("Separate response transmission failed."); } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/server/BasicCoapServer.java
Java
asf20
2,460
package org.ws4d.coap.server; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.rest.BasicCoapResource; import org.ws4d.coap.rest.CoapResourceServer; import org.ws4d.coap.rest.ResourceHandler; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * */ public class CoapSampleResourceServer { private static CoapSampleResourceServer sampleServer; private CoapResourceServer resourceServer; private static Logger logger = Logger .getLogger(CoapSampleResourceServer.class.getName()); /** * @param args */ public static void main(String[] args) { logger.addAppender(new ConsoleAppender(new SimpleLayout())); logger.setLevel(Level.INFO); logger.info("Start Sample Resource Server"); sampleServer = new CoapSampleResourceServer(); sampleServer.run(); } private void run() { if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); /* Show detailed logging of Resource Server*/ Logger resourceLogger = Logger.getLogger(CoapResourceServer.class.getName()); resourceLogger.setLevel(Level.ALL); /* add resources */ BasicCoapResource light = new BasicCoapResource("/test/light", "Content".getBytes(), CoapMediaType.text_plain); light.registerResourceHandler(new ResourceHandler() { @Override public void onPost(byte[] data) { System.out.println("Post to /test/light"); } }); light.setResourceType("light"); light.setObservable(true); resourceServer.createResource(light); try { resourceServer.start(); } catch (Exception e) { e.printStackTrace(); } int counter = 0; while(true){ try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } counter++; light.setValue(((String)"Message #" + counter).getBytes()); light.changed(); } } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/server/CoapSampleResourceServer.java
Java
asf20
2,027
/* Copyright [2011] [University of Rostock] * * 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. *****************************************************************************/ package org.ws4d.coap.server; import org.ws4d.coap.connection.BasicCoapChannelManager; import org.ws4d.coap.interfaces.CoapChannelManager; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class SeparateResponseCoapServer implements CoapServer { private static final int PORT = 5683; static int counter = 0; CoapResponse response = null; CoapServerChannel channel = null; public static void main(String[] args) { System.out.println("Start CoAP Server on port " + PORT); SeparateResponseCoapServer server = new SeparateResponseCoapServer(); CoapChannelManager channelManager = BasicCoapChannelManager.getInstance(); channelManager.createServerListener(server, PORT); } @Override public CoapServer onAccept(CoapRequest request) { System.out.println("Accept connection..."); return this; } @Override public void onRequest(CoapServerChannel channel, CoapRequest request) { System.out.println("Received message: " + request.toString()); this.channel = channel; response = channel.createSeparateResponse(request, CoapResponseCode.Content_205); Thread t = new Thread( new SendDelayedResponse() ); t.start(); } public class SendDelayedResponse implements Runnable { public void run() { response.setContentType(CoapMediaType.text_plain); response.setPayload("payload...".getBytes()); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } channel.sendSeparateResponse(response); } } @Override public void onSeparateResponseFailed(CoapServerChannel channel) { System.out.println("Separate Response failed"); } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/server/SeparateResponseCoapServer.java
Java
asf20
2,697
/* * 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(); } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ByteContentListener.java
Java
asf20
2,196
/* * 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 org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class ProxyMessageContext { /*unique for reqMessageID, remoteHost, remotePort*/ /* * Server Client * inRequest +--------+ TRANSFORM +--------+ outRequest * ------------->| |-----|||---->| |-------------> * | | | | * outResponse | | TRANSFORM | | inResponse * <-------------| |<----|||-----| |<------------- * +--------+ +--------+ * */ /* incomming messages */ private CoapRequest inCoapRequest; //the coapRequest of the origin client (maybe translated) private HttpRequest inHttpRequest; //the httpRequest of the origin client (maybe translated) private CoapResponse inCoapResponse; //the coap response of the final server private HttpResponse inHttpResponse; //the http response of the final server /* generated outgoing messages */ private CoapResponse outCoapResponse; //the coap response send to the client private CoapRequest outCoapRequest; private HttpResponse outHttpResponse; private HttpUriRequest outHttpRequest; /* trigger and channels*/ private CoapClientChannel outCoapClientChannel; NHttpResponseTrigger trigger; //needed by http /* corresponding cached resource*/ private ProxyResource resource; private URI uri; private InetAddress clientAddress; private int clientPort; private InetAddress serverAddress; private int serverPort; /* is true if a translation was done (always true for incoming http requests)*/ private boolean translate; //translate from coap to http /* indicates that the response comes from the cache*/ private boolean cached = false; /* in case of a HTTP Head this is true, GET and HEAD are both mapped to CoAP GET */ private boolean httpHeadMethod = false; /* times */ long requestTime; long responseTime; public ProxyMessageContext(CoapRequest request, boolean translate, URI uri) { this.inCoapRequest = request; this.translate = translate; this.uri = uri; } public ProxyMessageContext(HttpRequest request, boolean translate, URI uri, NHttpResponseTrigger trigger) { this.inHttpRequest = request; this.translate = translate; this.uri = uri; this.trigger = trigger; } public boolean isCoapRequest(){ return inCoapRequest != null; } public boolean isHttpRequest(){ return inHttpRequest != null; } public CoapRequest getInCoapRequest() { return inCoapRequest; } public void setInCoapRequest(CoapRequest inCoapRequest) { this.inCoapRequest = inCoapRequest; } public HttpRequest getInHttpRequest() { return inHttpRequest; } public void setInHttpRequest(HttpRequest inHttpRequest) { this.inHttpRequest = inHttpRequest; } public CoapResponse getInCoapResponse() { return inCoapResponse; } public void setInCoapResponse(CoapResponse inCoapResponse) { this.inCoapResponse = inCoapResponse; } public HttpResponse getInHttpResponse() { return inHttpResponse; } public void setInHttpResponse(HttpResponse inHttpResponse) { this.inHttpResponse = inHttpResponse; } public CoapResponse getOutCoapResponse() { return outCoapResponse; } public void setOutCoapResponse(CoapResponse outCoapResponse) { this.outCoapResponse = outCoapResponse; } public CoapRequest getOutCoapRequest() { return outCoapRequest; } public void setOutCoapRequest(CoapRequest outCoapRequest) { this.outCoapRequest = outCoapRequest; } public HttpResponse getOutHttpResponse() { return outHttpResponse; } public void setOutHttpResponse(HttpResponse outHttpResponse) { this.outHttpResponse = outHttpResponse; } public HttpUriRequest getOutHttpRequest() { return outHttpRequest; } public void setOutHttpRequest(HttpUriRequest outHttpRequest) { this.outHttpRequest = outHttpRequest; } public CoapClientChannel getOutCoapClientChannel() { return outCoapClientChannel; } public void setOutCoapClientChannel(CoapClientChannel outClientChannel) { this.outCoapClientChannel = outClientChannel; } public InetAddress getClientAddress() { return clientAddress; } public void setClientAddress(InetAddress clientAddress, int clientPort) { this.clientAddress = clientAddress; this.clientPort = clientPort; } public InetAddress getServerAddress() { return serverAddress; } public void setServerAddress(InetAddress serverAddress, int serverPort) { this.serverAddress = serverAddress; this.serverPort = serverPort; } public int getClientPort() { return clientPort; } public int getServerPort() { return serverPort; } public boolean isTranslate() { return translate; } public void setTranslatedCoapRequest(CoapRequest request) { this.inCoapRequest = request; } public void setTranslatedHttpRequest(HttpRequest request) { this.inHttpRequest = request; } public URI getUri() { return uri; } public NHttpResponseTrigger getTrigger() { return trigger; } public boolean isCached() { return cached; } public void setCached(boolean cached) { this.cached = cached; } public ProxyResource getResource() { return resource; } public void setResource(ProxyResource resource) { this.resource = resource; } public void setHttpHeadMethod(boolean httpHeadMethod) { this.httpHeadMethod = httpHeadMethod; } public boolean isHttpHeadMethod() { return httpHeadMethod; } public long getRequestTime() { return requestTime; } public void setRequestTime(long requestTime) { this.requestTime = requestTime; } public long getResponseTime() { return responseTime; } public void setResponseTime(long responseTime) { this.responseTime = responseTime; } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ProxyMessageContext.java
Java
asf20
6,941
package org.ws4d.coap.proxy; import org.apache.log4j.Logger; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.rest.BasicCoapResource; public class ProxyResource extends BasicCoapResource { static Logger logger = Logger.getLogger(Proxy.class); private ProxyResourceKey key = null; public ProxyResource(String path, byte[] value, CoapMediaType mediaType) { super(path, value, mediaType); } public ProxyResourceKey getKey() { return key; } public void setKey(ProxyResourceKey key) { this.key = key; } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ProxyResource.java
Java
asf20
569
/* * 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 java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerRegistry; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.log4j.Logger; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> * * TODO: IMPROVE Async Server Implementation, avoid ModifiedAsyncNHttpServiceHandler and deprecated function calls */ public class HttpServerNIO extends Thread{ static Logger logger = Logger.getLogger(Proxy.class); static private int PORT = 8080; ProxyMapper mapper = ProxyMapper.getInstance(); //interface-function for other classes/modules public void sendResponse(ProxyMessageContext context) { HttpResponse httpResponse = context.getOutHttpResponse(); NHttpResponseTrigger trigger = context.getTrigger(); trigger.submitResponse(httpResponse); } public void run() { this.setName("HTTP_NIO_Server"); //parameters for connection HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 50000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); //needed by framework, don't need any processors except the connection-control HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseConnControl() }); //create own service-handler with bytecontentlistener-class ModifiedAsyncNHttpServiceHandler handler = new ModifiedAsyncNHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); // Set up request handlers, use the same request-handler for all uris NHttpRequestHandlerRegistry reqistry = new NHttpRequestHandlerRegistry(); reqistry.register("*", new ProxyHttpRequestHandler()); handler.setHandlerResolver(reqistry); try { //create and start responder-thread //ioreactor is used by nio-framework to listen and react to http connections //2 dispatcher-threads are used to do the work ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params); IOEventDispatch ioeventdispatch = new DefaultServerIOEventDispatch(handler, params); ioReactor.listen(new InetSocketAddress(PORT)); ioReactor.execute(ioeventdispatch); } catch (IOReactorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } static class ProxyHttpRequestHandler implements NHttpRequestHandler { public ProxyHttpRequestHandler() { super(); } @Override public ConsumingNHttpEntity entityRequest( HttpEntityEnclosingRequest arg0, HttpContext arg1) throws HttpException, IOException { return null; } //handle() is called when a request is received //response is automatically generated by HttpProcessor, but use response from mapper //trigger is used for asynchronous response, see java-documentation @Override public void handle(final HttpRequest request, final HttpResponse response, final NHttpResponseTrigger trigger, HttpContext con) throws HttpException, IOException { logger.info("incomming HTTP request"); URI uri = ProxyMapper.resolveHttpRequestUri(request); if (uri != null){ InetAddress serverAddress = InetAddress.getByName(uri.getHost()); //FIXME: blocking operation??? int serverPort = uri.getPort(); if (serverPort == -1) { serverPort = org.ws4d.coap.Constants.COAP_DEFAULT_PORT; } /* translate always */ ProxyMessageContext context = new ProxyMessageContext(request, true, uri, trigger); context.setServerAddress(serverAddress, serverPort); ProxyMapper.getInstance().handleHttpServerRequest(context); } else { trigger.submitResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "Bad Header: Host")); } } } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/HttpServerNIO.java
Java
asf20
6,394
/* * 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 org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.Constants; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class Proxy { static Logger logger = Logger.getLogger(Proxy.class); static int defaultCachingTime = Constants.COAP_DEFAULT_MAX_AGE_S; public static void main(String[] args) { CommandLineParser cmdParser = new GnuParser(); Options options = new Options(); /* Add command line options */ options.addOption("c", "default-cache-time", true, "Default caching time in seconds"); CommandLine cmd = null; try { cmd = cmdParser.parse(options, args); } catch (ParseException e) { System.out.println( "Unexpected exception:" + e.getMessage() ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "jCoAP-Proxy", options ); System.exit(-1); } /* evaluate command line */ if(cmd.hasOption("c")) { try { defaultCachingTime = Integer.parseInt(cmd.getOptionValue("c")); if (defaultCachingTime == 0){ ProxyMapper.getInstance().setCacheEnabled(false); } System.out.println("Set caching time to " + cmd.getOptionValue("c") + " seconds (0 disables the cache)"); } catch (NumberFormatException e) { System.out.println( "Unexpected exception:" + e.getMessage() ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "jCoAP-Proxy", options ); System.exit(-1); } } logger.addAppender(new ConsoleAppender(new SimpleLayout())); // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF: logger.setLevel(Level.ALL); HttpServerNIO httpserver = new HttpServerNIO(); HttpClientNIO httpclient = new HttpClientNIO(); CoapClientProxy coapclient = new CoapClientProxy(); CoapServerProxy coapserver = new CoapServerProxy(); ProxyMapper.getInstance().setHttpServer(httpserver); ProxyMapper.getInstance().setHttpClient(httpclient); ProxyMapper.getInstance().setCoapClient(coapclient); ProxyMapper.getInstance().setCoapServer(coapserver); httpserver.start(); httpclient.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("===END==="); try { Thread.sleep(500); } catch (InterruptedException e) { } } }); ProxyRestInterface restInterface = new ProxyRestInterface(); restInterface.start(); } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/Proxy.java
Java
asf20
3,569
/* * 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 java.io.UnsupportedEncodingException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import net.sf.ehcache.Element; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.ParseException; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.ws4d.coap.interfaces.CoapClientChannel; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.messages.AbstractCoapMessage.CoapHeaderOptionType; import org.ws4d.coap.messages.BasicCoapRequest; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class ProxyMapper { static Logger logger = Logger.getLogger(Proxy.class); static final int DEFAULT_MAX_AGE_MS = 60000; //Max Age Default in ms //introduce other needed classes for communication private CoapClientProxy coapClient; private CoapServerProxy coapServer; private HttpServerNIO httpServer; private HttpClientNIO httpClient; private static ProxyCache cache; private static ProxyMapper instance; /*for statistics*/ private int httpRequestCount = 0; private int coapRequestCount = 0; private int servedFromCacheCount = 0; public synchronized static ProxyMapper getInstance() { if (instance == null) { instance = new ProxyMapper(); } return instance; } private ProxyMapper() { cache = new ProxyCache(); } /* * Server Client * +------+ +------+ RequestTime * InRequ --->| |----+-->Requ.Trans.-------->| |--->OutReq * | | | | | * | | | | | * | | ERROR | | * | | | | | * | | +<---ERROR -----+ | | * | | | | | | ResponseTime * OutResp<---| +<---+<--Resp.Trans.-+-------+ |<---InResp * +------+ +------+ * * HTTP -----------------------------> CoAP * * CoAP -----------------------------> HTTP * * CoAP -----------------------------> CoAP */ public void handleHttpServerRequest(ProxyMessageContext context) { httpRequestCount++; // do not translate methods: OPTIONS,TRACE,CONNECT -> error // "Not Implemented" if (isHttpRequestMethodSupported(context.getInHttpRequest())) { // perform request-transformation /* try to get from cache */ ProxyResource resource = null; if (context.getInHttpRequest().getRequestLine().getMethod().toLowerCase().equals("get")){ resource = cache.get(context); } if (resource != null) { /* answer from cache */ resourceToHttp(context, resource); context.setCached(true); // avoid "recaching" httpServer.sendResponse(context); logger.info("served HTTP request from cache"); servedFromCacheCount++; } else { /* not cached -> forward request */ try { coapClient.createChannel(context); //channel must be created first transRequestHttpToCoap(context); context.setRequestTime(System.currentTimeMillis()); coapClient.sendRequest(context); } catch (Exception e) { logger.warn("HTTP to CoAP Request failed: " + e.getMessage()); /* close if a channel was connected */ if (context.getOutCoapClientChannel() != null){ context.getOutCoapClientChannel().close(); } sendDirectHttpError(context, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); } } } else { /* method not supported */ sendDirectHttpError(context, HttpStatus.SC_NOT_IMPLEMENTED, "Not Implemented"); } } public void handleCoapServerRequest(ProxyMessageContext context) { coapRequestCount++; ProxyResource resource = null; if (context.getInCoapRequest().getRequestCode() == CoapRequestCode.GET){ resource = cache.get(context); } if (context.isTranslate()) { /* coap to http */ if (resource != null) { /* answer from cache */ resourceToHttp(context, resource); context.setCached(true); // avoid "recaching" httpServer.sendResponse(context); logger.info("served CoAP request from cache"); servedFromCacheCount++; } else { /* translate CoAP Request -> HTTP Request */ try { transRequestCoapToHttp(context); context.setRequestTime(System.currentTimeMillis()); httpClient.sendRequest(context); } catch (Exception e) { logger.warn("CoAP to HTTP Request translation failed: " + e.getMessage()); sendDirectCoapError(context, CoapResponseCode.Not_Found_404); } } } else { /* coap to coap */ if (resource != null) { /* answer from cache */ resourceToCoap(context, resource); context.setCached(true); // avoid "recaching" coapServer.sendResponse(context); logger.info("served from cache"); servedFromCacheCount++; } else { /* translate CoAP Request -> CoAP Request */ try { coapClient.createChannel(context); //channel must be created first transRequestCoapToCoap(context); context.setRequestTime(System.currentTimeMillis()); coapClient.sendRequest(context); } catch (Exception e) { logger.warn("CoAP to CoAP Request forwarding failed: " + e.getMessage()); sendDirectCoapError(context, CoapResponseCode.Not_Found_404); } } } } public void handleCoapClientResponse(ProxyMessageContext context) { context.setResponseTime(System.currentTimeMillis()); if (!context.isCached() && context.getInCoapResponse() !=null ) { // avoid recaching cache.cacheCoapResponse(context); } if (context.isTranslate()) { /* coap to HTTP */ try { transResponseCoapToHttp(context); } catch (Exception e) { logger.warn("CoAP to HTTP Response translation failed: " + e.getMessage()); context.setOutHttpResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error")); } httpServer.sendResponse(context); } else { /* coap to coap */ try { transResponseCoapToCoap(context); } catch (Exception e) { logger.warn("CoAP to CoAP Response forwarding failed: " + e.getMessage()); context.getOutCoapResponse().setResponseCode(CoapResponseCode.Internal_Server_Error_500); } coapServer.sendResponse(context); } } public void handleHttpClientResponse(ProxyMessageContext context) { context.setResponseTime(System.currentTimeMillis()); if (!context.isCached()) { cache.cacheHttpResponse(context); } try { transResponseHttpToCoap(context); } catch (Exception e) { logger.warn("HTTP to CoAP Response translation failed: " + e.getMessage()); context.getOutCoapResponse().setResponseCode(CoapResponseCode.Internal_Server_Error_500); } coapServer.sendResponse(context); } /* ------------------------------------ Translate Functions -----------------------------------*/ public static void transRequestCoapToCoap(ProxyMessageContext context){ CoapRequest in = context.getInCoapRequest(); CoapClientChannel channel = context.getOutCoapClientChannel(); context.setOutCoapRequest(channel.createRequest(CoapClientProxy.RELIABLE, in.getRequestCode())); CoapRequest out = context.getOutCoapRequest(); /*TODO: translate not using copy header options */ ((BasicCoapRequest) out).copyHeaderOptions((BasicCoapRequest)in); /* TODO: check if the next hop is a proxy or the final serer * implement coapUseProxy option for proxy */ out.removeOption(CoapHeaderOptionType.Proxy_Uri); out.setUriPath(context.getUri().getPath()); if (context.getUri().getQuery() != null){ out.setUriQuery(context.getUri().getQuery()); } out.removeOption(CoapHeaderOptionType.Token); out.setPayload(in.getPayload()); } public static void transRequestHttpToCoap(ProxyMessageContext context) throws IOException { HttpRequest httpRequest = context.getInHttpRequest(); boolean hasContent = false; CoapRequestCode requestCode; String method; method = httpRequest.getRequestLine().getMethod().toLowerCase(); if (method.contentEquals("get")) { requestCode = CoapRequestCode.GET; } else if (method.contentEquals("put")) { requestCode = CoapRequestCode.PUT; hasContent = true; } else if (method.contentEquals("post")) { requestCode = CoapRequestCode.POST; hasContent = true; } else if (method.contentEquals("delete")) { requestCode = CoapRequestCode.DELETE; } else if (method.contentEquals("head")) { // if we have a head request, coap should handle it as a get, // but without any message-body requestCode = CoapRequestCode.GET; context.setHttpHeadMethod(true); } else { throw new IllegalStateException("unknown message code"); } CoapClientChannel channel = context.getOutCoapClientChannel(); context.setOutCoapRequest(channel.createRequest(CoapClientProxy.RELIABLE, requestCode)); // Translate Headers CoapRequest coapRequest = context.getOutCoapRequest(); URI uri = null; // construct uri for later use uri = resolveHttpRequestUri(httpRequest); // Content-Type is in response only // Max-Age is in response only // Proxy-Uri doesn't matter for this purpose // ETag: if (httpRequest.containsHeader("Etag")) { Header[] headers = httpRequest.getHeaders("Etag"); if (headers.length > 0) { for (int i = 0; i < headers.length; i++) { String etag = headers[i].getValue(); coapRequest.addETag(etag.getBytes()); } } } // Uri-Host: // don't needs to be there // Location-Path is in response-only // Location-Query is in response-only // Uri-Path: // this is the implementation according to coap-rfc section 6.4 // first check if uri is absolute and that it has no fragment if (uri.isAbsolute() && uri.getFragment() == null) { coapRequest.setUriPath(uri.getPath()); } else { throw new IllegalStateException("uri has wrong format"); } // Token is the same number as msgID, not needed now // in future development it should be generated here // Accept: possible values are numeric media-types if (httpRequest.containsHeader("Accept")) { Header[] headers = httpRequest.getHeaders("Accept"); if (headers.length > 0) { for (int i = 0; i < headers.length; i++) { httpMediaType2coapMediaType(headers[i].getValue(), coapRequest); } } } // TODO: if-match: // if (request.containsHeader("If-Match")) { // Header[] headers = request.getHeaders("If-Match"); // if (headers.length > 0) { // for (int i=0; i < headers.length; i++) { // String header_value = headers[i].getValue(); // CoapHeaderOption option_ifmatch = new // CoapHeaderOption(CoapHeaderOptionType.If_Match, // header_value.getBytes()); // header.addOption(option_ifmatch ); // } // } // } // Uri-Query: // this is the implementation according to coap-rfc section 6.4 // first check if uri is absolute and that it has no fragment if (uri.isAbsolute() && uri.getFragment() == null) { if (uri.getQuery() != null) { // only add options if there are // some coapRequest.setUriQuery(uri.getQuery()); } } else { throw new IllegalStateException("uri has wrong format"); } // TODO: If-None-Match: // if (request.containsHeader("If-None-Match")) { // Header[] headers = request.getHeaders("If-None-Match"); // if (headers.length > 0) { // if (headers.length > 1) { // System.out.println("multiple headers in request, ignoring all except the first"); // } // String header_value = headers[0].getValue(); // CoapHeaderOption option_ifnonematch = new // CoapHeaderOption(CoapHeaderOptionType.If_None_Match, // header_value.getBytes()); // header.addOption(option_ifnonematch); // } // } // pass-through the payload if (hasContent){ BasicHttpEntityEnclosingRequest entirequest = (BasicHttpEntityEnclosingRequest) httpRequest; ConsumingNHttpEntityTemplate entity = (ConsumingNHttpEntityTemplate) entirequest.getEntity(); ByteContentListener listener = (ByteContentListener) entity.getContentListener(); byte[] data = listener.getContent(); context.getOutCoapRequest().setPayload(data); } } public static void transRequestCoapToHttp(ProxyMessageContext context) throws UnsupportedEncodingException{ HttpUriRequest httpRequest; CoapRequest request = context.getInCoapRequest(); CoapRequestCode code = request.getRequestCode(); //TODO:translate header options from coap-request to http-request NStringEntity entity; entity = new NStringEntity(new String(request.getPayload())); switch (code) { case GET: httpRequest = new HttpGet(context.getUri().toString()); break; case PUT: httpRequest = new HttpPut(context.getUri().toString()); ((HttpPut)httpRequest).setEntity(entity); break; case POST: httpRequest = new HttpPost(context.getUri().toString()); ((HttpPost)httpRequest).setEntity(entity); break; case DELETE: httpRequest = new HttpDelete(context.getUri().toString()); default: throw new IllegalStateException("unknown request code"); } context.setOutHttpRequest(httpRequest); } public static void transResponseCoapToCoap(ProxyMessageContext context){ CoapResponse in = context.getInCoapResponse(); CoapResponse out = context.getOutCoapResponse(); /*TODO: translate not using copy header options */ ((BasicCoapResponse) out).copyHeaderOptions((BasicCoapResponse)in); out.setResponseCode(in.getResponseCode()); out.removeOption(CoapHeaderOptionType.Token); out.setPayload(in.getPayload()); } public static void transResponseCoapToHttp(ProxyMessageContext context) throws UnsupportedEncodingException{ CoapResponse coapResponse = context.getInCoapResponse(); //create a response-object, set http version and assume a default state of ok HttpResponse httpResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); // differ between methods is necessary to set the right status-code String requestMethod = context.getInHttpRequest().getRequestLine().getMethod(); if (requestMethod.toLowerCase().contains("get")){ // set status code and reason phrase setHttpMsgCode(coapResponse, "get", httpResponse); // pass-through the payload, if we do not answer a head-request if (!context.isHttpHeadMethod()) { NStringEntity entity; entity = new NStringEntity(new String(coapResponse.getPayload()), "UTF-8"); entity.setContentType("text/plain"); httpResponse.setEntity(entity); } } else if (requestMethod.toLowerCase().contains("put")){ setHttpMsgCode(coapResponse, "put", httpResponse); } else if (requestMethod.toLowerCase().contains("post")){ setHttpMsgCode(coapResponse, "post", httpResponse); } else if (requestMethod.toLowerCase().contains("delete")){ setHttpMsgCode(coapResponse, "delete", httpResponse); } else { throw new IllegalStateException("unknown request method"); } // set Headers headerTranslateCoapToHttp(coapResponse, httpResponse); context.setOutHttpResponse(httpResponse); } public static void transResponseHttpToCoap(ProxyMessageContext context) throws ParseException, IOException{ //set the response-code according to response-code-mapping-table CoapResponse coapResponse = context.getOutCoapResponse(); coapResponse.setResponseCode(getCoapResponseCode(context)); //throws an exception if mapping failed //TODO: translate header-options //assume in this case a string-entity //TODO: add more entity-types coapResponse.setContentType(CoapMediaType.text_plain); String entity = ""; entity = EntityUtils.toString(context.getInHttpResponse().getEntity()); coapResponse.setPayload(entity); } /* these functions are called if the request translation fails and no message was forwarded */ public void sendDirectHttpError(ProxyMessageContext context,int code, String reason){ HttpResponse httpResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, code, reason); context.setOutHttpResponse(httpResponse); httpServer.sendResponse(context); } /* these functions are called if the request translation fails and no message was forwarded */ public void sendDirectCoapError(ProxyMessageContext context, CoapResponseCode code){ CoapServerChannel channel = (CoapServerChannel) context.getInCoapRequest().getChannel(); CoapResponse response = channel.createResponse(context.getInCoapRequest(), code); context.setInCoapResponse(response); coapServer.sendResponse(context); } public static void resourceToHttp(ProxyMessageContext context, ProxyResource resource){ /* TODO: very rudimentary implementation */ HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); try { NStringEntity entity; entity = new NStringEntity(new String(resource.getValue()), "UTF-8"); entity.setContentType("text/plain"); response.setEntity(entity); } catch (UnsupportedEncodingException e) { logger.error("HTTP entity creation failed"); } context.setOutHttpResponse(response); } public static void resourceToCoap(ProxyMessageContext context, ProxyResource resource){ CoapResponse response = context.getOutCoapResponse(); //already generated /* response code */ response.setResponseCode(CoapResponseCode.Content_205); /* payload */ response.setPayload(resource.getValue()); /* mediatype */ if (resource.getCoapMediaType() != null) { response.setContentType(resource.getCoapMediaType()); } /* Max-Age */ int maxAge = (int)(resource.expires() - System.currentTimeMillis()) / 1000; if (maxAge < 0){ /* should never happen because the function is only called if the resource is valid. * However, processing time can be an issue */ logger.warn("return expired resource (Max-Age = 0)"); maxAge = 0; } response.setMaxAge(maxAge); } public static void setHttpMsgCode(CoapResponse coapResponse, String requestMethod, HttpResponse httpResponse) { CoapResponseCode responseCode = coapResponse.getResponseCode(); switch(responseCode) { // case OK_200: { //removed from CoAP draft // httpResponse.setStatusCode(HttpStatus.SC_OK); // httpResponse.setReasonPhrase("Ok"); // break; // } case Created_201: { if (requestMethod.contains("post") || requestMethod.contains("put")) { httpResponse.setStatusCode(HttpStatus.SC_CREATED); httpResponse.setReasonPhrase("Created"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Deleted_202: { if (requestMethod.contains("delete")) { httpResponse.setStatusCode(HttpStatus.SC_NO_CONTENT); httpResponse.setReasonPhrase("No Content"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Valid_203: { httpResponse.setStatusCode(HttpStatus.SC_NOT_MODIFIED); httpResponse.setReasonPhrase("Not Modified"); break; } case Changed_204: { if (requestMethod.contains("post") || requestMethod.contains("put")) { httpResponse.setStatusCode(HttpStatus.SC_NO_CONTENT); httpResponse.setReasonPhrase("No Content"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Content_205: { if (requestMethod.contains("get")) { httpResponse.setStatusCode(HttpStatus.SC_OK); httpResponse.setReasonPhrase("OK"); } else { System.out.println("wrong msgCode for request-method!"); httpResponse.setStatusCode(HttpStatus.SC_METHOD_FAILURE); httpResponse.setReasonPhrase("Method Failure"); } break; } case Bad_Request_400: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Request"); break; } case Unauthorized_401: { httpResponse.setStatusCode(HttpStatus.SC_UNAUTHORIZED); httpResponse.setReasonPhrase("Unauthorized"); break; } case Bad_Option_402: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Option"); break; } case Forbidden_403: { httpResponse.setStatusCode(HttpStatus.SC_FORBIDDEN); httpResponse.setReasonPhrase("Forbidden"); break; } case Not_Found_404: { httpResponse.setStatusCode(HttpStatus.SC_NOT_FOUND); httpResponse.setReasonPhrase("Not Found"); break; } case Method_Not_Allowed_405: { httpResponse.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED); httpResponse.setReasonPhrase("Method Not Allowed"); break; } case Precondition_Failed_412: { httpResponse.setStatusCode(HttpStatus.SC_PRECONDITION_FAILED); httpResponse.setReasonPhrase("Precondition Failed"); break; } case Request_Entity_To_Large_413: { httpResponse.setStatusCode(HttpStatus.SC_REQUEST_TOO_LONG); httpResponse.setReasonPhrase("Request Too Long : Request entity too large"); break; } case Unsupported_Media_Type_415: { httpResponse.setStatusCode(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE); httpResponse.setReasonPhrase("Unsupported Media Type"); break; } case Internal_Server_Error_500: { httpResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); httpResponse.setReasonPhrase("Internal Server Error"); break; } case Not_Implemented_501: { httpResponse.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); httpResponse.setReasonPhrase("Not Implemented"); break; } case Bad_Gateway_502: { httpResponse.setStatusCode(HttpStatus.SC_BAD_GATEWAY); httpResponse.setReasonPhrase("Bad Gateway"); break; } case Service_Unavailable_503: { httpResponse.setStatusCode(HttpStatus.SC_SERVICE_UNAVAILABLE); httpResponse.setReasonPhrase("Service Unavailable"); break; } case Gateway_Timeout_504: { httpResponse.setStatusCode(HttpStatus.SC_GATEWAY_TIMEOUT); httpResponse.setReasonPhrase("Gateway Timeout"); break; } case Proxying_Not_Supported_505: { httpResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); httpResponse.setReasonPhrase("Internal Server Error : Proxying not supported"); break; } case UNKNOWN: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Request : Unknown Coap Message Code"); break; } default: { httpResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST); httpResponse.setReasonPhrase("Bad Request : Unknown Coap Message Code"); break; } } } //sets the coap-response code under use of http-status code; used in case coap-http public static CoapResponseCode getCoapResponseCode(ProxyMessageContext context) { HttpResponse httpResponse = context.getInHttpResponse(); //TODO: add cases in which http-code is the same, but coap-code is different, look at response-code-mapping-table switch(httpResponse.getStatusLine().getStatusCode()) { case HttpStatus.SC_CREATED: return CoapResponseCode.Created_201; case HttpStatus.SC_NO_CONTENT: if (context.getInCoapRequest().getRequestCode() == CoapRequestCode.DELETE) { return CoapResponseCode.Deleted_202; } else { return CoapResponseCode.Changed_204; } case HttpStatus.SC_NOT_MODIFIED: return CoapResponseCode.Valid_203; case HttpStatus.SC_OK: return CoapResponseCode.Content_205; case HttpStatus.SC_UNAUTHORIZED: return CoapResponseCode.Unauthorized_401; case HttpStatus.SC_FORBIDDEN:return CoapResponseCode.Forbidden_403; case HttpStatus.SC_NOT_FOUND:return CoapResponseCode.Not_Found_404; case HttpStatus.SC_METHOD_NOT_ALLOWED:return CoapResponseCode.Method_Not_Allowed_405; case HttpStatus.SC_PRECONDITION_FAILED: return CoapResponseCode.Precondition_Failed_412; case HttpStatus.SC_REQUEST_TOO_LONG: return CoapResponseCode.Request_Entity_To_Large_413; case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:return CoapResponseCode.Unsupported_Media_Type_415; case HttpStatus.SC_INTERNAL_SERVER_ERROR:return CoapResponseCode.Internal_Server_Error_500; case HttpStatus.SC_NOT_IMPLEMENTED:return CoapResponseCode.Not_Implemented_501; case HttpStatus.SC_BAD_GATEWAY:return CoapResponseCode.Bad_Gateway_502; case HttpStatus.SC_SERVICE_UNAVAILABLE:return CoapResponseCode.Service_Unavailable_503; case HttpStatus.SC_GATEWAY_TIMEOUT:return CoapResponseCode.Gateway_Timeout_504; default: throw new IllegalStateException("unknown HTTP response code"); } } //mediatype-mapping: public static void httpMediaType2coapMediaType(String mediatype, CoapRequest request) { String[] type_subtype = mediatype.split(","); for (String value : type_subtype) { if (value.toLowerCase().contains("text") && value.toLowerCase().contains("plain")) { request.addAccept(CoapMediaType.text_plain); } else if (value.toLowerCase().contains("application")) { // value is for example "application/xml;q=0.9" String[] subtypes = value.toLowerCase().split("/"); String subtype = ""; if (subtypes.length == 2) { subtype = subtypes[1]; // subtype is for example now "xml;q=0.9" } else { System.out.println("Error in reading Mediatypes!"); } // extract the subtype-name and remove the quality identifiers: String[] subname = subtype.split(";"); String name = ""; if (subname.length > 0) { name = subname[0]; // name is for example "xml" } else { System.out.println("Error in reading Mediatypes!"); } if (name.contentEquals("link-format")) { request.addAccept(CoapMediaType.link_format); } if (name.contentEquals("xml")) { request.addAccept(CoapMediaType.xml); } if (name.contentEquals("octet-stream")) { request.addAccept(CoapMediaType.octet_stream); } if (name.contentEquals("exi")) { request.addAccept(CoapMediaType.exi); } if (name.contentEquals("json")) { request.addAccept(CoapMediaType.json); } } } } // translate response-header-options in case of http-coap public static void headerTranslateCoapToHttp(CoapResponse coapResponse, HttpResponse httpResponse) { // investigate all coap-headers and set corresponding http-headers CoapMediaType contentType = coapResponse.getContentType(); if (contentType != null) { switch (contentType) { case text_plain: httpResponse.addHeader("Content-Type", "text/plain"); break; case link_format: httpResponse.addHeader("Content-Type", "application/link-format"); break; case json: httpResponse.addHeader("Content-Type", "application/json"); break; case exi: httpResponse.addHeader("Content-Type", "application/exi"); break; case octet_stream: httpResponse.addHeader("Content-Type", "application/octet-stream"); break; case xml: httpResponse.addHeader("Content-Type", "application/xml"); break; default: httpResponse.addHeader("Content-Type", "text/plain"); break; } } else { httpResponse.addHeader("Content-Type", "text/plain"); } long maxAge = coapResponse.getMaxAge(); if (maxAge < 0){ maxAge = DEFAULT_MAX_AGE_MS; } long maxAgeMs = maxAge * 1000; if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE){ httpResponse.addHeader("Retry-After", String.valueOf(maxAge)); } byte[] etag = coapResponse.getETag(); if (etag != null){ httpResponse.addHeader("Etag", new String(etag)); } //generate content-length-header if (httpResponse.getEntity() != null) httpResponse.addHeader("Content-length", "" + httpResponse.getEntity().getContentLength()); //set creation-date for Caching: httpResponse.addHeader("Date", "" + formatDate(new GregorianCalendar().getTime())); //expires-option is option-value (default is 60 secs) + current_date Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(calendar.getTimeInMillis() + maxAgeMs); String date = formatDate(calendar.getTime()); httpResponse.addHeader("Expires", date); } public static HttpResponse handleCoapDELETEresponse(CoapResponse response, HttpResponse httpResponse) { //set status code and reason phrase headerTranslateCoapToHttp(response, httpResponse); return httpResponse; } // //the mode is used to indicate for which case the proxy is listening to // //mode is unneccessary when proxy is listening to all cases, then there are more threads neccessary // public void setMode(Integer modenumber) { // mode = modenumber; // } //setter-functions to introduce other threads public void setHttpServer(HttpServerNIO server) { httpServer = server; } public void setHttpClient(HttpClientNIO client) { httpClient = client; } public void setCoapServer(CoapServerProxy server) { coapServer = server; } public void setCoapClient(CoapClientProxy client) { coapClient = client; } //exclude methods from processing:OPTIONS/TRACE/CONNECT public static boolean isHttpRequestMethodSupported(HttpRequest request) { String method = request.getRequestLine().getMethod().toLowerCase(); if (method.contentEquals("options") || method.contentEquals("trace") || method.contentEquals("connect")) return false; return true; } //makes a date to a string; http-header-values (expires, date...) must be a string in most cases public static String formatDate(Date date) { final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; if (date == null) { throw new IllegalArgumentException("date is null"); } SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_RFC1123, Locale.US); formatter.setTimeZone(TimeZone.getDefault()); //CEST String ret = formatter.format(date); return ret; } public static URI resolveHttpRequestUri(HttpRequest request){ URI uri = null; String uriString = request.getRequestLine().getUri(); /* make sure to have the scheme */ if (uriString.startsWith("coap://")){ /* do nothing */ } else if (uriString.startsWith("http://")){ uriString = "coap://" + uriString.substring(7); } else { /* not an absolute uri */ Header[] host = request.getHeaders("Host"); /* only one is accepted */ if (host.length <= 0){ /* error, unknown host*/ return null; } uriString = "coap://" + host[0].getValue() + uriString; } try { uri = new URI(uriString); } catch (URISyntaxException e) { return null; //indicates that resolve failed } return uri; } public static boolean isIPv4Address(InetAddress addr) { try { @SuppressWarnings("unused") //just to check if casting fails Inet4Address addr4 = (Inet4Address) addr; return true; } catch (ClassCastException ex) { return false; } } public static boolean isIPv6Address(InetAddress addr) { try { @SuppressWarnings("unused") //just to check if casting fails Inet6Address addr6 = (Inet6Address) addr; return true; } catch (ClassCastException ex) { return false; } } public int getHttpRequestCount() { return httpRequestCount; } public int getCoapRequestCount() { return coapRequestCount; } public int getServedFromCacheCount() { return servedFromCacheCount; } public void resetCounter(){ httpRequestCount = 0; coapRequestCount = 0; servedFromCacheCount = 0; } public void setCacheEnabled(boolean enabled) { cache.setEnabled(enabled); } public CoapClientProxy getCoapClient() { return coapClient; } public CoapServerProxy getCoapServer() { return coapServer; } public HttpServerNIO getHttpServer() { return httpServer; } public HttpClientNIO getHttpClient() { return httpClient; } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ProxyMapper.java
Java
asf20
34,263
/* * 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 } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/CoapServerProxy.java
Java
asf20
5,742
package org.ws4d.coap.proxy; import java.util.Vector; import org.apache.log4j.Logger; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.rest.BasicCoapResource; import org.ws4d.coap.rest.CoapResourceServer; public class ProxyRestInterface { static Logger logger = Logger.getLogger(Proxy.class); private CoapResourceServer resourceServer; public void start(){ if (resourceServer != null) resourceServer.stop(); resourceServer = new CoapResourceServer(); resourceServer.createResource(new ProxyStatisticResource()); try { resourceServer.start(5684); } catch (Exception e) { e.printStackTrace(); } } public class ProxyStatisticResource extends BasicCoapResource{ private ProxyStatisticResource(String path, byte[] value, CoapMediaType mediaType) { super(path, value, mediaType); } public ProxyStatisticResource(){ this("/statistic", null, CoapMediaType.text_plain); } @Override public byte[] getValue(Vector<String> query) { StringBuilder val = new StringBuilder(); ProxyMapper.getInstance().getCoapRequestCount(); val.append("Number of HTTP Requests: " + ProxyMapper.getInstance().getHttpRequestCount() + "\n"); val.append("Number of CoAP Requests: " + ProxyMapper.getInstance().getCoapRequestCount() + "\n"); val.append("Number of Reqeusts served from cache: " + ProxyMapper.getInstance().getServedFromCacheCount() + "\n"); return val.toString().getBytes(); } } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ProxyRestInterface.java
Java
asf20
1,479
/* * 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.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import net.sf.ehcache.config.CacheConfiguration; import net.sf.ehcache.store.MemoryStoreEvictionPolicy; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.messages.CoapRequestCode; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ /* * TODO's: * - implement Date option as described in "Connecting the Web with the Web of Things: Lessons Learned From Implementing a CoAP-HTTP Proxy" * - caching of HTTP resources not supported as HTTP servers may have enough resources (in terms of RAM/ROM/batery/computation) * * */ public class ProxyCache { static Logger logger = Logger.getLogger(Proxy.class); private static final int MAX_LIFETIME = Integer.MAX_VALUE; private static Cache cache; private static CacheManager cacheManager; private boolean enabled = true; private static final int defaultMaxAge = org.ws4d.coap.Constants.COAP_DEFAULT_MAX_AGE_S; private static final ProxyCacheTimePolicy cacheTimePolicy = ProxyCacheTimePolicy.Halftime; public ProxyCache() { cacheManager = CacheManager.create(); cache = new Cache(new CacheConfiguration("proxy", 100) .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU) .overflowToDisk(true) .eternal(false) .diskPersistent(false) .diskExpiryThreadIntervalSeconds(0)); cacheManager.addCache(cache); } public void removeKey(URI uri) { cache.remove(uri); } // public void put(ProxyMessageContext context) { // if (isEnabled() || context == null){ // return; // } // //TODO: check for overwrites // // // insertElement(context.getResource().getKey(), context.getResource()); //// URI uri = context.getUri(); //// if (uri.getScheme().equalsIgnoreCase("coap")){ //// putCoapRes(uri, context.getCoapResponse()); //// } else if (uri.getScheme().equalsIgnoreCase("http")){ //// putHttpRes(uri, context.getHttpResponse()); //// } // } // private void putHttpRes(URI uri, HttpResponse response){ // if (response == null){ // return; // } // logger.info( "Cache HTTP Resource (" + uri.toString() + ")"); // //first determine what to do // int code = response.getStatusLine().getStatusCode(); // // //make some garbage collection to avoid a cache overflow caused by many expired elements (when 80% charged as first idea) // if (cache.getSize() > cache.getCacheConfiguration().getMaxElementsInMemory()*0.8) { // cache.evictExpiredElements(); // } // // //set the max-age of new element // //use the http-header-options expires and date // //difference is the same value as the corresponding max-age from coap-response, but at this point we only have a http-response // int timeToLive = 0; // Header[] expireHeaders = response.getHeaders("Expires"); // if (expireHeaders.length == 1) { // String expire = expireHeaders[0].getValue(); // Date expireDate = StringToDate(expire); // // Header[] dateHeaders = response.getHeaders("Date"); // if (dateHeaders.length == 1) { // String dvalue = dateHeaders[0].getValue(); // Date date = StringToDate(dvalue); // // timeToLive = (int) ((expireDate.getTime() - date.getTime()) / 1000); // } // } // // //cache-actions are dependent of response-code, as described in coap-rfc-draft-7 // switch(code) { // case HttpStatus.SC_CREATED: { // if (cache.isKeyInCache(uri)) { // markExpired(uri); // } // break; // } // case HttpStatus.SC_NO_CONTENT: { // if (cache.isKeyInCache(uri)) { // markExpired(uri); // } // break; // } // case HttpStatus.SC_NOT_MODIFIED: { // if (cache.isKeyInCache(uri)) { // insertElement(uri, response, timeToLive); //should update the response if req is already in cache // } // break; // } // default: { // insertElement(uri, response, timeToLive); // break; // } // } // } // private void putCoapRes(ProxyResourceKey key, CoapResponse response){ // if (response == null){ // return; // } // logger.debug( "Cache CoAP Resource (" + uri.toString() + ")"); // // long timeToLive = response.getMaxAge(); // if (timeToLive < 0){ // timeToLive = defaultTimeToLive; // } // insertElement(key, response); // } // // public HttpResponse getHttpRes(URI uri) { // if (defaultTimeToLive == 0) return null; // if (cache.getQuiet(uri) != null) { // Object o = cache.get(uri).getObjectValue(); // logger.debug( "Found in cache (" + uri.toString() + ")"); // return (HttpResponse) o; // } else { // logger.debug( "Not in cache (" + uri.toString() + ")"); // return null; // } // } // // public CoapResponse getCoapRes(URI uri) { // if (defaultTimeToLive == 0) return null; // // if (cache.getQuiet(uri) != null) { // Object o = cache.get(uri).getObjectValue(); // logger.debug( "Found in cache (" + uri.toString() + ")"); // return (CoapResponse) o; // }else{ // logger.debug( "Not in cache (" + uri.toString() + ")"); // return null; // } // } public boolean isInCache(ProxyResourceKey key) { if (!isEnabled()){ return false; } if (cache.isKeyInCache(key)) { return true; } else { return false; } } //for some operations it is necessary to build an http-date from string private static Date StringToDate(String string_date) { Date date = null; //this pattern is the official http-date format final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_RFC1123, Locale.US); formatter.setTimeZone(TimeZone.getDefault()); //CEST, default is GMT try { date = (Date) formatter.parse(string_date); } catch (ParseException e) { e.printStackTrace(); } return date; } // //mark an element as expired // private void markExpired(ProxyResourceKey key) { // if (cache.getQuiet(key) != null) { // cache.get(key).setTimeToLive(0); // } // } private boolean insertElement(ProxyResourceKey key, ProxyResource resource) { Element elem = new Element(key, resource); if (resource.expires() == -1) { /* never expires */ cache.put(elem); } else { long ttl = resource.expires() - System.currentTimeMillis(); if (ttl > 0) { /* limit the maximum lifetime */ if (ttl > MAX_LIFETIME) { ttl = MAX_LIFETIME; } elem.setTimeToLive((int) ttl); cache.put(elem); logger.debug("cache insert: " + resource.getPath() ); } else { /* resource is already expired */ return false; } } return true; } private void updateTtl(ProxyResourceKey key, long newExpires) { /*getQuiet is used to not update statistics */ Element elem = cache.getQuiet(key); if (elem != null) { long ttl = newExpires - System.currentTimeMillis(); if (ttl > 0 || newExpires == -1 ) { /* limit the maximum lifetime */ if (ttl > MAX_LIFETIME) { ttl = MAX_LIFETIME; } elem.setTimeToLive((int) ttl); } } } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public ProxyResource get(ProxyMessageContext context) { if (!isEnabled()){ return null; } String path = context.getUri().getPath(); if(path == null){ /* no caching */ return null; } Element elem = cache.get(new ProxyResourceKey(context.getServerAddress(), context.getServerPort(), path)); logger.debug("cache get: " + context.getServerAddress().toString() + " " + context.getServerPort() + " " + path); if (elem != null) { /* found cached entry */ ProxyResource res = (ProxyResource) elem.getObjectValue(); if (!res.isExpired()) { return res; } } return null; } public void cacheHttpResponse(ProxyMessageContext context) { if (!isEnabled()){ return; } /* TODO caching of HTTP responses currently not supported (not use to unload HTTP servers) */ return; } public void cacheCoapResponse(ProxyMessageContext context) { if (!isEnabled()){ return; } CoapResponse response = context.getInCoapResponse(); String path = context.getUri().getPath(); if(path == null){ /* no caching */ return; } ProxyResourceKey key = new ProxyResourceKey(context.getServerAddress(), context.getServerPort(), path); /* NOTE: * - currently caching is only implemented for success error codes (2.xx) * - not fresh resources are removed (could be used for validation model)*/ switch (context.getInCoapResponse().getResponseCode()) { case Created_201: /* A cache SHOULD mark any stored response for the created resource as not fresh. This response is not cacheable.*/ cache.remove(key); break; case Deleted_202: /* This response is not cacheable. However, a cache SHOULD mark any stored response for the deleted resource as not fresh.*/ cache.remove(key); break; case Valid_203: /* When a cache receives a 2.03 (Valid) response, it needs to update the stored response with the value of the Max-Age Option included in the response (see Section 5.6.2). */ //TODO break; case Changed_204: /* This response is not cacheable. However, a cache SHOULD mark any stored response for the changed resource as not fresh. */ cache.remove(key); break; case Content_205: /* This response is cacheable: Caches can use the Max-Age Option to determine freshness (see Section 5.6.1) and (if present) the ETag Option for validation (see Section 5.6.2).*/ /* CACHE RESOURCE */ ProxyResource resource = new ProxyResource(path, response.getPayload(), response.getContentType()); resource.setExpires(cacheTimePolicy.calcExpires(context.getRequestTime(), context.getResponseTime(), response.getMaxAge())); insertElement(key, resource); break; default: break; } } public enum ProxyCacheTimePolicy{ Request(0), Response(1), Halftime(2); int state; private ProxyCacheTimePolicy(int state){ this.state = state; } public long calcExpires(long requestTime, long responseTime, long maxAge){ if (maxAge == -1){ maxAge = defaultMaxAge; } switch (this) { case Request: return requestTime + (maxAge * 1000) ; case Response: return responseTime + (maxAge * 1000); case Halftime: return requestTime + ((responseTime - requestTime) / 2) + (maxAge * 1000); } return 0; } } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ProxyCache.java
Java
asf20
11,688
/* * 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 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); } } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/CoapClientProxy.java
Java
asf20
2,822
/* * 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 org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.impl.nio.client.DefaultHttpAsyncClient; import org.apache.http.message.BasicHttpResponse; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.http.nio.concurrent.FutureCallback; import org.apache.http.nio.reactor.IOReactorException; import org.apache.log4j.Logger; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class HttpClientNIO extends Thread { static Logger logger = Logger.getLogger(Proxy.class); ProxyMapper mapper = ProxyMapper.getInstance(); HttpAsyncClient httpClient; public HttpClientNIO() { try { httpClient = new DefaultHttpAsyncClient(); } catch (IOReactorException e) { System.exit(-1); e.printStackTrace(); } httpClient.start(); logger.info("HTTP client started"); } public void sendRequest(ProxyMessageContext context) { // future is used to receive response asynchronous, without blocking //ProxyHttpFutureCallback allows to associate a ProxyMessageContext logger.info("send HTTP request"); ProxyHttpFutureCallback fc = new ProxyHttpFutureCallback(); fc.setContext(context); httpClient.execute(context.getOutHttpRequest(), fc); } private class ProxyHttpFutureCallback implements FutureCallback<HttpResponse>{ private ProxyMessageContext context = null; public void setContext(ProxyMessageContext context) { this.context = context; } // this is called when response is received public void completed(final HttpResponse response) { if (context != null) { context.setInHttpResponse(response); mapper.handleHttpClientResponse(context); } } public void failed(final Exception ex) { logger.warn("HTTP client request failed"); if (context != null) { context.setInHttpResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, ex.getMessage())); mapper.handleHttpClientResponse(context); } } public void cancelled() { logger.warn("HTTP Client Request cancelled"); if (context != null) { /* null indicates no response */ context.setInHttpResponse(new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "http connection canceled")); mapper.handleHttpClientResponse(context); } } } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/HttpClientNIO.java
Java
asf20
3,172
/* * 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.ConnectionReuseStrategy; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.MethodNotSupportedException; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.UnsupportedHttpVersionException; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate; import org.apache.http.nio.entity.NByteArrayEntity; import org.apache.http.nio.entity.NHttpEntityWrapper; import org.apache.http.nio.entity.ProducingNHttpEntity; import org.apache.http.nio.protocol.NHttpHandlerBase; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerResolver; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpExpectationVerifier; import org.apache.http.protocol.HttpProcessor; import org.apache.http.util.EncodingUtils; /** * Fully asynchronous HTTP server side protocol handler implementation that * implements the essential requirements of the HTTP protocol for the server * side message processing as described by RFC . It is capable of processing * HTTP requests with nearly constant memory footprint. Only HTTP message heads * are stored in memory, while content of message bodies is streamed directly * from the entity to the underlying channel (and vice versa) * {@link ConsumingNHttpEntity} and {@link ProducingNHttpEntity} interfaces. * <p/> * When using this class, it is important to ensure that entities supplied for * writing implement {@link ProducingNHttpEntity}. Doing so will allow the * entity to be written out asynchronously. If entities supplied for writing do * not implement {@link ProducingNHttpEntity}, a delegate is added that buffers * the entire contents in memory. Additionally, the buffering might take place * in the I/O thread, which could cause I/O to block temporarily. For best * results, ensure that all entities set on {@link HttpResponse}s from * {@link NHttpRequestHandler}s implement {@link ProducingNHttpEntity}. * <p/> * If incoming requests enclose a content entity, {@link NHttpRequestHandler}s * are expected to return a {@link ConsumingNHttpEntity} for reading the * content. After the entity is finished reading the data, * {@link NHttpRequestHandler#handle(HttpRequest, HttpResponse, NHttpResponseTrigger, HttpContext)} * is called to generate a response. * <p/> * Individual {@link NHttpRequestHandler}s do not have to submit a response * immediately. They can defer transmission of the HTTP response back to the * client without blocking the I/O thread and to delegate the processing the * HTTP request to a worker thread. The worker thread in its turn can use an * instance of {@link NHttpResponseTrigger} passed as a parameter to submit * a response as at a later point of time once the response becomes available. * * @see ConsumingNHttpEntity * @see ProducingNHttpEntity * * @since 4.0 */ /** * @author Christian Lerche <christian.lerche@uni-rostock.de> * @author Andy Seidel <andy.seidel@uni-rostock.de> */ public class ModifiedAsyncNHttpServiceHandler extends NHttpHandlerBase implements NHttpServiceHandler { protected final HttpResponseFactory responseFactory; protected NHttpRequestHandlerResolver handlerResolver; protected HttpExpectationVerifier expectationVerifier; public ModifiedAsyncNHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final ByteBufferAllocator allocator, final HttpParams params) { super(httpProcessor, connStrategy, allocator, params); if (responseFactory == null) { throw new IllegalArgumentException("Response factory may not be null"); } this.responseFactory = responseFactory; } public ModifiedAsyncNHttpServiceHandler( final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final HttpParams params) { this(httpProcessor, responseFactory, connStrategy, new HeapByteBufferAllocator(), params); } public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { this.expectationVerifier = expectationVerifier; } public void setHandlerResolver(final NHttpRequestHandlerResolver handlerResolver) { this.handlerResolver = handlerResolver; } public void connected(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = new ServerConnState(); context.setAttribute(CONN_STATE, connState); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); if (this.eventListener != null) { this.eventListener.connectionOpen(conn); } } public void requestReceived(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); HttpRequest request = conn.getHttpRequest(); request.setParams(new DefaultedHttpParams(request.getParams(), this.params)); connState.setRequest(request); NHttpRequestHandler requestHandler = getRequestHandler(request); connState.setRequestHandler(requestHandler); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } HttpResponse response; try { if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; if (entityRequest.expectContinue()) { response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); if (this.expectationVerifier != null) { try { this.expectationVerifier.verify(request, response, context); } catch (HttpException ex) { response = this.responseFactory.newHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(ex, response); } } if (response.getStatusLine().getStatusCode() < 200) { // Send 1xx response indicating the server expections // have been met conn.submitResponse(response); } else { conn.resetInput(); sendResponse(conn, request, response); } } // Request content is expected. ConsumingNHttpEntity consumingEntity = null; // Lookup request handler for this request if (requestHandler != null) { consumingEntity = requestHandler.entityRequest(entityRequest, context); } if (consumingEntity == null) { consumingEntity = new ConsumingNHttpEntityTemplate( entityRequest.getEntity(), new ByteContentListener()); } entityRequest.setEntity(consumingEntity); connState.setConsumingEntity(consumingEntity); } else { // No request content is expected. // Process request right away conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void closed(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); try { connState.reset(); } catch (IOException ex) { if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } if (this.eventListener != null) { this.eventListener.connectionClosed(conn); } } public void exception(final NHttpServerConnection conn, final HttpException httpex) { if (conn.isResponseSubmitted()) { // There is not much that we can do if a response head // has already been submitted closeConnection(conn, httpex); if (eventListener != null) { eventListener.fatalProtocolException(httpex, conn); } return; } HttpContext context = conn.getContext(); try { HttpResponse response = this.responseFactory.newHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(httpex, response); response.setEntity(null); sendResponse(conn, null, response); } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void exception(final NHttpServerConnection conn, final IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } public void timeout(final NHttpServerConnection conn) { handleTimeout(conn); } public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); HttpRequest request = connState.getRequest(); ConsumingNHttpEntity consumingEntity = connState.getConsumingEntity(); try { consumingEntity.consumeContent(decoder, conn); if (decoder.isCompleted()) { conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void responseReady(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); if (connState.isHandled()) { return; } HttpRequest request = connState.getRequest(); try { IOException ioex = connState.getIOException(); if (ioex != null) { throw ioex; } HttpException httpex = connState.getHttpException(); if (httpex != null) { HttpResponse response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(httpex, response); connState.setResponse(response); } HttpResponse response = connState.getResponse(); if (response != null) { connState.setHandled(true); sendResponse(conn, request, response); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { closeConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); HttpResponse response = conn.getHttpResponse(); try { ProducingNHttpEntity entity = connState.getProducingEntity(); entity.produceContent(encoder, conn); if (encoder.isCompleted()) { connState.finishOutput(); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready to process new request connState.reset(); conn.requestInput(); } responseComplete(response, context); } } catch (IOException ex) { shutdownConnection(conn, ex); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } } private void handleException(final HttpException ex, final HttpResponse response) { int code = HttpStatus.SC_INTERNAL_SERVER_ERROR; if (ex instanceof MethodNotSupportedException) { code = HttpStatus.SC_NOT_IMPLEMENTED; } else if (ex instanceof UnsupportedHttpVersionException) { code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED; } else if (ex instanceof ProtocolException) { code = HttpStatus.SC_BAD_REQUEST; } response.setStatusCode(code); byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage()); NByteArrayEntity entity = new NByteArrayEntity(msg); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); } /** * @throws HttpException - not thrown currently */ private void processRequest( final NHttpServerConnection conn, final HttpRequest request) throws IOException, HttpException { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } NHttpResponseTrigger trigger = new ResponseTriggerImpl(connState, conn); try { this.httpProcessor.process(request, context); NHttpRequestHandler handler = connState.getRequestHandler(); if (handler != null) { HttpResponse response = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_OK, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handler.handle( request, response, trigger, context); } else { HttpResponse response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_NOT_IMPLEMENTED, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); trigger.submitResponse(response); } } catch (HttpException ex) { trigger.handleException(ex); } } private void sendResponse( final NHttpServerConnection conn, final HttpRequest request, final HttpResponse response) throws IOException, HttpException { HttpContext context = conn.getContext(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); // Now that a response is ready, we can cleanup the listener for the request. connState.finishInput(); // Some processers need the request that generated this response. context.setAttribute(ExecutionContext.HTTP_REQUEST, request); this.httpProcessor.process(response, context); context.setAttribute(ExecutionContext.HTTP_REQUEST, null); if (response.getEntity() != null && !canResponseHaveBody(request, response)) { response.setEntity(null); } HttpEntity entity = response.getEntity(); if (entity != null) { if (entity instanceof ProducingNHttpEntity) { connState.setProducingEntity((ProducingNHttpEntity) entity); } else { connState.setProducingEntity(new NHttpEntityWrapper(entity)); } } conn.submitResponse(response); if (entity == null) { if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready to process new request connState.reset(); conn.requestInput(); } responseComplete(response, context); } } /** * Signals that this response has been fully sent. This will be called after * submitting the response to a connection, if there is no entity in the * response. If there is an entity, it will be called after the entity has * completed. */ protected void responseComplete(HttpResponse response, HttpContext context) { } private NHttpRequestHandler getRequestHandler(HttpRequest request) { NHttpRequestHandler handler = null; if (this.handlerResolver != null) { String requestURI = request.getRequestLine().getUri(); handler = this.handlerResolver.lookup(requestURI); } return handler; } protected static class ServerConnState { private volatile NHttpRequestHandler requestHandler; private volatile HttpRequest request; private volatile ConsumingNHttpEntity consumingEntity; private volatile HttpResponse response; private volatile ProducingNHttpEntity producingEntity; private volatile IOException ioex; private volatile HttpException httpex; private volatile boolean handled; public void finishInput() throws IOException { if (this.consumingEntity != null) { this.consumingEntity.finish(); this.consumingEntity = null; } } public void finishOutput() throws IOException { if (this.producingEntity != null) { this.producingEntity.finish(); this.producingEntity = null; } } public void reset() throws IOException { finishInput(); this.request = null; finishOutput(); this.handled = false; this.response = null; this.ioex = null; this.httpex = null; this.requestHandler = null; } public NHttpRequestHandler getRequestHandler() { return this.requestHandler; } public void setRequestHandler(final NHttpRequestHandler requestHandler) { this.requestHandler = requestHandler; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public ConsumingNHttpEntity getConsumingEntity() { return this.consumingEntity; } public void setConsumingEntity(final ConsumingNHttpEntity consumingEntity) { this.consumingEntity = consumingEntity; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public ProducingNHttpEntity getProducingEntity() { return this.producingEntity; } public void setProducingEntity(final ProducingNHttpEntity producingEntity) { this.producingEntity = producingEntity; } public IOException getIOException() { return this.ioex; } @Deprecated public IOException getIOExepction() { return this.ioex; } public void setIOException(final IOException ex) { this.ioex = ex; } @Deprecated public void setIOExepction(final IOException ex) { this.ioex = ex; } public HttpException getHttpException() { return this.httpex; } @Deprecated public HttpException getHttpExepction() { return this.httpex; } public void setHttpException(final HttpException ex) { this.httpex = ex; } @Deprecated public void setHttpExepction(final HttpException ex) { this.httpex = ex; } public boolean isHandled() { return this.handled; } public void setHandled(boolean handled) { this.handled = handled; } } private static class ResponseTriggerImpl implements NHttpResponseTrigger { private final ServerConnState connState; private final IOControl iocontrol; private volatile boolean triggered; public ResponseTriggerImpl(final ServerConnState connState, final IOControl iocontrol) { super(); this.connState = connState; this.iocontrol = iocontrol; } public void submitResponse(final HttpResponse response) { if (response == null) { throw new IllegalArgumentException("Response may not be null"); } if (this.triggered) { throw new IllegalStateException("Response already triggered"); } this.triggered = true; this.connState.setResponse(response); this.iocontrol.requestOutput(); } public void handleException(final HttpException ex) { if (this.triggered) { throw new IllegalStateException("Response already triggered"); } this.triggered = true; this.connState.setHttpException(ex); this.iocontrol.requestOutput(); } public void handleException(final IOException ex) { if (this.triggered) { throw new IllegalStateException("Response already triggered"); } this.triggered = true; this.connState.setIOException(ex); this.iocontrol.requestOutput(); } } }
1060413246zhaohong-
ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ModifiedAsyncNHttpServiceHandler.java
Java
asf20
26,831
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ package com.sky.musik; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; /** * Example of requesting and displaying an interstitial ad. */ public class InterstitialActivity extends Activity { private InterstitialAd mInterstitial; private Button mShowButton; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_interstitial); mInterstitial = new InterstitialAd(this); mInterstitial.setAdUnitId(getResources().getString(R.string.ad_unit_id)); mInterstitial.setAdListener(new ToastAdListener(this) { @Override public void onAdLoaded() { super.onAdLoaded(); mShowButton.setText("Show Interstitial"); mShowButton.setEnabled(true); } @Override public void onAdFailedToLoad(int errorCode) { super.onAdFailedToLoad(errorCode); mShowButton.setText("Ad Failed to Load"); mShowButton.setEnabled(false); } }); mShowButton = (Button) findViewById(R.id.showButton); mShowButton.setEnabled(false); } public void loadInterstitial(View unusedView) { mShowButton.setText("Loading Interstitial..."); mShowButton.setEnabled(false); mInterstitial.loadAd(new AdRequest.Builder().build()); } public void showInterstitial(View unusedView) { if (mInterstitial.isLoaded()) { mInterstitial.show(); } mShowButton.setText("Interstitial Not Ready"); mShowButton.setEnabled(false); } }
0e8c07ac7597ee3feadc6087f2569f63
trunk/skymusik/src/com/sky/musik/InterstitialActivity.java
Java
oos
2,511
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ package com.sky.musik.activity; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.widget.SlidingDrawer; import android.widget.Toast; import com.sky.musik.R; /** * Example of including a Google banner ad in code and listening for ad events. */ @SuppressWarnings("deprecation") public class PlayerActivity extends Activity { SlidingDrawer sliding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.player); sliding = (SlidingDrawer) findViewById(R.id.player_sliding); } @Override public boolean onTouchEvent(MotionEvent event) { //Toast.makeText(getApplicationContext(), "aaaa", Toast.LENGTH_SHORT).show(); sliding.onTouchEvent(event); return super.onTouchEvent(event); } }
0e8c07ac7597ee3feadc6087f2569f63
trunk/skymusik/src/com/sky/musik/activity/PlayerActivity.java
Java
oos
1,446
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ package com.sky.musik; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; /** * Displays examples of integrating different ad formats with the Google AdMob SDK for * Android. */ public class GoogleAdsSampleActivity extends ListActivity { private static class Sample { private String mTitle; private Class<? extends Activity> mActivityClass; private Sample(String title, Class<? extends Activity> activityClass) { mTitle = title; mActivityClass = activityClass; } @Override public String toString() { return mTitle; } public Class<? extends Activity> getActivityClass() { return mActivityClass; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Resources res = getResources(); Sample[] samples = { new Sample(res.getString(R.string.banner_in_xml), BannerXmlActivity.class), new Sample(res.getString(R.string.banner_in_code), BannerCodeActivity.class), new Sample(res.getString(R.string.interstitial), InterstitialActivity.class) }; setListAdapter( new ArrayAdapter<Sample>(this, android.R.layout.simple_list_item_1, samples)); } @Override protected void onListItemClick(ListView listView, View view, int position, long id) { Sample sample = (Sample) listView.getItemAtPosition(position); Intent intent = new Intent(this.getApplicationContext(), sample.getActivityClass()); startActivity(intent); } }
0e8c07ac7597ee3feadc6087f2569f63
trunk/skymusik/src/com/sky/musik/GoogleAdsSampleActivity.java
Java
oos
2,453
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ package com.sky.musik; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import android.content.Context; import android.widget.Toast; /** * An ad listener that toasts all ad events. */ public class ToastAdListener extends AdListener { private Context mContext; public ToastAdListener(Context context) { this.mContext = context; } @Override public void onAdLoaded() { Toast.makeText(mContext, "onAdLoaded()", Toast.LENGTH_SHORT).show(); } @Override public void onAdFailedToLoad(int errorCode) { String errorReason = ""; switch(errorCode) { case AdRequest.ERROR_CODE_INTERNAL_ERROR: errorReason = "Internal error"; break; case AdRequest.ERROR_CODE_INVALID_REQUEST: errorReason = "Invalid request"; break; case AdRequest.ERROR_CODE_NETWORK_ERROR: errorReason = "Network Error"; break; case AdRequest.ERROR_CODE_NO_FILL: errorReason = "No fill"; break; } Toast.makeText(mContext, String.format("onAdFailedToLoad(%s)", errorReason), Toast.LENGTH_SHORT).show(); } @Override public void onAdOpened() { Toast.makeText(mContext, "onAdOpened()", Toast.LENGTH_SHORT).show(); } @Override public void onAdClosed() { Toast.makeText(mContext, "onAdClosed()", Toast.LENGTH_SHORT).show(); } @Override public void onAdLeftApplication() { Toast.makeText(mContext, "onAdLeftApplication()", Toast.LENGTH_SHORT).show(); } }
0e8c07ac7597ee3feadc6087f2569f63
trunk/skymusik/src/com/sky/musik/ToastAdListener.java
Java
oos
2,311
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ package com.sky.musik; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import android.app.Activity; import android.os.Bundle; /** * Example of including a Google banner ad in XML. */ public class BannerXmlActivity extends Activity { private AdView mAdView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_banner_xml); mAdView = (AdView) findViewById(R.id.adView); mAdView.setAdListener(new ToastAdListener(this)); mAdView.loadAd(new AdRequest.Builder().build()); } @Override protected void onPause() { mAdView.pause(); super.onPause(); } @Override protected void onResume() { super.onResume(); mAdView.resume(); } @Override protected void onDestroy() { mAdView.destroy(); super.onDestroy(); } }
0e8c07ac7597ee3feadc6087f2569f63
trunk/skymusik/src/com/sky/musik/BannerXmlActivity.java
Java
oos
1,589
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ package com.sky.musik; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import android.app.Activity; import android.os.Bundle; import android.widget.RelativeLayout; /** * Example of including a Google banner ad in code and listening for ad events. */ public class BannerCodeActivity extends Activity { private AdView mAdView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_banner_code_ad_listener); mAdView = new AdView(this); mAdView.setAdUnitId(getResources().getString(R.string.ad_unit_id)); mAdView.setAdSize(AdSize.BANNER); mAdView.setAdListener(new ToastAdListener(this)); RelativeLayout layout = (RelativeLayout) findViewById(R.id.mainLayout); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); layout.addView(mAdView, params); mAdView.loadAd(new AdRequest.Builder().build()); } @Override protected void onPause() { mAdView.pause(); super.onPause(); } @Override protected void onResume() { super.onResume(); mAdView.resume(); } @Override protected void onDestroy() { mAdView.destroy(); super.onDestroy(); } }
0e8c07ac7597ee3feadc6087f2569f63
trunk/skymusik/src/com/sky/musik/BannerCodeActivity.java
Java
oos
2,112
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ package com.sky.widget.navigation; import android.R; import android.app.ActionBar; import android.app.Activity; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.lang.reflect.Method; /** * This class encapsulates some awful hacks. * * Before JB-MR2 (API 18) it was not possible to change the home-as-up indicator glyph * in an action bar without some really gross hacks. Since the MR2 SDK is not published as of * this writing, the new API is accessed via reflection here if available. */ class ActionBarDrawerToggleHoneycomb { private static final String TAG = "ActionBarDrawerToggleHoneycomb"; private static final int[] THEME_ATTRS = new int[] { R.attr.homeAsUpIndicator }; public static Object setActionBarUpIndicator(Object info, Activity activity, Drawable drawable, int contentDescRes) { if (info == null) { info = new SetIndicatorInfo(activity); } final SetIndicatorInfo sii = (SetIndicatorInfo) info; if (sii.setHomeAsUpIndicator != null) { try { final ActionBar actionBar = activity.getActionBar(); sii.setHomeAsUpIndicator.invoke(actionBar, drawable); sii.setHomeActionContentDescription.invoke(actionBar, contentDescRes); } catch (Exception e) { Log.w(TAG, "Couldn't set home-as-up indicator via JB-MR2 API", e); } } else if (sii.upIndicatorView != null) { sii.upIndicatorView.setImageDrawable(drawable); } else { Log.w(TAG, "Couldn't set home-as-up indicator"); } return info; } public static Object setActionBarDescription(Object info, Activity activity, int contentDescRes) { if (info == null) { info = new SetIndicatorInfo(activity); } final SetIndicatorInfo sii = (SetIndicatorInfo) info; if (sii.setHomeAsUpIndicator != null) { try { final ActionBar actionBar = activity.getActionBar(); sii.setHomeActionContentDescription.invoke(actionBar, contentDescRes); } catch (Exception e) { Log.w(TAG, "Couldn't set content description via JB-MR2 API", e); } } return info; } public static Drawable getThemeUpIndicator(Activity activity) { final TypedArray a = activity.obtainStyledAttributes(THEME_ATTRS); final Drawable result = a.getDrawable(0); a.recycle(); return result; } private static class SetIndicatorInfo { public Method setHomeAsUpIndicator; public Method setHomeActionContentDescription; public ImageView upIndicatorView; SetIndicatorInfo(Activity activity) { try { setHomeAsUpIndicator = ActionBar.class.getDeclaredMethod("setHomeAsUpIndicator", Drawable.class); setHomeActionContentDescription = ActionBar.class.getDeclaredMethod( "setHomeActionContentDescription", Integer.TYPE); // If we got the method we won't need the stuff below. return; } catch (NoSuchMethodException e) { // Oh well. We'll use the other mechanism below instead. } final View home = activity.findViewById(android.R.id.home); if (home == null) { // Action bar doesn't have a known configuration, an OEM messed with things. return; } final ViewGroup parent = (ViewGroup) home.getParent(); final int childCount = parent.getChildCount(); if (childCount != 2) { // No idea which one will be the right one, an OEM messed with things. return; } final View first = parent.getChildAt(0); final View second = parent.getChildAt(1); final View up = first.getId() == android.R.id.home ? second : first; if (up instanceof ImageView) { // Jackpot! (Probably...) upIndicatorView = (ImageView) up; } } } }
0e8c07ac7597ee3feadc6087f2569f63
trunk/skymusik/src/com/sky/widget/navigation/ActionBarDrawerToggleHoneycomb.java
Java
oos
4,989
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ package com.sky.widget.navigation; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.support.v4.view.AccessibilityDelegateCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.KeyEventCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewGroupCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.widget.ViewDragHelper; import android.util.AttributeSet; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; /** * DrawerLayout acts as a top-level container for window content that allows for * interactive "drawer" views to be pulled out from the edge of the window. * * <p>Drawer positioning and layout is controlled using the <code>android:layout_gravity</code> * attribute on child views corresponding to which side of the view you want the drawer * to emerge from: left or right. (Or start/end on platform versions that support layout direction.) * </p> * * <p>To use a DrawerLayout, position your primary content view as the first child with * a width and height of <code>match_parent</code>. Add drawers as child views after the main * content view and set the <code>layout_gravity</code> appropriately. Drawers commonly use * <code>match_parent</code> for height with a fixed width.</p> * * <p>{@link DrawerListener} can be used to monitor the state and motion of drawer views. * Avoid performing expensive operations such as layout during animation as it can cause * stuttering; try to perform expensive operations during the {@link #STATE_IDLE} state. * {@link SimpleDrawerListener} offers default/no-op implementations of each callback method.</p> * * <p>As per the Android Design guide, any drawers positioned to the left/start should * always contain content for navigating around the application, whereas any drawers * positioned to the right/end should always contain actions to take on the current content. * This preserves the same navigation left, actions right structure present in the Action Bar * and elsewhere.</p> */ public class DrawerLayout extends ViewGroup { private static final String TAG = "DrawerLayout"; /** * Indicates that any drawers are in an idle, settled state. No animation is in progress. */ public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE; /** * Indicates that a drawer is currently being dragged by the user. */ public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING; /** * Indicates that a drawer is in the process of settling to a final position. */ public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING; /** * The drawer is unlocked. */ public static final int LOCK_MODE_UNLOCKED = 0; /** * The drawer is locked closed. The user may not open it, though * the app may open it programmatically. */ public static final int LOCK_MODE_LOCKED_CLOSED = 1; /** * The drawer is locked open. The user may not close it, though the app * may close it programmatically. */ public static final int LOCK_MODE_LOCKED_OPEN = 2; private static final int MIN_DRAWER_MARGIN = 64; // dp private static final int DEFAULT_SCRIM_COLOR = 0x99000000; /** * Length of time to delay before peeking the drawer. */ private static final int PEEK_DELAY = 160; // ms /** * Minimum velocity that will be detected as a fling */ private static final int MIN_FLING_VELOCITY = 400; // dips per second /** * Experimental feature. */ private static final boolean ALLOW_EDGE_LOCK = false; private static final boolean CHILDREN_DISALLOW_INTERCEPT = true; private static final float TOUCH_SLOP_SENSITIVITY = 1.f; private static final int[] LAYOUT_ATTRS = new int[] { android.R.attr.layout_gravity }; private int mMinDrawerMargin; private int mScrimColor = DEFAULT_SCRIM_COLOR; private float mScrimOpacity; private Paint mScrimPaint = new Paint(); private final ViewDragHelper mLeftDragger; private final ViewDragHelper mRightDragger; private final ViewDragCallback mLeftCallback; private final ViewDragCallback mRightCallback; private int mDrawerState; private boolean mInLayout; private boolean mFirstLayout = true; private int mLockModeLeft; private int mLockModeRight; private boolean mDisallowInterceptRequested; private boolean mChildrenCanceledTouch; private DrawerListener mListener; private float mInitialMotionX; private float mInitialMotionY; private Drawable mShadowLeft; private Drawable mShadowRight; /** * Listener for monitoring events about drawers. */ public interface DrawerListener { /** * Called when a drawer's position changes. * @param drawerView The child view that was moved * @param slideOffset The new offset of this drawer within its range, from 0-1 */ public void onDrawerSlide(View drawerView, float slideOffset); /** * Called when a drawer has settled in a completely open state. * The drawer is interactive at this point. * * @param drawerView Drawer view that is now open */ public void onDrawerOpened(View drawerView); /** * Called when a drawer has settled in a completely closed state. * * @param drawerView Drawer view that is now closed */ public void onDrawerClosed(View drawerView); /** * Called when the drawer motion state changes. The new state will * be one of {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}. * * @param newState The new drawer motion state */ public void onDrawerStateChanged(int newState); } /** * Stub/no-op implementations of all methods of {@link DrawerListener}. * Override this if you only care about a few of the available callback methods. */ public static abstract class SimpleDrawerListener implements DrawerListener { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } } public DrawerLayout(Context context) { this(context, null); } public DrawerLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DrawerLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final float density = getResources().getDisplayMetrics().density; mMinDrawerMargin = (int) (MIN_DRAWER_MARGIN * density + 0.5f); final float minVel = MIN_FLING_VELOCITY * density; mLeftCallback = new ViewDragCallback(Gravity.LEFT); mRightCallback = new ViewDragCallback(Gravity.RIGHT); mLeftDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mLeftCallback); mLeftDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); mLeftDragger.setMinVelocity(minVel); mLeftCallback.setDragger(mLeftDragger); mRightDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mRightCallback); mRightDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT); mRightDragger.setMinVelocity(minVel); mRightCallback.setDragger(mRightDragger); // So that we can catch the back button setFocusableInTouchMode(true); ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate()); ViewGroupCompat.setMotionEventSplittingEnabled(this, false); } /** * Set a simple drawable used for the left or right shadow. * The drawable provided must have a nonzero intrinsic width. * * @param shadowDrawable Shadow drawable to use at the edge of a drawer * @param gravity Which drawer the shadow should apply to */ public void setDrawerShadow(Drawable shadowDrawable, int gravity) { /* * TODO Someone someday might want to set more complex drawables here. * They're probably nuts, but we might want to consider registering callbacks, * setting states, etc. properly. */ final int absGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); if ((absGravity & Gravity.LEFT) == Gravity.LEFT) { mShadowLeft = shadowDrawable; invalidate(); } if ((absGravity & Gravity.RIGHT) == Gravity.RIGHT) { mShadowRight = shadowDrawable; invalidate(); } } /** * Set a simple drawable used for the left or right shadow. * The drawable provided must have a nonzero intrinsic width. * * @param resId Resource id of a shadow drawable to use at the edge of a drawer * @param gravity Which drawer the shadow should apply to */ public void setDrawerShadow(int resId, int gravity) { setDrawerShadow(getResources().getDrawable(resId), gravity); } /** * Set a color to use for the scrim that obscures primary content while a drawer is open. * * @param color Color to use in 0xAARRGGBB format. */ public void setScrimColor(int color) { mScrimColor = color; invalidate(); } /** * Set a listener to be notified of drawer events. * * @param listener Listener to notify when drawer events occur * @see DrawerListener */ public void setDrawerListener(DrawerListener listener) { mListener = listener; } /** * Enable or disable interaction with all drawers. * * <p>This allows the application to restrict the user's ability to open or close * any drawer within this layout. DrawerLayout will still respond to calls to * {@link #openDrawer(int)}, {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking drawers open or closed will implicitly open or close * any drawers as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. */ public void setDrawerLockMode(int lockMode) { setDrawerLockMode(lockMode, Gravity.LEFT); setDrawerLockMode(lockMode, Gravity.RIGHT); } /** * Enable or disable interaction with the given drawer. * * <p>This allows the application to restrict the user's ability to open or close * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking a drawer open or closed will implicitly open or close * that drawer as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. * @param edgeGravity Gravity.LEFT, RIGHT, START or END. * Expresses which drawer to change the mode for. * * @see #LOCK_MODE_UNLOCKED * @see #LOCK_MODE_LOCKED_CLOSED * @see #LOCK_MODE_LOCKED_OPEN */ public void setDrawerLockMode(int lockMode, int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity(edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { mLockModeLeft = lockMode; } else if (absGravity == Gravity.RIGHT) { mLockModeRight = lockMode; } if (lockMode != LOCK_MODE_UNLOCKED) { // Cancel interaction in progress final ViewDragHelper helper = absGravity == Gravity.LEFT ? mLeftDragger : mRightDragger; helper.cancel(); } switch (lockMode) { case LOCK_MODE_LOCKED_OPEN: final View toOpen = findDrawerWithGravity(absGravity); if (toOpen != null) { openDrawer(toOpen); } break; case LOCK_MODE_LOCKED_CLOSED: final View toClose = findDrawerWithGravity(absGravity); if (toClose != null) { closeDrawer(toClose); } break; // default: do nothing } } /** * Enable or disable interaction with the given drawer. * * <p>This allows the application to restrict the user's ability to open or close * the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)}, * {@link #closeDrawer(int)} and friends if a drawer is locked.</p> * * <p>Locking a drawer open or closed will implicitly open or close * that drawer as appropriate.</p> * * @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED}, * {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}. * @param drawerView The drawer view to change the lock mode for * * @see #LOCK_MODE_UNLOCKED * @see #LOCK_MODE_LOCKED_CLOSED * @see #LOCK_MODE_LOCKED_OPEN */ public void setDrawerLockMode(int lockMode, View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a " + "drawer with appropriate layout_gravity"); } final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity; setDrawerLockMode(lockMode, gravity); } /** * Check the lock mode of the drawer with the given gravity. * * @param edgeGravity Gravity of the drawer to check * @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or * {@link #LOCK_MODE_LOCKED_OPEN}. */ public int getDrawerLockMode(int edgeGravity) { final int absGravity = GravityCompat.getAbsoluteGravity( edgeGravity, ViewCompat.getLayoutDirection(this)); if (absGravity == Gravity.LEFT) { return mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return mLockModeRight; } return LOCK_MODE_UNLOCKED; } /** * Check the lock mode of the given drawer view. * * @param drawerView Drawer view to check lock mode * @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or * {@link #LOCK_MODE_LOCKED_OPEN}. */ public int getDrawerLockMode(View drawerView) { final int absGravity = getDrawerViewAbsoluteGravity(drawerView); if (absGravity == Gravity.LEFT) { return mLockModeLeft; } else if (absGravity == Gravity.RIGHT) { return mLockModeRight; } return LOCK_MODE_UNLOCKED; } /** * Resolve the shared state of all drawers from the component ViewDragHelpers. * Should be called whenever a ViewDragHelper's state changes. */ void updateDrawerState(int forGravity, int activeState, View activeDrawer) { final int leftState = mLeftDragger.getViewDragState(); final int rightState = mRightDragger.getViewDragState(); final int state; if (leftState == STATE_DRAGGING || rightState == STATE_DRAGGING) { state = STATE_DRAGGING; } else if (leftState == STATE_SETTLING || rightState == STATE_SETTLING) { state = STATE_SETTLING; } else { state = STATE_IDLE; } if (activeDrawer != null && activeState == STATE_IDLE) { final LayoutParams lp = (LayoutParams) activeDrawer.getLayoutParams(); if (lp.onScreen == 0) { dispatchOnDrawerClosed(activeDrawer); } else if (lp.onScreen == 1) { dispatchOnDrawerOpened(activeDrawer); } } if (state != mDrawerState) { mDrawerState = state; if (mListener != null) { mListener.onDrawerStateChanged(state); } } } void dispatchOnDrawerClosed(View drawerView) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (lp.knownOpen) { lp.knownOpen = false; if (mListener != null) { mListener.onDrawerClosed(drawerView); } sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } } void dispatchOnDrawerOpened(View drawerView) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (!lp.knownOpen) { lp.knownOpen = true; if (mListener != null) { mListener.onDrawerOpened(drawerView); } drawerView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } } void dispatchOnDrawerSlide(View drawerView, float slideOffset) { if (mListener != null) { mListener.onDrawerSlide(drawerView, slideOffset); } } void setDrawerViewOffset(View drawerView, float slideOffset) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); if (slideOffset == lp.onScreen) { return; } lp.onScreen = slideOffset; dispatchOnDrawerSlide(drawerView, slideOffset); } float getDrawerViewOffset(View drawerView) { return ((LayoutParams) drawerView.getLayoutParams()).onScreen; } /** * @return the absolute gravity of the child drawerView, resolved according * to the current layout direction */ int getDrawerViewAbsoluteGravity(View drawerView) { final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity; return GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(this)); } boolean checkDrawerViewAbsoluteGravity(View drawerView, int checkFor) { final int absGravity = getDrawerViewAbsoluteGravity(drawerView); return (absGravity & checkFor) == checkFor; } View findOpenDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (((LayoutParams) child.getLayoutParams()).knownOpen) { return child; } } return null; } void moveDrawerToOffset(View drawerView, float slideOffset) { final float oldOffset = getDrawerViewOffset(drawerView); final int width = drawerView.getWidth(); final int oldPos = (int) (width * oldOffset); final int newPos = (int) (width * slideOffset); final int dx = newPos - oldPos; drawerView.offsetLeftAndRight( checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT) ? dx : -dx); setDrawerViewOffset(drawerView, slideOffset); } /** * @param gravity the gravity of the child to return. If specified as a * relative value, it will be resolved according to the current * layout direction. * @return the drawer with the specified gravity */ View findDrawerWithGravity(int gravity) { final int absHorizGravity = GravityCompat.getAbsoluteGravity( gravity, ViewCompat.getLayoutDirection(this)) & Gravity.HORIZONTAL_GRAVITY_MASK; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final int childAbsGravity = getDrawerViewAbsoluteGravity(child); if ((childAbsGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == absHorizGravity) { return child; } } return null; } /** * Simple gravity to string - only supports LEFT and RIGHT for debugging output. * * @param gravity Absolute gravity value * @return LEFT or RIGHT as appropriate, or a hex string */ static String gravityToString(int gravity) { if ((gravity & Gravity.LEFT) == Gravity.LEFT) { return "LEFT"; } if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) { return "RIGHT"; } return Integer.toHexString(gravity); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mFirstLayout = true; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mFirstLayout = true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) { if (isInEditMode()) { // Don't crash the layout editor. Consume all of the space if specified // or pick a magic number from thin air otherwise. // TODO Better communication with tools of this bogus state. // It will crash on a real device. if (widthMode == MeasureSpec.AT_MOST) { widthMode = MeasureSpec.EXACTLY; } else if (widthMode == MeasureSpec.UNSPECIFIED) { widthMode = MeasureSpec.EXACTLY; widthSize = 300; } if (heightMode == MeasureSpec.AT_MOST) { heightMode = MeasureSpec.EXACTLY; } else if (heightMode == MeasureSpec.UNSPECIFIED) { heightMode = MeasureSpec.EXACTLY; heightSize = 300; } } else { throw new IllegalArgumentException( "DrawerLayout must be measured with MeasureSpec.EXACTLY."); } } setMeasuredDimension(widthSize, heightSize); // Gravity value for each drawer we've seen. Only one of each permitted. int foundDrawers = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (isContentView(child)) { // Content views get measured at exactly the layout's size. final int contentWidthSpec = MeasureSpec.makeMeasureSpec( widthSize - lp.leftMargin - lp.rightMargin, MeasureSpec.EXACTLY); final int contentHeightSpec = MeasureSpec.makeMeasureSpec( heightSize - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY); child.measure(contentWidthSpec, contentHeightSpec); } else if (isDrawerView(child)) { final int childGravity = getDrawerViewAbsoluteGravity(child) & Gravity.HORIZONTAL_GRAVITY_MASK; if ((foundDrawers & childGravity) != 0) { throw new IllegalStateException("Child drawer has absolute gravity " + gravityToString(childGravity) + " but this " + TAG + " already has a " + "drawer view along that edge"); } final int drawerWidthSpec = getChildMeasureSpec(widthMeasureSpec, mMinDrawerMargin + lp.leftMargin + lp.rightMargin, lp.width); final int drawerHeightSpec = getChildMeasureSpec(heightMeasureSpec, lp.topMargin + lp.bottomMargin, lp.height); child.measure(drawerWidthSpec, drawerHeightSpec); } else { throw new IllegalStateException("Child " + child + " at index " + i + " does not have a valid layout_gravity - must be Gravity.LEFT, " + "Gravity.RIGHT or Gravity.NO_GRAVITY"); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; final int width = r - l; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (isContentView(child)) { child.layout(lp.leftMargin, lp.topMargin, lp.leftMargin + child.getMeasuredWidth(), lp.topMargin + child.getMeasuredHeight()); } else { // Drawer, if it wasn't onMeasure would have thrown an exception. final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); int childLeft; final float newOffset; if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { childLeft = -childWidth + (int) (childWidth * lp.onScreen); newOffset = (float) (childWidth + childLeft) / childWidth; } else { // Right; onMeasure checked for us. childLeft = width - (int) (childWidth * lp.onScreen); newOffset = (float) (width - childLeft) / childWidth; } final boolean changeOffset = newOffset != lp.onScreen; final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (vgrav) { default: case Gravity.TOP: { child.layout(childLeft, lp.topMargin, childLeft + childWidth, lp.topMargin + childHeight); break; } case Gravity.BOTTOM: { final int height = b - t; child.layout(childLeft, height - lp.bottomMargin - child.getMeasuredHeight(), childLeft + childWidth, height - lp.bottomMargin); break; } case Gravity.CENTER_VERTICAL: { final int height = b - t; int childTop = (height - childHeight) / 2; // Offset for margins. If things don't fit right because of // bad measurement before, oh well. if (childTop < lp.topMargin) { childTop = lp.topMargin; } else if (childTop + childHeight > height - lp.bottomMargin) { childTop = height - lp.bottomMargin - childHeight; } child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); break; } } if (changeOffset) { setDrawerViewOffset(child, newOffset); } final int newVisibility = lp.onScreen > 0 ? VISIBLE : INVISIBLE; if (child.getVisibility() != newVisibility) { child.setVisibility(newVisibility); } } } mInLayout = false; mFirstLayout = false; } @Override public void requestLayout() { if (!mInLayout) { super.requestLayout(); } } @Override public void computeScroll() { final int childCount = getChildCount(); float scrimOpacity = 0; for (int i = 0; i < childCount; i++) { final float onscreen = ((LayoutParams) getChildAt(i).getLayoutParams()).onScreen; scrimOpacity = Math.max(scrimOpacity, onscreen); } mScrimOpacity = scrimOpacity; // "|" used on purpose; both need to run. if (mLeftDragger.continueSettling(true) | mRightDragger.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } private static boolean hasOpaqueBackground(View v) { final Drawable bg = v.getBackground(); if (bg != null) { return bg.getOpacity() == PixelFormat.OPAQUE; } return false; } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { final int height = getHeight(); final boolean drawingContent = isContentView(child); int clipLeft = 0, clipRight = getWidth(); final int restoreCount = canvas.save(); if (drawingContent) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View v = getChildAt(i); if (v == child || v.getVisibility() != VISIBLE || !hasOpaqueBackground(v) || !isDrawerView(v) || v.getHeight() < height) { continue; } if (checkDrawerViewAbsoluteGravity(v, Gravity.LEFT)) { final int vright = v.getRight(); if (vright > clipLeft) clipLeft = vright; } else { final int vleft = v.getLeft(); if (vleft < clipRight) clipRight = vleft; } } canvas.clipRect(clipLeft, 0, clipRight, getHeight()); } final boolean result = super.drawChild(canvas, child, drawingTime); canvas.restoreToCount(restoreCount); if (mScrimOpacity > 0 && drawingContent) { final int baseAlpha = (mScrimColor & 0xff000000) >>> 24; final int imag = (int) (baseAlpha * mScrimOpacity); final int color = imag << 24 | (mScrimColor & 0xffffff); mScrimPaint.setColor(color); canvas.drawRect(clipLeft, 0, clipRight, getHeight(), mScrimPaint); } else if (mShadowLeft != null && checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { final int shadowWidth = mShadowLeft.getIntrinsicWidth(); final int childRight = child.getRight(); final int drawerPeekDistance = mLeftDragger.getEdgeSize(); final float alpha = Math.max(0, Math.min((float) childRight / drawerPeekDistance, 1.f)); mShadowLeft.setBounds(childRight, child.getTop(), childRight + shadowWidth, child.getBottom()); mShadowLeft.setAlpha((int) (0xff * alpha)); mShadowLeft.draw(canvas); } else if (mShadowRight != null && checkDrawerViewAbsoluteGravity(child, Gravity.RIGHT)) { final int shadowWidth = mShadowRight.getIntrinsicWidth(); final int childLeft = child.getLeft(); final int showing = getWidth() - childLeft; final int drawerPeekDistance = mRightDragger.getEdgeSize(); final float alpha = Math.max(0, Math.min((float) showing / drawerPeekDistance, 1.f)); mShadowRight.setBounds(childLeft - shadowWidth, child.getTop(), childLeft, child.getBottom()); mShadowRight.setAlpha((int) (0xff * alpha)); mShadowRight.draw(canvas); } return result; } boolean isContentView(View child) { return ((LayoutParams) child.getLayoutParams()).gravity == Gravity.NO_GRAVITY; } boolean isDrawerView(View child) { final int gravity = ((LayoutParams) child.getLayoutParams()).gravity; final int absGravity = GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(child)); return (absGravity & (Gravity.LEFT | Gravity.RIGHT)) != 0; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { final int action = MotionEventCompat.getActionMasked(ev); // "|" used deliberately here; both methods should be invoked. final boolean interceptForDrag = mLeftDragger.shouldInterceptTouchEvent(ev) | mRightDragger.shouldInterceptTouchEvent(ev); boolean interceptForTap = false; switch (action) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mInitialMotionX = x; mInitialMotionY = y; if (mScrimOpacity > 0 && isContentView(mLeftDragger.findTopChildUnder((int) x, (int) y))) { interceptForTap = true; } mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_MOVE: { // If we cross the touch slop, don't perform the delayed peek for an edge touch. if (mLeftDragger.checkTouchSlop(ViewDragHelper.DIRECTION_ALL)) { mLeftCallback.removeCallbacks(); mRightCallback.removeCallbacks(); } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { closeDrawers(true); mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; } } return interceptForDrag || interceptForTap || hasPeekingDrawer() || mChildrenCanceledTouch; } @Override public boolean onTouchEvent(MotionEvent ev) { mLeftDragger.processTouchEvent(ev); mRightDragger.processTouchEvent(ev); final int action = ev.getAction(); boolean wantTouchEvents = true; switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mInitialMotionX = x; mInitialMotionY = y; mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } case MotionEvent.ACTION_UP: { final float x = ev.getX(); final float y = ev.getY(); boolean peekingOnly = true; final View touchedView = mLeftDragger.findTopChildUnder((int) x, (int) y); if (touchedView != null && isContentView(touchedView)) { final float dx = x - mInitialMotionX; final float dy = y - mInitialMotionY; final int slop = mLeftDragger.getTouchSlop(); if (dx * dx + dy * dy < slop * slop) { // Taps close a dimmed open drawer but only if it isn't locked open. final View openDrawer = findOpenDrawer(); if (openDrawer != null) { peekingOnly = getDrawerLockMode(openDrawer) == LOCK_MODE_LOCKED_OPEN; } } } closeDrawers(peekingOnly); mDisallowInterceptRequested = false; break; } case MotionEvent.ACTION_CANCEL: { closeDrawers(true); mDisallowInterceptRequested = false; mChildrenCanceledTouch = false; break; } } return wantTouchEvents; } public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (CHILDREN_DISALLOW_INTERCEPT || (!mLeftDragger.isEdgeTouched(ViewDragHelper.EDGE_LEFT) && !mRightDragger.isEdgeTouched(ViewDragHelper.EDGE_RIGHT))) { // If we have an edge touch we want to skip this and track it for later instead. super.requestDisallowInterceptTouchEvent(disallowIntercept); } mDisallowInterceptRequested = disallowIntercept; if (disallowIntercept) { closeDrawers(true); } } /** * Close all currently open drawer views by animating them out of view. */ public void closeDrawers() { closeDrawers(false); } void closeDrawers(boolean peekingOnly) { boolean needsInvalidate = false; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!isDrawerView(child) || (peekingOnly && !lp.isPeeking)) { continue; } final int childWidth = child.getWidth(); if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { needsInvalidate |= mLeftDragger.smoothSlideViewTo(child, -childWidth, child.getTop()); } else { needsInvalidate |= mRightDragger.smoothSlideViewTo(child, getWidth(), child.getTop()); } lp.isPeeking = false; } mLeftCallback.removeCallbacks(); mRightCallback.removeCallbacks(); if (needsInvalidate) { invalidate(); } } /** * Open the specified drawer view by animating it into view. * * @param drawerView Drawer view to open */ public void openDrawer(View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer"); } if (mFirstLayout) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); lp.onScreen = 1.f; lp.knownOpen = true; } else { if (checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { mLeftDragger.smoothSlideViewTo(drawerView, 0, drawerView.getTop()); } else { mRightDragger.smoothSlideViewTo(drawerView, getWidth() - drawerView.getWidth(), drawerView.getTop()); } } invalidate(); } /** * Open the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * GravityCompat.START or GravityCompat.END may also be used. */ public void openDrawer(int gravity) { final View drawerView = findDrawerWithGravity(gravity); if (drawerView == null) { throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity)); } openDrawer(drawerView); } /** * Close the specified drawer view by animating it into view. * * @param drawerView Drawer view to close */ public void closeDrawer(View drawerView) { if (!isDrawerView(drawerView)) { throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer"); } if (mFirstLayout) { final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams(); lp.onScreen = 0.f; lp.knownOpen = false; } else { if (checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) { mLeftDragger.smoothSlideViewTo(drawerView, -drawerView.getWidth(), drawerView.getTop()); } else { mRightDragger.smoothSlideViewTo(drawerView, getWidth(), drawerView.getTop()); } } invalidate(); } /** * Close the specified drawer by animating it out of view. * * @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. * GravityCompat.START or GravityCompat.END may also be used. */ public void closeDrawer(int gravity) { final View drawerView = findDrawerWithGravity(gravity); if (drawerView == null) { throw new IllegalArgumentException("No drawer view found with gravity " + gravityToString(gravity)); } closeDrawer(drawerView); } /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. To check for partial visibility use * {@link #isDrawerVisible(android.view.View)}. * * @param drawer Drawer view to check * @return true if the given drawer view is in an open state * @see #isDrawerVisible(android.view.View) */ public boolean isDrawerOpen(View drawer) { if (!isDrawerView(drawer)) { throw new IllegalArgumentException("View " + drawer + " is not a drawer"); } return ((LayoutParams) drawer.getLayoutParams()).knownOpen; } /** * Check if the given drawer view is currently in an open state. * To be considered "open" the drawer must have settled into its fully * visible state. If there is no drawer with the given gravity this method * will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer view is in an open state */ public boolean isDrawerOpen(int drawerGravity) { final View drawerView = findDrawerWithGravity(drawerGravity); if (drawerView != null) { return isDrawerOpen(drawerView); } return false; } /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere inbetween. * * @param drawer Drawer view to check * @return true if the given drawer is visible on-screen * @see #isDrawerOpen(android.view.View) */ public boolean isDrawerVisible(View drawer) { if (!isDrawerView(drawer)) { throw new IllegalArgumentException("View " + drawer + " is not a drawer"); } return ((LayoutParams) drawer.getLayoutParams()).onScreen > 0; } /** * Check if a given drawer view is currently visible on-screen. The drawer * may be only peeking onto the screen, fully extended, or anywhere inbetween. * If there is no drawer with the given gravity this method will return false. * * @param drawerGravity Gravity of the drawer to check * @return true if the given drawer is visible on-screen */ public boolean isDrawerVisible(int drawerGravity) { final View drawerView = findDrawerWithGravity(drawerGravity); if (drawerView != null) { return isDrawerVisible(drawerView); } return false; } private boolean hasPeekingDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final LayoutParams lp = (LayoutParams) getChildAt(i).getLayoutParams(); if (lp.isPeeking) { return true; } } return false; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams ? new LayoutParams((LayoutParams) p) : p instanceof ViewGroup.MarginLayoutParams ? new LayoutParams((MarginLayoutParams) p) : new LayoutParams(p); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams && super.checkLayoutParams(p); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } private boolean hasVisibleDrawer() { return findVisibleDrawer() != null; } private View findVisibleDrawer() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (isDrawerView(child) && isDrawerVisible(child)) { return child; } } return null; } void cancelChildViewTouch() { // Cancel child touches if (!mChildrenCanceledTouch) { final long now = SystemClock.uptimeMillis(); final MotionEvent cancelEvent = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { getChildAt(i).dispatchTouchEvent(cancelEvent); } cancelEvent.recycle(); mChildrenCanceledTouch = true; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && hasVisibleDrawer()) { KeyEventCompat.startTracking(event); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { final View visibleDrawer = findVisibleDrawer(); if (visibleDrawer != null && getDrawerLockMode(visibleDrawer) == LOCK_MODE_UNLOCKED) { closeDrawers(); } return visibleDrawer != null; } return super.onKeyUp(keyCode, event); } @Override protected void onRestoreInstanceState(Parcelable state) { final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (ss.openDrawerGravity != Gravity.NO_GRAVITY) { final View toOpen = findDrawerWithGravity(ss.openDrawerGravity); if (toOpen != null) { openDrawer(toOpen); } } setDrawerLockMode(ss.lockModeLeft, Gravity.LEFT); setDrawerLockMode(ss.lockModeRight, Gravity.RIGHT); } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); final SavedState ss = new SavedState(superState); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (!isDrawerView(child)) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.knownOpen) { ss.openDrawerGravity = lp.gravity; // Only one drawer can be open at a time. break; } } ss.lockModeLeft = mLockModeLeft; ss.lockModeRight = mLockModeRight; return ss; } /** * State persisted across instances */ protected static class SavedState extends BaseSavedState { int openDrawerGravity = Gravity.NO_GRAVITY; int lockModeLeft = LOCK_MODE_UNLOCKED; int lockModeRight = LOCK_MODE_UNLOCKED; public SavedState(Parcel in) { super(in); openDrawerGravity = in.readInt(); } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(openDrawerGravity); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel source) { return new SavedState(source); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } private class ViewDragCallback extends ViewDragHelper.Callback { private final int mAbsGravity; private ViewDragHelper mDragger; private final Runnable mPeekRunnable = new Runnable() { @Override public void run() { peekDrawer(); } }; public ViewDragCallback(int gravity) { mAbsGravity = gravity; } public void setDragger(ViewDragHelper dragger) { mDragger = dragger; } public void removeCallbacks() { DrawerLayout.this.removeCallbacks(mPeekRunnable); } @Override public boolean tryCaptureView(View child, int pointerId) { // Only capture views where the gravity matches what we're looking for. // This lets us use two ViewDragHelpers, one for each side drawer. return isDrawerView(child) && checkDrawerViewAbsoluteGravity(child, mAbsGravity) && getDrawerLockMode(child) == LOCK_MODE_UNLOCKED; } @Override public void onViewDragStateChanged(int state) { updateDrawerState(mAbsGravity, state, mDragger.getCapturedView()); } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { float offset; final int childWidth = changedView.getWidth(); // This reverses the positioning shown in onLayout. if (checkDrawerViewAbsoluteGravity(changedView, Gravity.LEFT)) { offset = (float) (childWidth + left) / childWidth; } else { final int width = getWidth(); offset = (float) (width - left) / childWidth; } setDrawerViewOffset(changedView, offset); changedView.setVisibility(offset == 0 ? INVISIBLE : VISIBLE); invalidate(); } @Override public void onViewCaptured(View capturedChild, int activePointerId) { final LayoutParams lp = (LayoutParams) capturedChild.getLayoutParams(); lp.isPeeking = false; closeOtherDrawer(); } private void closeOtherDrawer() { final int otherGrav = mAbsGravity == Gravity.LEFT ? Gravity.RIGHT : Gravity.LEFT; final View toClose = findDrawerWithGravity(otherGrav); if (toClose != null) { closeDrawer(toClose); } } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { // Offset is how open the drawer is, therefore left/right values // are reversed from one another. final float offset = getDrawerViewOffset(releasedChild); final int childWidth = releasedChild.getWidth(); int left; if (checkDrawerViewAbsoluteGravity(releasedChild, Gravity.LEFT)) { left = xvel > 0 || xvel == 0 && offset > 0.5f ? 0 : -childWidth; } else { final int width = getWidth(); left = xvel < 0 || xvel == 0 && offset > 0.5f ? width - childWidth : width; } mDragger.settleCapturedViewAt(left, releasedChild.getTop()); invalidate(); } @Override public void onEdgeTouched(int edgeFlags, int pointerId) { postDelayed(mPeekRunnable, PEEK_DELAY); } private void peekDrawer() { final View toCapture; final int childLeft; final int peekDistance = mDragger.getEdgeSize(); final boolean leftEdge = mAbsGravity == Gravity.LEFT; if (leftEdge) { toCapture = findDrawerWithGravity(Gravity.LEFT); childLeft = (toCapture != null ? -toCapture.getWidth() : 0) + peekDistance; } else { toCapture = findDrawerWithGravity(Gravity.RIGHT); childLeft = getWidth() - peekDistance; } // Only peek if it would mean making the drawer more visible and the drawer isn't locked if (toCapture != null && ((leftEdge && toCapture.getLeft() < childLeft) || (!leftEdge && toCapture.getLeft() > childLeft)) && getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) { final LayoutParams lp = (LayoutParams) toCapture.getLayoutParams(); mDragger.smoothSlideViewTo(toCapture, childLeft, toCapture.getTop()); lp.isPeeking = true; invalidate(); closeOtherDrawer(); cancelChildViewTouch(); } } @Override public boolean onEdgeLock(int edgeFlags) { if (ALLOW_EDGE_LOCK) { final View drawer = findDrawerWithGravity(mAbsGravity); if (drawer != null && !isDrawerOpen(drawer)) { closeDrawer(drawer); } return true; } return false; } @Override public void onEdgeDragStarted(int edgeFlags, int pointerId) { final View toCapture; if ((edgeFlags & ViewDragHelper.EDGE_LEFT) == ViewDragHelper.EDGE_LEFT) { toCapture = findDrawerWithGravity(Gravity.LEFT); } else { toCapture = findDrawerWithGravity(Gravity.RIGHT); } if (toCapture != null && getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) { mDragger.captureChildView(toCapture, pointerId); } } @Override public int getViewHorizontalDragRange(View child) { return child.getWidth(); } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { if (checkDrawerViewAbsoluteGravity(child, Gravity.LEFT)) { return Math.max(-child.getWidth(), Math.min(left, 0)); } else { final int width = getWidth(); return Math.max(width - child.getWidth(), Math.min(left, width)); } } @Override public int clampViewPositionVertical(View child, int top, int dy) { return child.getTop(); } } public static class LayoutParams extends ViewGroup.MarginLayoutParams { public int gravity = Gravity.NO_GRAVITY; float onScreen; boolean isPeeking; boolean knownOpen; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); final TypedArray a = c.obtainStyledAttributes(attrs, LAYOUT_ATTRS); this.gravity = a.getInt(0, Gravity.NO_GRAVITY); a.recycle(); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(int width, int height, int gravity) { this(width, height); this.gravity = gravity; } public LayoutParams(LayoutParams source) { super(source); this.gravity = source.gravity; } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); } } class AccessibilityDelegate extends AccessibilityDelegateCompat { private final Rect mTmpRect = new Rect(); @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { final AccessibilityNodeInfoCompat superNode = AccessibilityNodeInfoCompat.obtain(info); super.onInitializeAccessibilityNodeInfo(host, superNode); info.setSource(host); final ViewParent parent = ViewCompat.getParentForAccessibility(host); if (parent instanceof View) { info.setParent((View) parent); } copyNodeInfoNoChildren(info, superNode); superNode.recycle(); addChildrenForAccessibility(info, (ViewGroup) host); } private void addChildrenForAccessibility(AccessibilityNodeInfoCompat info, ViewGroup v) { final int childCount = v.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = v.getChildAt(i); if (filter(child)) { continue; } // Adding children that are marked as not important for // accessibility will break the hierarchy, so we need to check // that value and re-parent views if necessary. final int importance = ViewCompat.getImportantForAccessibility(child); switch (importance) { case ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS: // Always skip NO_HIDE views and their descendants. break; case ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO: // Re-parent children of NO view groups, skip NO views. if (child instanceof ViewGroup) { addChildrenForAccessibility(info, (ViewGroup) child); } break; case ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO: // Force AUTO views to YES and add them. ViewCompat.setImportantForAccessibility( child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); case ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES: info.addChild(child); break; } } } @Override public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) { if (!filter(child)) { return super.onRequestSendAccessibilityEvent(host, child, event); } return false; } public boolean filter(View child) { final View openDrawer = findOpenDrawer(); return openDrawer != null && openDrawer != child; } /** * This should really be in AccessibilityNodeInfoCompat, but there unfortunately * seem to be a few elements that are not easily cloneable using the underlying API. * Leave it private here as it's not general-purpose useful. */ private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat dest, AccessibilityNodeInfoCompat src) { final Rect rect = mTmpRect; src.getBoundsInParent(rect); dest.setBoundsInParent(rect); src.getBoundsInScreen(rect); dest.setBoundsInScreen(rect); dest.setVisibleToUser(src.isVisibleToUser()); dest.setPackageName(src.getPackageName()); dest.setClassName(src.getClassName()); dest.setContentDescription(src.getContentDescription()); dest.setEnabled(src.isEnabled()); dest.setClickable(src.isClickable()); dest.setFocusable(src.isFocusable()); dest.setFocused(src.isFocused()); dest.setAccessibilityFocused(src.isAccessibilityFocused()); dest.setSelected(src.isSelected()); dest.setLongClickable(src.isLongClickable()); dest.addAction(src.getActions()); } } }
0e8c07ac7597ee3feadc6087f2569f63
trunk/skymusik/src/com/sky/widget/navigation/DrawerLayout.java
Java
oos
61,767
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ package com.sky.widget.navigation; import android.app.Activity; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.InsetDrawable; import android.os.Build; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.view.MenuItem; import android.view.View; /** * This class provides a handy way to tie together the functionality of * {@link DrawerLayout} and the framework <code>ActionBar</code> to implement the recommended * design for navigation drawers. * * <p>To use <code>ActionBarDrawerToggle</code>, create one in your Activity and call through * to the following methods corresponding to your Activity callbacks:</p> * * <ul> * <li>{@link Activity#onConfigurationChanged(android.content.res.Configuration) onConfigurationChanged}</li> * <li>{@link Activity#onOptionsItemSelected(android.view.MenuItem) onOptionsItemSelected}</li> * </ul> * * <p>Call {@link #syncState()} from your <code>Activity</code>'s * {@link Activity#onPostCreate(android.os.Bundle) onPostCreate} to synchronize the indicator * with the state of the linked DrawerLayout after <code>onRestoreInstanceState</code> * has occurred.</p> * * <p><code>ActionBarDrawerToggle</code> can be used directly as a * {@link DrawerLayout.DrawerListener}, or if you are already providing your own listener, * call through to each of the listener methods from your own.</p> */ public class ActionBarDrawerToggle implements DrawerLayout.DrawerListener { /** * Allows an implementing Activity to return an {@link ActionBarDrawerToggle.Delegate} to use * with ActionBarDrawerToggle. */ public interface DelegateProvider { /** * @return Delegate to use for ActionBarDrawableToggles, or null if the Activity * does not wish to override the default behavior. */ Delegate getDrawerToggleDelegate(); } public interface Delegate { /** * @return Up indicator drawable as defined in the Activity's theme, or null if one is not * defined. */ Drawable getThemeUpIndicator(); /** * Set the Action Bar's up indicator drawable and content description. * * @param upDrawable - Drawable to set as up indicator * @param contentDescRes - Content description to set */ void setActionBarUpIndicator(Drawable upDrawable, int contentDescRes); /** * Set the Action Bar's up indicator content description. * * @param contentDescRes - Content description to set */ void setActionBarDescription(int contentDescRes); } private interface ActionBarDrawerToggleImpl { Drawable getThemeUpIndicator(Activity activity); Object setActionBarUpIndicator(Object info, Activity activity, Drawable themeImage, int contentDescRes); Object setActionBarDescription(Object info, Activity activity, int contentDescRes); } private static class ActionBarDrawerToggleImplBase implements ActionBarDrawerToggleImpl { @Override public Drawable getThemeUpIndicator(Activity activity) { return null; } @Override public Object setActionBarUpIndicator(Object info, Activity activity, Drawable themeImage, int contentDescRes) { // No action bar to set. return info; } @Override public Object setActionBarDescription(Object info, Activity activity, int contentDescRes) { // No action bar to set return info; } } private static class ActionBarDrawerToggleImplHC implements ActionBarDrawerToggleImpl { @Override public Drawable getThemeUpIndicator(Activity activity) { return ActionBarDrawerToggleHoneycomb.getThemeUpIndicator(activity); } @Override public Object setActionBarUpIndicator(Object info, Activity activity, Drawable themeImage, int contentDescRes) { return ActionBarDrawerToggleHoneycomb.setActionBarUpIndicator(info, activity, themeImage, contentDescRes); } @Override public Object setActionBarDescription(Object info, Activity activity, int contentDescRes) { return ActionBarDrawerToggleHoneycomb.setActionBarDescription(info, activity, contentDescRes); } } private static final ActionBarDrawerToggleImpl IMPL; static { final int version = Build.VERSION.SDK_INT; if (version >= 11) { IMPL = new ActionBarDrawerToggleImplHC(); } else { IMPL = new ActionBarDrawerToggleImplBase(); } } /** Fraction of its total width by which to offset the toggle drawable. */ private static final float TOGGLE_DRAWABLE_OFFSET = 1 / 3f; // android.R.id.home as defined by public API in v11 private static final int ID_HOME = 0x0102002c; private final Activity mActivity; private final Delegate mActivityImpl; private final DrawerLayout mDrawerLayout; private boolean mDrawerIndicatorEnabled = true; private Drawable mThemeImage; private Drawable mDrawerImage; private SlideDrawable mSlider; private final int mDrawerImageResource; private final int mOpenDrawerContentDescRes; private final int mCloseDrawerContentDescRes; private Object mSetIndicatorInfo; /** * Construct a new ActionBarDrawerToggle. * * <p>The given {@link Activity} will be linked to the specified {@link DrawerLayout}. * The provided drawer indicator drawable will animate slightly off-screen as the drawer * is opened, indicating that in the open state the drawer will move off-screen when pressed * and in the closed state the drawer will move on-screen when pressed.</p> * * <p>String resources must be provided to describe the open/close drawer actions for * accessibility services.</p> * * @param activity The Activity hosting the drawer * @param drawerLayout The DrawerLayout to link to the given Activity's ActionBar * @param drawerImageRes A Drawable resource to use as the drawer indicator * @param openDrawerContentDescRes A String resource to describe the "open drawer" action * for accessibility * @param closeDrawerContentDescRes A String resource to describe the "close drawer" action * for accessibility */ public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int drawerImageRes, int openDrawerContentDescRes, int closeDrawerContentDescRes) { mActivity = activity; // Allow the Activity to provide an impl if (activity instanceof DelegateProvider) { mActivityImpl = ((DelegateProvider) activity).getDrawerToggleDelegate(); } else { mActivityImpl = null; } mDrawerLayout = drawerLayout; mDrawerImageResource = drawerImageRes; mOpenDrawerContentDescRes = openDrawerContentDescRes; mCloseDrawerContentDescRes = closeDrawerContentDescRes; mThemeImage = getThemeUpIndicator(); mDrawerImage = activity.getResources().getDrawable(drawerImageRes); mSlider = new SlideDrawable(mDrawerImage); mSlider.setOffset(TOGGLE_DRAWABLE_OFFSET); } /** * Synchronize the state of the drawer indicator/affordance with the linked DrawerLayout. * * <p>This should be called from your <code>Activity</code>'s * {@link Activity#onPostCreate(android.os.Bundle) onPostCreate} method to synchronize after * the DrawerLayout's instance state has been restored, and any other time when the state * may have diverged in such a way that the ActionBarDrawerToggle was not notified. * (For example, if you stop forwarding appropriate drawer events for a period of time.)</p> */ public void syncState() { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mSlider.setPosition(1); } else { mSlider.setPosition(0); } if (mDrawerIndicatorEnabled) { setActionBarUpIndicator(mSlider, mDrawerLayout.isDrawerOpen(GravityCompat.START) ? mCloseDrawerContentDescRes : mOpenDrawerContentDescRes); } } /** * Enable or disable the drawer indicator. The indicator defaults to enabled. * * <p>When the indicator is disabled, the <code>ActionBar</code> will revert to displaying * the home-as-up indicator provided by the <code>Activity</code>'s theme in the * <code>android.R.attr.homeAsUpIndicator</code> attribute instead of the animated * drawer glyph.</p> * * @param enable true to enable, false to disable */ public void setDrawerIndicatorEnabled(boolean enable) { if (enable != mDrawerIndicatorEnabled) { if (enable) { setActionBarUpIndicator(mSlider, mDrawerLayout.isDrawerOpen(GravityCompat.START) ? mCloseDrawerContentDescRes : mOpenDrawerContentDescRes); } else { setActionBarUpIndicator(mThemeImage, 0); } mDrawerIndicatorEnabled = enable; } } /** * @return true if the enhanced drawer indicator is enabled, false otherwise * @see #setDrawerIndicatorEnabled(boolean) */ public boolean isDrawerIndicatorEnabled() { return mDrawerIndicatorEnabled; } /** * This method should always be called by your <code>Activity</code>'s * {@link Activity#onConfigurationChanged(android.content.res.Configuration) onConfigurationChanged} * method. * * @param newConfig The new configuration */ public void onConfigurationChanged(Configuration newConfig) { // Reload drawables that can change with configuration mThemeImage = getThemeUpIndicator(); mDrawerImage = mActivity.getResources().getDrawable(mDrawerImageResource); syncState(); } /** * This method should be called by your <code>Activity</code>'s * {@link Activity#onOptionsItemSelected(android.view.MenuItem) onOptionsItemSelected} method. * If it returns true, your <code>onOptionsItemSelected</code> method should return true and * skip further processing. * * @param item the MenuItem instance representing the selected menu item * @return true if the event was handled and further processing should not occur */ public boolean onOptionsItemSelected(MenuItem item) { if (item != null && item.getItemId() == ID_HOME && mDrawerIndicatorEnabled) { if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { mDrawerLayout.openDrawer(GravityCompat.START); } return true; } return false; } /** * {@link DrawerLayout.DrawerListener} callback method. If you do not use your * ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call * through to this method from your own listener object. * * @param drawerView The child view that was moved * @param slideOffset The new offset of this drawer within its range, from 0-1 */ @Override public void onDrawerSlide(View drawerView, float slideOffset) { float glyphOffset = mSlider.getPosition(); if (slideOffset > 0.5f) { glyphOffset = Math.max(glyphOffset, Math.max(0.f, slideOffset - 0.5f) * 2); } else { glyphOffset = Math.min(glyphOffset, slideOffset * 2); } mSlider.setPosition(glyphOffset); } /** * {@link DrawerLayout.DrawerListener} callback method. If you do not use your * ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call * through to this method from your own listener object. * * @param drawerView Drawer view that is now open */ @Override public void onDrawerOpened(View drawerView) { mSlider.setPosition(1); if (mDrawerIndicatorEnabled) { setActionBarDescription(mCloseDrawerContentDescRes); } } /** * {@link DrawerLayout.DrawerListener} callback method. If you do not use your * ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call * through to this method from your own listener object. * * @param drawerView Drawer view that is now closed */ @Override public void onDrawerClosed(View drawerView) { mSlider.setPosition(0); if (mDrawerIndicatorEnabled) { setActionBarDescription(mOpenDrawerContentDescRes); } } /** * {@link DrawerLayout.DrawerListener} callback method. If you do not use your * ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call * through to this method from your own listener object. * * @param newState The new drawer motion state */ @Override public void onDrawerStateChanged(int newState) { } Drawable getThemeUpIndicator() { if (mActivityImpl != null) { return mActivityImpl.getThemeUpIndicator(); } return IMPL.getThemeUpIndicator(mActivity); } void setActionBarUpIndicator(Drawable upDrawable, int contentDescRes) { if (mActivityImpl != null) { mActivityImpl.setActionBarUpIndicator(upDrawable, contentDescRes); return; } mSetIndicatorInfo = IMPL .setActionBarUpIndicator(mSetIndicatorInfo, mActivity, upDrawable, contentDescRes); } void setActionBarDescription(int contentDescRes) { if (mActivityImpl != null) { mActivityImpl.setActionBarDescription(contentDescRes); return; } mSetIndicatorInfo = IMPL .setActionBarDescription(mSetIndicatorInfo, mActivity, contentDescRes); } private class SlideDrawable extends InsetDrawable implements Drawable.Callback { private final boolean mHasMirroring = Build.VERSION.SDK_INT > 18; private final Rect mTmpRect = new Rect(); private float mPosition; private float mOffset; private SlideDrawable(Drawable wrapped) { super(wrapped, 0); } /** * Sets the current position along the offset. * * @param position a value between 0 and 1 */ public void setPosition(float position) { mPosition = position; invalidateSelf(); } public float getPosition() { return mPosition; } /** * Specifies the maximum offset when the position is at 1. * * @param offset maximum offset as a fraction of the drawable width, * positive to shift left or negative to shift right. * @see #setPosition(float) */ public void setOffset(float offset) { mOffset = offset; invalidateSelf(); } @Override public void draw(Canvas canvas) { copyBounds(mTmpRect); canvas.save(); // Layout direction must be obtained from the activity. final boolean isLayoutRTL = ViewCompat.getLayoutDirection( mActivity.getWindow().getDecorView()) == ViewCompat.LAYOUT_DIRECTION_RTL; final int flipRtl = isLayoutRTL ? -1 : 1; final int width = mTmpRect.width(); canvas.translate(-mOffset * width * mPosition * flipRtl, 0); // Force auto-mirroring if it's not supported by the platform. if (isLayoutRTL && !mHasMirroring) { canvas.translate(width, 0); canvas.scale(-1, 1); } super.draw(canvas); canvas.restore(); } } }
0e8c07ac7597ee3feadc6087f2569f63
trunk/skymusik/src/com/sky/widget/navigation/ActionBarDrawerToggle.java
Java
oos
16,939
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.PercentageObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Read the throttle position in percentage. */ public class ThrottlePositionObdCommand extends PercentageObdCommand { /** * Default ctor. */ public ThrottlePositionObdCommand() { super("01 11"); } /** * Copy ctor. * * @param other */ public ThrottlePositionObdCommand(ThrottlePositionObdCommand other) { super(other); } /** * */ @Override public String getName() { return AvailableCommandNames.THROTTLE_POS.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/engine/ThrottlePositionObdCommand.java
Java
asf20
660
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.PercentageObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Calculated Engine Load value. */ public class EngineLoadObdCommand extends PercentageObdCommand { /** * @param command */ public EngineLoadObdCommand() { super("01 04"); } /** * @param other */ public EngineLoadObdCommand(ObdCommand other) { super(other); } /* (non-Javadoc) * @see eu.lighthouselabs.obd.commands.ObdCommand#getName() */ @Override public String getName() { return AvailableCommandNames.ENGINE_LOAD.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/engine/EngineLoadObdCommand.java
Java
asf20
712
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Displays the current engine revolutions per minute (RPM). */ public class EngineRPMObdCommand extends ObdCommand { private int _rpm = -1; /** * Default ctor. */ public EngineRPMObdCommand() { super("01 0C"); } /** * Copy ctor. * * @param other */ public EngineRPMObdCommand(EngineRPMObdCommand other) { super(other); } /** * @return the engine RPM per minute */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [41 0C] of the response int a = buffer.get(2); int b = buffer.get(3); _rpm = (a * 256 + b) / 4; } return String.format("%d%s", _rpm, " RPM"); } @Override public String getName() { return AvailableCommandNames.ENGINE_RPM.getValue(); } public int getRPM() { return _rpm; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/engine/EngineRPMObdCommand.java
Java
asf20
1,004
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description * * Mass Air Flow */ public class MassAirFlowObdCommand extends ObdCommand { private float _maf = -1.0f; /** * Default ctor. */ public MassAirFlowObdCommand() { super("01 10"); } /** * Copy ctor. * * @param other */ public MassAirFlowObdCommand(MassAirFlowObdCommand other) { super(other); } /** * */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [hh hh] of the response int a = buffer.get(2); int b = buffer.get(3); _maf = (a * 256 + b) / 100.0f; } return String.format("%.2f%s", _maf, "g/s"); } /** * @return MAF value for further calculus. */ public double getMAF() { return _maf; } @Override public String getName() { return AvailableCommandNames.MAF.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/engine/MassAirFlowObdCommand.java
Java
asf20
1,021
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description */ public class EngineRuntimeObdCommand extends ObdCommand { /** * Default ctor. */ public EngineRuntimeObdCommand() { super("01 1F"); } /** * Copy ctor. * * @param other */ public EngineRuntimeObdCommand(EngineRuntimeObdCommand other) { super(other); } @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [01 0C] of the response int a = buffer.get(2); int b = buffer.get(3); int value = a * 256 + b; // determine time String hh = String.format("%02d", value / 3600); String mm = String.format("%02d", (value % 3600) / 60); String ss = String.format("%02d", value % 60); res = String.format("%s:%s:%s", hh, mm, ss); } return res; } @Override public String getName() { return AvailableCommandNames.ENGINE_RUNTIME.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/engine/EngineRuntimeObdCommand.java
Java
asf20
1,091
/* * TODO put header */ package eu.lighthouselabs.obd.commands.control; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Fuel systems that use conventional oxygen sensor display the commanded open * loop equivalence ratio while the system is in open loop. Should report 100% * when in closed loop fuel. * * To obtain the actual air/fuel ratio being commanded, multiply the * stoichiometric A/F ratio by the equivalence ratio. For example, gasoline, * stoichiometric is 14.64:1 ratio. If the fuel control system was commanded an * equivalence ratio of 0.95, the commanded A/F ratio to the engine would be * 14.64 * 0.95 = 13.9 A/F. */ public class CommandEquivRatioObdCommand extends ObdCommand { /* * Equivalent ratio (%) */ private double ratio = 0.00; /** * Default ctor. */ public CommandEquivRatioObdCommand() { super("01 44"); } /** * Copy ctor. * * @param other */ public CommandEquivRatioObdCommand(CommandEquivRatioObdCommand other) { super(other); } /** * */ @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response int a = buffer.get(2); int b = buffer.get(3); ratio = (a * 256 + b) / 32768; res = String.format("%.1f%s", ratio, "%"); } return res; } /** * @return */ public double getRatio() { return ratio; } @Override public String getName() { return AvailableCommandNames.EQUIV_RATIO.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/control/CommandEquivRatioObdCommand.java
Java
asf20
1,571
/* * TODO put header */ package eu.lighthouselabs.obd.commands.control; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * In order to get ECU Trouble Codes, one must first send a DtcNumberObdCommand * and by so, determining the number of error codes available by means of * getTotalAvailableCodes(). * * If none are available (totalCodes < 1), don't instantiate this command. */ public class TroubleCodesObdCommand extends ObdCommand { protected final static char[] dtcLetters = { 'P', 'C', 'B', 'U' }; private StringBuffer codes = null; private int howManyTroubleCodes = 0; /** * Default ctor. */ public TroubleCodesObdCommand(int howManyTroubleCodes) { super("03"); codes = new StringBuffer(); this.howManyTroubleCodes = howManyTroubleCodes; } /** * Copy ctor. * * @param other */ public TroubleCodesObdCommand(TroubleCodesObdCommand other) { super(other); codes = new StringBuffer(); } // TODO clean // int count = numCmd.getCodeCount(); // int dtcNum = (count + 2) / 3; // for (int i = 0; i < dtcNum; i++) { // sendCommand(cmd); // String res = getResult(); // for (int j = 0; j < 3; j++) { // String byte1 = res.substring(3 + j * 6, 5 + j * 6); // String byte2 = res.substring(6 + j * 6, 8 + j * 6); // int b1 = Integer.parseInt(byte1, 16); // int b2 = Integer.parseInt(byte2, 16); // int val = (b1 << 8) + b2; // if (val == 0) { // break; // } // String code = "P"; // if ((val & 0xC000) > 14) { // code = "C"; // } // code += Integer.toString((val & 0x3000) >> 12); // code += Integer.toString((val & 0x0fff)); // codes.append(code); // codes.append("\n"); // } /** * @return the formatted result of this command in string representation. */ public String formatResult() { String res = getResult(); if (!"NODATA".equals(res)) { /* * Ignore first byte [43] of the response and then read each two * bytes. */ int begin = 2; // start at 2nd byte int end = 6; // end at 4th byte for (int i = 0; i < howManyTroubleCodes * 2; i++) { // read and jump 2 bytes byte b1 = Byte.parseByte(res.substring(begin, end)); begin += 2; end += 2; // read and jump 2 bytes byte b2 = Byte.parseByte(res.substring(begin, end)); begin += 2; end += 2; int tempValue = b1 << 8 | b2; } } String[] ress = res.split("\r"); for (String r : ress) { String k = r.replace("\r", ""); codes.append(k); codes.append("\n"); } return codes.toString(); } @Override public String getFormattedResult() { // TODO Auto-generated method stub return null; } @Override public String getName() { return AvailableCommandNames.TROUBLE_CODES.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/control/TroubleCodesObdCommand.java
Java
asf20
2,765
/* * TODO put header */ package eu.lighthouselabs.obd.commands.control; import eu.lighthouselabs.obd.commands.PercentageObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description * * Timing Advance */ public class TimingAdvanceObdCommand extends PercentageObdCommand { public TimingAdvanceObdCommand() { super("01 0E"); } public TimingAdvanceObdCommand(TimingAdvanceObdCommand other) { super(other); } @Override public String getName() { return AvailableCommandNames.TIMING_ADVANCE.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/control/TimingAdvanceObdCommand.java
Java
asf20
560
/* * TODO put header */ package eu.lighthouselabs.obd.commands.control; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * This command will for now read MIL (check engine light) state and number of * diagnostic trouble codes currently flagged in the ECU. * * Perhaps in the future we'll extend this to read the 3rd, 4th and 5th bytes of * the response in order to store information about the availability and * completeness of certain on-board tests. */ public class DtcNumberObdCommand extends ObdCommand { private int codeCount = 0; private boolean milOn = false; /** * Default ctor. */ public DtcNumberObdCommand() { super("01 01"); } /** * Copy ctor. * * @param other */ public DtcNumberObdCommand(DtcNumberObdCommand other) { super(other); } /** * */ public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response int mil = buffer.get(2); if ((mil & 0x80) == 128) milOn = true; codeCount = mil & 0x7F; } res = milOn ? "MIL is ON" : "MIL is OFF"; return new StringBuilder().append(res).append(codeCount) .append(" codes").toString(); } /** * @return the number of trouble codes currently flaggd in the ECU. */ public int getTotalAvailableCodes() { return codeCount; } /** * * @return the state of the check engine light state. */ public boolean getMilOn() { return milOn; } @Override public String getName() { return AvailableCommandNames.DTC_NUMBER.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/control/DtcNumberObdCommand.java
Java
asf20
1,625
/* * TODO put header */ package eu.lighthouselabs.obd.commands.protocol; import eu.lighthouselabs.obd.commands.ObdCommand; /** * This command will turn-off echo. */ public class EchoOffObdCommand extends ObdCommand { /** * @param command */ public EchoOffObdCommand() { super("AT E0"); } /** * @param other */ public EchoOffObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Echo Off"; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/protocol/EchoOffObdCommand.java
Java
asf20
641
/* * TODO put header */ package eu.lighthouselabs.obd.commands.protocol; import java.io.IOException; import java.io.InputStream; import eu.lighthouselabs.obd.commands.ObdCommand; /** * This method will reset the OBD connection. */ public class ObdResetCommand extends ObdCommand { /** * @param command */ public ObdResetCommand() { super("AT Z"); } /** * @param other */ public ObdResetCommand(ObdResetCommand other) { super(other); } /** * Reset command returns an empty string, so we must override the following * two methods. * @throws IOException */ @Override public void readResult(InputStream in) throws IOException { // do nothing return; } @Override public String getResult() { return ""; } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Reset OBD"; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/protocol/ObdResetCommand.java
Java
asf20
996
/* * TODO put description */ package eu.lighthouselabs.obd.commands.protocol; import eu.lighthouselabs.obd.commands.ObdCommand; /** * This will set the value of time in milliseconds (ms) that the OBD interface * will wait for a response from the ECU. If exceeds, the response is "NO DATA". */ public class TimeoutObdCommand extends ObdCommand { /** * @param a * value between 0 and 255 that multiplied by 4 results in the * desired timeout in milliseconds (ms). */ public TimeoutObdCommand(int timeout) { super("AT ST " + Integer.toHexString(0xFF & timeout)); } /** * @param other */ public TimeoutObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Timeout"; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/protocol/TimeoutObdCommand.java
Java
asf20
941
/* * TODO put header */ package eu.lighthouselabs.obd.commands.protocol; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.ObdProtocols; /** * Select the protocol to use. */ public class SelectProtocolObdCommand extends ObdCommand { private final ObdProtocols _protocol; /** * @param command */ public SelectProtocolObdCommand(ObdProtocols protocol) { super("AT SP " + protocol.getValue()); _protocol = protocol; } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Select Protocol " + _protocol.name(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/protocol/SelectProtocolObdCommand.java
Java
asf20
742
/* * TODO put header */ package eu.lighthouselabs.obd.commands.protocol; import eu.lighthouselabs.obd.commands.ObdCommand; /** * Turns off line-feed. */ public class LineFeedOffObdCommand extends ObdCommand { /** * @param command */ public LineFeedOffObdCommand() { super("AT L0"); } /** * @param other */ public LineFeedOffObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Line Feed Off"; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/protocol/LineFeedOffObdCommand.java
Java
asf20
646
/* * TODO put header */ package eu.lighthouselabs.obd.commands.temperature; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Engine Coolant Temperature. */ public class EngineCoolantTemperatureObdCommand extends TemperatureObdCommand { /** * */ public EngineCoolantTemperatureObdCommand() { super("01 05"); } /** * @param other */ public EngineCoolantTemperatureObdCommand(TemperatureObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getName() */ @Override public String getName() { return AvailableCommandNames.ENGINE_COOLANT_TEMP.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/temperature/EngineCoolantTemperatureObdCommand.java
Java
asf20
662
/* * TODO put header */ package eu.lighthouselabs.obd.commands.temperature; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO * * put description */ public class AirIntakeTemperatureObdCommand extends TemperatureObdCommand { public AirIntakeTemperatureObdCommand() { super("01 0F"); } public AirIntakeTemperatureObdCommand(AirIntakeTemperatureObdCommand other) { super(other); } @Override public String getName() { return AvailableCommandNames.AIR_INTAKE_TEMP.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/temperature/AirIntakeTemperatureObdCommand.java
Java
asf20
521
/* * TODO put header */ package eu.lighthouselabs.obd.commands.temperature; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SystemOfUnits; /** * TODO * * put description */ public abstract class TemperatureObdCommand extends ObdCommand implements SystemOfUnits { private float temperature = 0.0f; /** * Default ctor. * * @param cmd */ public TemperatureObdCommand(String cmd) { super(cmd); } /** * Copy ctor. * * @param other */ public TemperatureObdCommand(TemperatureObdCommand other) { super(other); } /** * TODO * * put description of why we subtract 40 * * @param temp * @return */ protected final float prepareTempValue(float temp) { return temp - 40; } /** * Get values from 'buff', since we can't rely on char/string for calculations. * * @return Temperature in Celsius or Fahrenheit. */ @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response temperature = prepareTempValue(buffer.get(2)); // convert? if (useImperialUnits) res = String.format("%.1f%s", getImperialUnit(), "F"); else res = String.format("%.0f%s", temperature, "C"); } return res; } /** * @return the temperature in Celsius. */ public float getTemperature() { return temperature; } /** * @return the temperature in Fahrenheit. */ public float getImperialUnit() { return temperature * 1.8f + 32; } /** * @return the temperature in Kelvin. */ public float getKelvin() { return temperature + 273.15f; } /** * @return the OBD command name. */ public abstract String getName(); }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/temperature/TemperatureObdCommand.java
Java
asf20
1,742
/* * TODO put header */ package eu.lighthouselabs.obd.commands.temperature; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Ambient Air Temperature. */ public class AmbientAirTemperatureObdCommand extends TemperatureObdCommand { /** * @param cmd */ public AmbientAirTemperatureObdCommand() { super("01 46"); } /** * @param other */ public AmbientAirTemperatureObdCommand(TemperatureObdCommand other) { super(other); } @Override public String getName() { return AvailableCommandNames.AMBIENT_AIR_TEMP.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/temperature/AmbientAirTemperatureObdCommand.java
Java
asf20
571
/* * TODO put header */ package eu.lighthouselabs.obd.commands.utils; /** * Misc utilities */ public final class ObdUtils { /** * @param an integer value * @return the equivalent FuelType name. */ public final static String getFuelTypeName(int value) { String name = null; switch (value) { case 1: name = "Gasoline"; break; case 2: name = "Methanol"; break; case 3: name = "Ethanol"; break; case 4: name = "Diesel"; break; case 5: name = "GPL/LGP"; break; case 6: name = "Natural Gas (CNG)"; break; case 7: name = "Propane"; break; case 8: name = "Electric"; break; case 9: name = "Biodiesel + Gasoline"; break; case 10: name = "Biodiesel + Methanol"; break; case 11: name = "Biodiesel + Ethanol"; break; case 12: name = "Biodiesel + GPL/LPG"; break; case 13: name = "Biodiesel + Natural Gas"; break; case 14: name = "Biodiesel + Propane"; break; case 15: name = "Biodiesel + Electric"; break; case 16: name = "Biodiesel + Gasoline/Electric"; break; case 17: name = "Hybrid Gasoline"; break; case 18: name = "Hybrid Ethanol"; break; case 19: name = "Hybrid Diesel"; break; case 20: name = "Hybrid Electric"; break; case 21: name = "Hybrid Mixed"; break; case 22: name = "Hybrid Regenerative"; break; default: name = "NODATA"; } return name; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/utils/ObdUtils.java
Java
asf20
1,452
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Get fuel level in percentage */ public class FuelLevelObdCommand extends ObdCommand { private float fuelLevel = 0f; /** * @param command */ public FuelLevelObdCommand() { super("01 2F"); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [hh hh] of the response fuelLevel = 100.0f * buffer.get(2) / 255.0f; } return String.format("%.1f%s", fuelLevel, "%"); } @Override public String getName() { return AvailableCommandNames.FUEL_LEVEL.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/fuel/FuelLevelObdCommand.java
Java
asf20
841
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SpeedObdCommand; import eu.lighthouselabs.obd.commands.control.CommandEquivRatioObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineRPMObdCommand; import eu.lighthouselabs.obd.commands.pressure.IntakeManifoldPressureObdCommand; import eu.lighthouselabs.obd.commands.temperature.AirIntakeTemperatureObdCommand; /** * TODO put description */ public class FuelEconomyWithoutMAFObdCommand extends ObdCommand { public static final double AIR_FUEL_RATIO = 14.64; public static final double FUEL_DENSITY_GRAMS_PER_LITER = 720.0; public FuelEconomyWithoutMAFObdCommand() { super(""); } /** * As it's a fake command, neither do we need to send request or read * response. */ @Override public void run(InputStream in, OutputStream out) throws IOException, InterruptedException { // prepare variables EngineRPMObdCommand rpmCmd = new EngineRPMObdCommand(); rpmCmd.run(in, out); rpmCmd.getFormattedResult(); AirIntakeTemperatureObdCommand airTempCmd = new AirIntakeTemperatureObdCommand(); airTempCmd.run(in, out); airTempCmd.getFormattedResult(); SpeedObdCommand speedCmd = new SpeedObdCommand(); speedCmd.run(in, out); speedCmd.getFormattedResult(); CommandEquivRatioObdCommand equivCmd = new CommandEquivRatioObdCommand(); equivCmd.run(in, out); equivCmd.getFormattedResult(); IntakeManifoldPressureObdCommand pressCmd = new IntakeManifoldPressureObdCommand(); pressCmd.run(in, out); pressCmd.getFormattedResult(); double imap = rpmCmd.getRPM() * pressCmd.getMetricUnit() / airTempCmd.getKelvin(); // double maf = (imap / 120) * (speedCmd.getMetricSpeed()/100)*() } @Override public String getFormattedResult() { // TODO Auto-generated method stub return null; } @Override public String getName() { // TODO Auto-generated method stub return null; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/fuel/FuelEconomyWithoutMAFObdCommand.java
Java
asf20
2,219
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.enums.AvailableCommandNames; import eu.lighthouselabs.obd.enums.FuelType; /** * TODO put description */ public class FuelEconomyWithMAFObdCommand { private int speed = 1; private double maf = 1; private float ltft = 1; private double ratio = 1; private FuelType fuelType; private boolean useImperial = false; double mpg = -1; double litersPer100Km = -1; /** * @param command */ public FuelEconomyWithMAFObdCommand(FuelType fuelType, int speed, double maf, float ltft, boolean useImperial) { this.fuelType = fuelType; this.speed = speed; this.maf = maf; this.ltft = ltft; this.useImperial = useImperial; mpg = (14.7 * 6.17 * 454 * speed * 0.621371) / (3600 * maf); // mpg = 710.7 * speed / maf * (1 + ltft / 100); // mpg = (14.7 * ratio * 6.17 * 454.0 * speed * 0.621371) / (3600.0 * maf); // mpg = (14.7 * (1 + ltft / 100) * 6.17 * 454.0 * speed * 0.621371) / (3600.0 * maf); // litersPer100Km = mpg / 2.2352; litersPer100Km = 235.2 / mpg; // float fuelDensity = 0.71f; // if (fuelType.equals(FuelType.DIESEL)) // fuelDensity = 0.832f; // litersPer100Km = (maf / 14.7 / fuelDensity * 3600) * (1 + ltft / 100) // / speed; } /** * As it's a fake command, neither do we need to send request or read * response. */ public double getMPG() { return mpg; } /** * @return the fuel consumption in l/100km */ public double getLitersPer100Km() { return litersPer100Km; } public String getFormattedResult() { String res = "NODATA"; res = String.format("%.2f%s", litersPer100Km, "l/100km"); if (useImperial) res = String.format("%.1f%s", mpg, "mpg"); return res; } public String getName() { return AvailableCommandNames.FUEL_ECONOMY_WITH_MAF.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/fuel/FuelEconomyWithMAFObdCommand.java
Java
asf20
1,847
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SpeedObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description */ public class FuelEconomyObdCommand extends ObdCommand { protected float kml = -1.0f; private float speed = -1.0f; /** * Default ctor. */ public FuelEconomyObdCommand() { super(""); } /** * As it's a fake command, neither do we need to send request or read * response. */ @Override public void run(InputStream in, OutputStream out) throws IOException, InterruptedException { // get consumption liters per hour FuelConsumptionObdCommand fuelConsumptionCommand = new FuelConsumptionObdCommand(); fuelConsumptionCommand.run(in, out); fuelConsumptionCommand.getFormattedResult(); float fuelConsumption = fuelConsumptionCommand.getLitersPerHour(); // get metric speed SpeedObdCommand speedCommand = new SpeedObdCommand(); speedCommand.run(in, out); speedCommand.getFormattedResult(); speed = speedCommand.getMetricSpeed(); // get l/100km kml = (100 / speed) * fuelConsumption; } /** * * @return */ @Override public String getFormattedResult() { if (useImperialUnits) { // convert to mpg return String.format("%.1f %s", getMilesPerUKGallon(), "mpg"); } return String.format("%.1f %s", kml, "l/100km"); } public float getLitersPer100Km() { return kml; } public float getMilesPerUSGallon() { return 235.2f / kml; } public float getMilesPerUKGallon() { return 282.5f / kml; } @Override public String getName() { return AvailableCommandNames.FUEL_ECONOMY.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/fuel/FuelEconomyObdCommand.java
Java
asf20
1,815
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.FuelTrim; /** * Get Fuel Trim. * */ public class FuelTrimObdCommand extends ObdCommand { private float fuelTrimValue = 0.0f; private final FuelTrim bank; /** * Default ctor. * * Will read the bank from parameters and construct the command accordingly. * Please, see FuelTrim enum for more details. */ public FuelTrimObdCommand(FuelTrim bank) { super(bank.getObdCommand()); this.bank = bank; } /** * @param value * @return */ private float prepareTempValue(int value) { Double perc = (value - 128) * (100.0 / 128); return Float.parseFloat(perc.toString()); } @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [hh hh] of the response fuelTrimValue = prepareTempValue(buffer.get(2)); } return String.format("%.2f%s", fuelTrimValue, "%"); } /** * @return the readed Fuel Trim percentage value. */ public final float getValue() { return fuelTrimValue; } /** * @return the name of the bank in string representation. */ public final String getBank() { return bank.getBank(); } @Override public String getName() { return bank.getBank(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/fuel/FuelTrimObdCommand.java
Java
asf20
1,334
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description */ public class FuelConsumptionObdCommand extends ObdCommand { private float fuelRate = -1.0f; public FuelConsumptionObdCommand() { super("01 5E"); } public FuelConsumptionObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [hh hh] of the response int a = buffer.get(2); int b = buffer.get(3); fuelRate = (a * 256 + b) * 0.05f; } String res = String.format("%.1f%s", fuelRate, ""); return res; } public float getLitersPerHour() { return fuelRate; } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getName() */ @Override public String getName() { return AvailableCommandNames.FUEL_CONSUMPTION.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/fuel/FuelConsumptionObdCommand.java
Java
asf20
1,110
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.utils.ObdUtils; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * This command is intended to determine the vehicle fuel type. */ public class FindFuelTypeObdCommand extends ObdCommand { private int fuelType = 0; /** * Default ctor. */ public FindFuelTypeObdCommand() { super("10 51"); } /** * Copy ctor * * @param other */ public FindFuelTypeObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.command.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response fuelType = buffer.get(2); res = getFuelTypeName(); } return res; } /** * @return Fuel type name. */ public final String getFuelTypeName() { return ObdUtils.getFuelTypeName(fuelType); } @Override public String getName() { return AvailableCommandNames.FUEL_TYPE.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/fuel/FindFuelTypeObdCommand.java
Java
asf20
1,166
package eu.lighthouselabs.obd.commands.pressure; import eu.lighthouselabs.obd.enums.AvailableCommandNames; public class FuelPressureObdCommand extends PressureObdCommand { public FuelPressureObdCommand() { super("010A"); } public FuelPressureObdCommand(FuelPressureObdCommand other) { super(other); } /** * TODO * * put description of why we multiply by 3 * * @param temp * @return */ @Override protected final int preparePressureValue() { return tempValue * 3; } @Override public String getName() { return AvailableCommandNames.FUEL_PRESSURE.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/pressure/FuelPressureObdCommand.java
Java
asf20
602
/* * TODO put header */ package eu.lighthouselabs.obd.commands.pressure; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Intake Manifold Pressure */ public class IntakeManifoldPressureObdCommand extends PressureObdCommand { /** * Default ctor. */ public IntakeManifoldPressureObdCommand() { super("01 0B"); } /** * Copy ctor. * * @param other */ public IntakeManifoldPressureObdCommand( IntakeManifoldPressureObdCommand other) { super(other); } @Override public String getName() { return AvailableCommandNames.INTAKE_MANIFOLD_PRESSURE.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/pressure/IntakeManifoldPressureObdCommand.java
Java
asf20
609
/* * TODO put header */ package eu.lighthouselabs.obd.commands.pressure; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SystemOfUnits; /** * TODO put description */ public abstract class PressureObdCommand extends ObdCommand implements SystemOfUnits { protected int tempValue = 0; protected int pressure = 0; /** * Default ctor * * @param cmd */ public PressureObdCommand(String cmd) { super(cmd); } /** * Copy ctor. * * @param cmd */ public PressureObdCommand(PressureObdCommand other) { super(other); } /** * Some PressureObdCommand subclasses will need to implement this method in * order to determine the final kPa value. * * *NEED* to read tempValue * * @return */ protected int preparePressureValue() { return tempValue; } /** * */ @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response tempValue = buffer.get(2); pressure = preparePressureValue(); // this will need tempValue res = String.format("%d%s", pressure, "kPa"); if (useImperialUnits) { res = String.format("%.1f%s", getImperialUnit(), "psi"); } } return res; } /** * @return the pressure in kPa */ public int getMetricUnit() { return pressure; } /** * @return the pressure in psi */ public float getImperialUnit() { Double d = pressure * 0.145037738; return Float.valueOf(d.toString()); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/pressure/PressureObdCommand.java
Java
asf20
1,525
/* * TODO put header */ package eu.lighthouselabs.obd.commands; /** * This interface will define methods for converting to/from imperial units and * from/to metric units. */ public interface SystemOfUnits { float getImperialUnit(); }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/SystemOfUnits.java
Java
asf20
243
/* * TODO put header */ package eu.lighthouselabs.obd.commands; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; /** * TODO put description */ public abstract class ObdCommand { protected ArrayList<Integer> buffer = null; protected String cmd = null; protected boolean useImperialUnits = false; protected String rawData = null; /** * Default ctor to use * * @param command * the command to send */ public ObdCommand(String command) { this.cmd = command; this.buffer = new ArrayList<Integer>(); } /** * Prevent empty instantiation */ private ObdCommand() { } /** * Copy ctor. * * @param other * the ObdCommand to copy. */ public ObdCommand(ObdCommand other) { this(other.cmd); } /** * Sends the OBD-II request and deals with the response. * * This method CAN be overriden in fake commands. */ public void run(InputStream in, OutputStream out) throws IOException, InterruptedException { sendCommand(out); readResult(in); } /** * Sends the OBD-II request. * * This method may be overriden in subclasses, such as ObMultiCommand or * TroubleCodesObdCommand. * * @param cmd * The command to send. */ protected void sendCommand(OutputStream out) throws IOException, InterruptedException { // add the carriage return char cmd += "\r"; // write to OutputStream, or in this case a BluetoothSocket out.write(cmd.getBytes()); out.flush(); /* * HACK GOLDEN HAMMER ahead!! * * TODO clean * * Due to the time that some systems may take to respond, let's give it * 500ms. */ Thread.sleep(200); } /** * Resends this command. * * */ protected void resendCommand(OutputStream out) throws IOException, InterruptedException { out.write("\r".getBytes()); out.flush(); /* * HACK GOLDEN HAMMER ahead!! * * TODO clean this * * Due to the time that some systems may take to respond, let's give it * 500ms. */ // Thread.sleep(250); } /** * Reads the OBD-II response. * * This method may be overriden in subclasses, such as ObdMultiCommand. */ protected void readResult(InputStream in) throws IOException { byte b = 0; StringBuilder res = new StringBuilder(); // read until '>' arrives while ((char) (b = (byte) in.read()) != '>') if ((char) b != ' ') res.append((char) b); /* * Imagine the following response 41 0c 00 0d. * * ELM sends strings!! So, ELM puts spaces between each "byte". And pay * attention to the fact that I've put the word byte in quotes, because * 41 is actually TWO bytes (two chars) in the socket. So, we must do * some more processing.. */ // rawData = res.toString().trim(); // clear buffer buffer.clear(); // read string each two chars int begin = 0; int end = 2; while (end <= rawData.length()) { String temp = "0x" + rawData.substring(begin, end); buffer.add(Integer.decode(temp)); begin = end; end += 2; } } /** * @return the raw command response in string representation. */ public String getResult() { if (rawData.contains("SEARCHING") || rawData.contains("DATA")) { rawData = "NODATA"; } return rawData; } /** * @return a formatted command response in string representation. */ public abstract String getFormattedResult(); /****************************************************************** * Getters & Setters */ /** * @return a list of integers */ public ArrayList<Integer> getBuffer() { return buffer; } /** * Returns this command in string representation. * * @return the command */ public String getCommand() { return cmd; } /** * @return true if imperial units are used, or false otherwise */ public boolean useImperialUnits() { return useImperialUnits; } /** * Set to 'true' if you want to use imperial units, false otherwise. By * default this value is set to 'false'. * * @param isImperial */ public void useImperialUnits(boolean isImperial) { this.useImperialUnits = isImperial; } /** * @return the OBD command name. */ public abstract String getName(); }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/ObdCommand.java
Java
asf20
4,231
/* * TODO put header */ package eu.lighthouselabs.obd.commands; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; /** * TODO put description */ public class ObdMultiCommand { private ArrayList<ObdCommand> commands; /** * Default ctor. */ public ObdMultiCommand() { this.commands = new ArrayList<ObdCommand>(); } /** * Add ObdCommand to list of ObdCommands. * * @param command */ public void add(ObdCommand command) { this.commands.add(command); } /** * Removes ObdCommand from the list of ObdCommands. * @param command */ public void remove(ObdCommand command) { this.commands.remove(command); } /** * Iterate all commands and call: * - sendCommand() * - readResult() */ public void sendCommands(InputStream in, OutputStream out) throws IOException, InterruptedException { for (ObdCommand command : commands) { /* * Send command and read response. */ command.run(in, out); } } /** * * @return */ public String getFormattedResult() { StringBuilder res = new StringBuilder(); for (ObdCommand command : commands) { res.append(command.getFormattedResult()).append(","); } return res.toString(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/ObdMultiCommand.java
Java
asf20
1,270
/* * TODO put header */ package eu.lighthouselabs.obd.commands; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description * * Current speed. */ public class SpeedObdCommand extends ObdCommand implements SystemOfUnits { private int metricSpeed = 0; /** * Default ctor. */ public SpeedObdCommand() { super("01 0D"); } /** * Copy ctor. * * @param other */ public SpeedObdCommand(SpeedObdCommand other) { super(other); } /** * */ public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { //Ignore first two bytes [hh hh] of the response. metricSpeed = buffer.get(2); res = String.format("%d%s", metricSpeed, "km/h"); if (useImperialUnits) res = String.format("%.2f%s", getImperialUnit(), "mph"); } return res; } /** * @return the speed in metric units. */ public int getMetricSpeed() { return metricSpeed; } /** * @return the speed in imperial units. */ public float getImperialSpeed() { return getImperialUnit(); } /** * Convert from km/h to mph */ public float getImperialUnit() { Double tempValue = metricSpeed * 0.621371192; return Float.valueOf(tempValue.toString()); } @Override public String getName() { return AvailableCommandNames.SPEED.getValue(); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/commands/SpeedObdCommand.java
Java
asf20
1,344
/* * TODO put header */ package eu.lighthouselabs.obd.enums; /** * TODO put description */ public enum AvailableCommandNames { AIR_INTAKE_TEMP("Air Intake Temperature"), AMBIENT_AIR_TEMP("Ambient Air Temperature"), ENGINE_COOLANT_TEMP("Engine Coolant Temperature"), BAROMETRIC_PRESSURE("Barometric Pressure"), FUEL_PRESSURE("Fuel Pressure"), INTAKE_MANIFOLD_PRESSURE("Intake Manifold Pressure"), ENGINE_LOAD("Engine Load"), ENGINE_RUNTIME("Engine Runtime"), ENGINE_RPM("Engine RPM"), SPEED("Vehicle Speed"), MAF("Mass Air Flow"), THROTTLE_POS("Throttle Position"), TROUBLE_CODES("Trouble Codes"), FUEL_LEVEL("Fuel Level"), FUEL_TYPE("Fuel Type"), FUEL_CONSUMPTION("Fuel Consumption"), FUEL_ECONOMY("Fuel Economy"), FUEL_ECONOMY_WITH_MAF("Fuel Economy 2"), FUEL_ECONOMY_WITHOUT_MAF("Fuel Economy 3"), TIMING_ADVANCE("Timing Advance"), DTC_NUMBER("Diagnostic Trouble Codes"), EQUIV_RATIO("Command Equivalence Ratio"); private final String value; /** * * @param value */ private AvailableCommandNames(String value) { this.value = value; } /** * * @return */ public final String getValue() { return value; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/enums/AvailableCommandNames.java
Java
asf20
1,165
/* * TODO put header */ package eu.lighthouselabs.obd.enums; /** * All OBD protocols. */ public enum ObdProtocols { /** * Auto select protocol and save. */ AUTO('0'), /** * 41.6 kbaud */ SAE_J1850_PWM('1'), /** * 10.4 kbaud */ SAE_J1850_VPW('2'), /** * 5 baud init */ ISO_9141_2('3'), /** * 5 baud init */ ISO_14230_4_KWP('4'), /** * Fast init */ ISO_14230_4_KWP_FAST('5'), /** * 11 bit ID, 500 kbaud */ ISO_15765_4_CAN('6'), /** * 29 bit ID, 500 kbaud */ ISO_15765_4_CAN_B('7'), /** * 11 bit ID, 250 kbaud */ ISO_15765_4_CAN_C('8'), /** * 29 bit ID, 250 kbaud */ ISO_15765_4_CAN_D('9'), /** * 29 bit ID, 250 kbaud (user adjustable) */ SAE_J1939_CAN('A'), /** * 11 bit ID (user adjustable), 125 kbaud (user adjustable) */ USER1_CAN('B'), /** * 11 bit ID (user adjustable), 50 kbaud (user adjustable) */ USER2_CAN('C'); private final char value; ObdProtocols(char value) { this.value = value; } public char getValue() { return value; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/enums/ObdProtocols.java
Java
asf20
1,044
/* * TODO put header */ package eu.lighthouselabs.obd.enums; /** * Select one of the Fuel Trim percentage banks to access. */ public enum FuelTrim { SHORT_TERM_BANK_1(0x06), LONG_TERM_BANK_1(0x07), SHORT_TERM_BANK_2(0x08), LONG_TERM_BANK_2(0x09); private final int value; /** * * @param value */ private FuelTrim(int value) { this.value = value; } /** * * @return */ public final int getValue() { return value; } /** * * @return */ public final String getObdCommand() { return new String("01 " + value); } public final String getBank() { String res = "NODATA"; switch (value) { case 0x06: res = "Short Term Fuel Trim Bank 1"; break; case 0x07: res = "Long Term Fuel Trim Bank 1"; break; case 0x08: res = "Short Term Fuel Trim Bank 2"; break; case 0x09: res = "Long Term Fuel Trim Bank 2"; break; default: break; } return res; } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/enums/FuelTrim.java
Java
asf20
937
/* * TODO put header */ package eu.lighthouselabs.obd.enums; import eu.lighthouselabs.obd.commands.utils.ObdUtils; /** * MODE 1 PID 0x51 will return one of the following values to identify the fuel * type of the vehicle. */ public enum FuelType { GASOLINE(0x01), METHANOL(0x02), ETHANOL(0x03), DIESEL(0x04), LPG(0x05), CNG(0x06), PROPANE(0x07), ELECTRIC(0x08), BIFUEL_GASOLINE(0x09), BIFUEL_METHANOL(0x0A), BIFUEL_ETHANOL(0x0B), BIFUEL_LPG(0x0C), BIFUEL_CNG(0x0D), BIFUEL_PROPANE(0x0E), BIFUEL_ELECTRIC(0x0F), BIFUEL_GASOLINE_ELECTRIC(0x10), HYBRID_GASOLINE(0x11), HYBRID_ETHANOL(0x12), HYBRID_DIESEL(0x13), HYBRID_ELECTRIC(0x14), HYBRID_MIXED(0x15), HYBRID_REGENERATIVE(0x16); private final int value; /** * * @param value */ private FuelType(int value) { this.value = value; } /** * * @return */ public final int getValue() { return value; } /** * * @return */ public final String getName() { return ObdUtils.getFuelTypeName(value); } }
09055199d-
obd-api/src/main/java/eu/lighthouselabs/obd/enums/FuelType.java
Java
asf20
1,010
/* * TODO put header */ package eu.lighthouselabs.obd.reader.config; import java.util.ArrayList; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SpeedObdCommand; import eu.lighthouselabs.obd.commands.control.CommandEquivRatioObdCommand; import eu.lighthouselabs.obd.commands.control.DtcNumberObdCommand; import eu.lighthouselabs.obd.commands.control.TimingAdvanceObdCommand; import eu.lighthouselabs.obd.commands.control.TroubleCodesObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineLoadObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineRPMObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineRuntimeObdCommand; import eu.lighthouselabs.obd.commands.engine.MassAirFlowObdCommand; import eu.lighthouselabs.obd.commands.engine.ThrottlePositionObdCommand; import eu.lighthouselabs.obd.commands.fuel.FindFuelTypeObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelLevelObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelTrimObdCommand; import eu.lighthouselabs.obd.commands.pressure.BarometricPressureObdCommand; import eu.lighthouselabs.obd.commands.pressure.FuelPressureObdCommand; import eu.lighthouselabs.obd.commands.pressure.IntakeManifoldPressureObdCommand; import eu.lighthouselabs.obd.commands.protocol.ObdResetCommand; import eu.lighthouselabs.obd.commands.temperature.AirIntakeTemperatureObdCommand; import eu.lighthouselabs.obd.commands.temperature.AmbientAirTemperatureObdCommand; import eu.lighthouselabs.obd.commands.temperature.EngineCoolantTemperatureObdCommand; import eu.lighthouselabs.obd.enums.FuelTrim; /** * TODO put description */ public final class ObdConfig { public static ArrayList<ObdCommand> getCommands() { ArrayList<ObdCommand> cmds = new ArrayList<ObdCommand>(); // Protocol cmds.add(new ObdResetCommand()); // Control cmds.add(new CommandEquivRatioObdCommand()); cmds.add(new DtcNumberObdCommand()); cmds.add(new TimingAdvanceObdCommand()); cmds.add(new TroubleCodesObdCommand(0)); // Engine cmds.add(new EngineLoadObdCommand()); cmds.add(new EngineRPMObdCommand()); cmds.add(new EngineRuntimeObdCommand()); cmds.add(new MassAirFlowObdCommand()); // Fuel // cmds.add(new AverageFuelEconomyObdCommand()); // cmds.add(new FuelEconomyObdCommand()); // cmds.add(new FuelEconomyMAPObdCommand()); // cmds.add(new FuelEconomyCommandedMAPObdCommand()); cmds.add(new FindFuelTypeObdCommand()); cmds.add(new FuelLevelObdCommand()); cmds.add(new FuelTrimObdCommand(FuelTrim.LONG_TERM_BANK_1)); cmds.add(new FuelTrimObdCommand(FuelTrim.LONG_TERM_BANK_2)); cmds.add(new FuelTrimObdCommand(FuelTrim.SHORT_TERM_BANK_1)); cmds.add(new FuelTrimObdCommand(FuelTrim.SHORT_TERM_BANK_2)); // Pressure cmds.add(new BarometricPressureObdCommand()); cmds.add(new FuelPressureObdCommand()); cmds.add(new IntakeManifoldPressureObdCommand()); // Temperature cmds.add(new AirIntakeTemperatureObdCommand()); cmds.add(new AmbientAirTemperatureObdCommand()); cmds.add(new EngineCoolantTemperatureObdCommand()); // Misc cmds.add(new SpeedObdCommand()); cmds.add(new ThrottlePositionObdCommand()); return cmds; } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/config/ObdConfig.java
Java
asf20
3,192
package eu.lighthouselabs.obd.reader.network; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class DataUploader { public String uploadRecord(String urlStr, Map<String,String> data) throws IOException, URISyntaxException { String encData = getEncodedData(data); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 30000); HttpClient client = new DefaultHttpClient(params); HttpPost request = new HttpPost(); request.setURI(new URI(urlStr)); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); request.setEntity(new StringEntity(encData)); ResponseHandler<String> resHandle = new BasicResponseHandler(); String response = client.execute(request,resHandle); return response; } public String getEncodedData(Map<String,String> data) throws UnsupportedEncodingException { StringBuffer buff = new StringBuffer(); Iterator<String> keys = data.keySet().iterator(); while (keys.hasNext()) { String k = keys.next(); buff.append(URLEncoder.encode(k,"UTF-8")); buff.append("="); buff.append(URLEncoder.encode(data.get(k),"UTF-8")); buff.append("&"); } return buff.toString(); } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/network/DataUploader.java
Java
asf20
1,900
/* * TODO put header */ package eu.lighthouselabs.obd.reader; import eu.lighthouselabs.obd.reader.io.ObdCommandJob; /** * TODO put description */ public interface IPostMonitor { void setListener(IPostListener callback); boolean isRunning(); void executeQueue(); void addJobToQueue(ObdCommandJob job); }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/IPostMonitor.java
Java
asf20
317
/* * TODO put header */ package eu.lighthouselabs.obd.reader; import eu.lighthouselabs.obd.reader.io.ObdCommandJob; /** * TODO put description */ public interface IPostListener { void stateUpdate(ObdCommandJob job); }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/IPostListener.java
Java
asf20
228
package eu.lighthouselabs.obd.reader.drawable; import eu.lighthouselabs.obd.reader.R; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.AttributeSet; public class CoolantGaugeView extends GradientGaugeView { public final static int min_temp = 35; public final static int max_temp = 138; public final static int TEXT_SIZE = 18; public final static int range = max_temp - min_temp; private int temp = min_temp; public CoolantGaugeView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; paint = new Paint(); paint.setTextSize(TEXT_SIZE); Typeface bold = Typeface.defaultFromStyle(Typeface.BOLD); paint.setTypeface(bold); paint.setStrokeWidth(3); paint.setStyle(Paint.Style.FILL_AND_STROKE); } public void setTemp(int temp) { this.temp = temp; if (this.temp < min_temp) { this.temp = min_temp + 2; } if (this.temp > max_temp) { this.temp = max_temp; } invalidate(); } @Override protected void onDraw(Canvas canvas) { Resources res = context.getResources(); Drawable container = (Drawable) res.getDrawable(R.drawable.coolant_gauge); int width = getWidth(); int left = getLeft(); int top = getTop(); paint.setColor(Color.BLUE); canvas.drawText("C",left,top+TEXT_SIZE,paint); paint.setColor(Color.RED); canvas.drawText("H", left+width-TEXT_SIZE, top+TEXT_SIZE, paint); drawGradient(canvas, container, TEXT_SIZE+5, temp-min_temp,range); } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/drawable/CoolantGaugeView.java
Java
asf20
1,652
package eu.lighthouselabs.obd.reader.drawable; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RectShape; import android.util.AttributeSet; import android.util.Log; import android.view.View; public abstract class GradientGaugeView extends View { protected Context context = null; protected Paint paint = null; public GradientGaugeView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; paint = new Paint(); } @Override protected abstract void onDraw(Canvas canvas); protected void drawGradient(Canvas canvas, Drawable container, int offset, double value, double range) { int width = getWidth(); int height = getHeight(); int left = getLeft(); int top = getTop(); Log.i("width",String.format("%d %d",width,left)); container.setBounds(left,top+offset,left+width,top+height+offset); container.draw(canvas); ShapeDrawable cover = new ShapeDrawable(new RectShape()); double perc = value / range; int coverLeft = (int)(width * perc); cover.setBounds(left+coverLeft, top+offset, left+width, top+height+offset); cover.draw(canvas); } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/drawable/GradientGaugeView.java
Java
asf20
1,285
package eu.lighthouselabs.obd.reader.drawable; import eu.lighthouselabs.obd.reader.R; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.AttributeSet; public class AccelGaugeView extends GradientGaugeView { public final static int TEXT_SIZE = 15; public final static int range = 20; private double accel = 2; public AccelGaugeView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; paint = new Paint(); paint.setTextSize(TEXT_SIZE); Typeface bold = Typeface.defaultFromStyle(Typeface.BOLD); paint.setTypeface(bold); paint.setStrokeWidth(3); paint.setStyle(Paint.Style.FILL); } public void setAccel(double accel) { this.accel = accel; } @Override protected void onDraw(Canvas canvas) { Resources res = context.getResources(); Drawable container = (Drawable) res.getDrawable(R.drawable.accel_gauge); int width = getWidth(); int left = getLeft(); int top = getTop(); paint.setColor(Color.GREEN); canvas.drawText("Soft",left,top+TEXT_SIZE,paint); paint.setColor(Color.RED); canvas.drawText("Hard", left+width-TEXT_SIZE*3, top+TEXT_SIZE, paint); drawGradient(canvas, container, TEXT_SIZE+5, accel, range); } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/drawable/AccelGaugeView.java
Java
asf20
1,406
/* * TODO put header */ package eu.lighthouselabs.obd.reader.activity; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.preference.PreferenceManager; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import eu.lighthouselabs.obd.commands.SpeedObdCommand; import eu.lighthouselabs.obd.commands.control.CommandEquivRatioObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineRPMObdCommand; import eu.lighthouselabs.obd.commands.engine.MassAirFlowObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelEconomyObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelEconomyWithMAFObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelLevelObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelTrimObdCommand; import eu.lighthouselabs.obd.commands.temperature.AmbientAirTemperatureObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; import eu.lighthouselabs.obd.enums.FuelTrim; import eu.lighthouselabs.obd.enums.FuelType; import eu.lighthouselabs.obd.reader.IPostListener; import eu.lighthouselabs.obd.reader.R; import eu.lighthouselabs.obd.reader.io.ObdCommandJob; import eu.lighthouselabs.obd.reader.io.ObdGatewayService; import eu.lighthouselabs.obd.reader.io.ObdGatewayServiceConnection; /** * The main activity. */ public class MainActivity extends Activity { private static final String TAG = "MainActivity"; /* * TODO put description */ static final int NO_BLUETOOTH_ID = 0; static final int BLUETOOTH_DISABLED = 1; static final int NO_GPS_ID = 2; static final int START_LIVE_DATA = 3; static final int STOP_LIVE_DATA = 4; static final int SETTINGS = 5; static final int COMMAND_ACTIVITY = 6; static final int TABLE_ROW_MARGIN = 7; static final int NO_ORIENTATION_SENSOR = 8; private Handler mHandler = new Handler(); /** * Callback for ObdGatewayService to update UI. */ private IPostListener mListener = null; private Intent mServiceIntent = null; private ObdGatewayServiceConnection mServiceConnection = null; private SensorManager sensorManager = null; private Sensor orientSensor = null; private SharedPreferences prefs = null; private PowerManager powerManager = null; private PowerManager.WakeLock wakeLock = null; private boolean preRequisites = true; private int speed = 1; private double maf = 1; private float ltft = 0; private double equivRatio = 1; private final SensorEventListener orientListener = new SensorEventListener() { public void onSensorChanged(SensorEvent event) { float x = event.values[0]; String dir = ""; if (x >= 337.5 || x < 22.5) { dir = "N"; } else if (x >= 22.5 && x < 67.5) { dir = "NE"; } else if (x >= 67.5 && x < 112.5) { dir = "E"; } else if (x >= 112.5 && x < 157.5) { dir = "SE"; } else if (x >= 157.5 && x < 202.5) { dir = "S"; } else if (x >= 202.5 && x < 247.5) { dir = "SW"; } else if (x >= 247.5 && x < 292.5) { dir = "W"; } else if (x >= 292.5 && x < 337.5) { dir = "NW"; } TextView compass = (TextView) findViewById(R.id.compass_text); updateTextView(compass, dir); } public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } }; public void updateTextView(final TextView view, final String txt) { new Handler().post(new Runnable() { public void run() { view.setText(txt); } }); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * TODO clean-up this upload thing * * ExceptionHandler.register(this, * "http://www.whidbeycleaning.com/droid/server.php"); */ setContentView(R.layout.main); mListener = new IPostListener() { public void stateUpdate(ObdCommandJob job) { String cmdName = job.getCommand().getName(); String cmdResult = job.getCommand().getFormattedResult(); Log.d(TAG, FuelTrim.LONG_TERM_BANK_1.getBank() + " equals " + cmdName + "?"); if (AvailableCommandNames.ENGINE_RPM.getValue().equals(cmdName)) { TextView tvRpm = (TextView) findViewById(R.id.rpm_text); tvRpm.setText(cmdResult); } else if (AvailableCommandNames.SPEED.getValue().equals( cmdName)) { TextView tvSpeed = (TextView) findViewById(R.id.spd_text); tvSpeed.setText(cmdResult); speed = ((SpeedObdCommand) job.getCommand()) .getMetricSpeed(); } else if (AvailableCommandNames.MAF.getValue().equals(cmdName)) { maf = ((MassAirFlowObdCommand) job.getCommand()).getMAF(); addTableRow(cmdName, cmdResult); } else if (FuelTrim.LONG_TERM_BANK_1.getBank().equals(cmdName)) { ltft = ((FuelTrimObdCommand) job.getCommand()).getValue(); } else if (AvailableCommandNames.EQUIV_RATIO.getValue().equals(cmdName)) { equivRatio = ((CommandEquivRatioObdCommand) job.getCommand()).getRatio(); addTableRow(cmdName, cmdResult); } else { addTableRow(cmdName, cmdResult); } } }; /* * Validate GPS service. */ LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager.getProvider(LocationManager.GPS_PROVIDER) == null) { /* * TODO for testing purposes we'll not make GPS a pre-requisite. */ // preRequisites = false; showDialog(NO_GPS_ID); } /* * Validate Bluetooth service. */ // Bluetooth device exists? final BluetoothAdapter mBtAdapter = BluetoothAdapter .getDefaultAdapter(); if (mBtAdapter == null) { preRequisites = false; showDialog(NO_BLUETOOTH_ID); } else { // Bluetooth device is enabled? if (!mBtAdapter.isEnabled()) { preRequisites = false; showDialog(BLUETOOTH_DISABLED); } } /* * Get Orientation sensor. */ sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); List<Sensor> sens = sensorManager .getSensorList(Sensor.TYPE_ORIENTATION); if (sens.size() <= 0) { showDialog(NO_ORIENTATION_SENSOR); } else { orientSensor = sens.get(0); } // validate app pre-requisites if (preRequisites) { /* * Prepare service and its connection */ mServiceIntent = new Intent(this, ObdGatewayService.class); mServiceConnection = new ObdGatewayServiceConnection(); mServiceConnection.setServiceListener(mListener); // bind service Log.d(TAG, "Binding service.."); bindService(mServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE); } } @Override protected void onDestroy() { super.onDestroy(); releaseWakeLockIfHeld(); mServiceIntent = null; mServiceConnection = null; mListener = null; mHandler = null; } @Override protected void onPause() { super.onPause(); Log.d(TAG, "Pausing.."); releaseWakeLockIfHeld(); } /** * If lock is held, release. Lock will be held when the service is running. */ private void releaseWakeLockIfHeld() { if (wakeLock.isHeld()) { wakeLock.release(); } } protected void onResume() { super.onResume(); Log.d(TAG, "Resuming.."); sensorManager.registerListener(orientListener, orientSensor, SensorManager.SENSOR_DELAY_UI); prefs = PreferenceManager.getDefaultSharedPreferences(this); powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ObdReader"); } private void updateConfig() { Intent configIntent = new Intent(this, ConfigActivity.class); startActivity(configIntent); } public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, START_LIVE_DATA, 0, "Start Live Data"); menu.add(0, COMMAND_ACTIVITY, 0, "Run Command"); menu.add(0, STOP_LIVE_DATA, 0, "Stop"); menu.add(0, SETTINGS, 0, "Settings"); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case START_LIVE_DATA: startLiveData(); return true; case STOP_LIVE_DATA: stopLiveData(); return true; case SETTINGS: updateConfig(); return true; // case COMMAND_ACTIVITY: // staticCommand(); // return true; } return false; } // private void staticCommand() { // Intent commandIntent = new Intent(this, ObdReaderCommandActivity.class); // startActivity(commandIntent); // } private void startLiveData() { Log.d(TAG, "Starting live data.."); if (!mServiceConnection.isRunning()) { Log.d(TAG, "Service is not running. Going to start it.."); startService(mServiceIntent); } // start command execution mHandler.post(mQueueCommands); // screen won't turn off until wakeLock.release() wakeLock.acquire(); } private void stopLiveData() { Log.d(TAG, "Stopping live data.."); if (mServiceConnection.isRunning()) stopService(mServiceIntent); // remove runnable mHandler.removeCallbacks(mQueueCommands); releaseWakeLockIfHeld(); } protected Dialog onCreateDialog(int id) { AlertDialog.Builder build = new AlertDialog.Builder(this); switch (id) { case NO_BLUETOOTH_ID: build.setMessage("Sorry, your device doesn't support Bluetooth."); return build.create(); case BLUETOOTH_DISABLED: build.setMessage("You have Bluetooth disabled. Please enable it!"); return build.create(); case NO_GPS_ID: build.setMessage("Sorry, your device doesn't support GPS."); return build.create(); case NO_ORIENTATION_SENSOR: build.setMessage("Orientation sensor missing?"); return build.create(); } return null; } public boolean onPrepareOptionsMenu(Menu menu) { MenuItem startItem = menu.findItem(START_LIVE_DATA); MenuItem stopItem = menu.findItem(STOP_LIVE_DATA); MenuItem settingsItem = menu.findItem(SETTINGS); MenuItem commandItem = menu.findItem(COMMAND_ACTIVITY); // validate if preRequisites are satisfied. if (preRequisites) { if (mServiceConnection.isRunning()) { startItem.setEnabled(false); stopItem.setEnabled(true); settingsItem.setEnabled(false); commandItem.setEnabled(false); } else { stopItem.setEnabled(false); startItem.setEnabled(true); settingsItem.setEnabled(true); commandItem.setEnabled(false); } } else { startItem.setEnabled(false); stopItem.setEnabled(false); settingsItem.setEnabled(false); commandItem.setEnabled(false); } return true; } private void addTableRow(String key, String val) { TableLayout tl = (TableLayout) findViewById(R.id.data_table); TableRow tr = new TableRow(this); MarginLayoutParams params = new ViewGroup.MarginLayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.setMargins(TABLE_ROW_MARGIN, TABLE_ROW_MARGIN, TABLE_ROW_MARGIN, TABLE_ROW_MARGIN); tr.setLayoutParams(params); tr.setBackgroundColor(Color.BLACK); TextView name = new TextView(this); name.setGravity(Gravity.RIGHT); name.setText(key + ": "); TextView value = new TextView(this); value.setGravity(Gravity.LEFT); value.setText(val); tr.addView(name); tr.addView(value); tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); /* * TODO remove this hack * * let's define a limit number of rows */ if (tl.getChildCount() > 10) tl.removeViewAt(0); } /** * */ private Runnable mQueueCommands = new Runnable() { public void run() { /* * If values are not default, then we have values to calculate MPG */ Log.d(TAG, "SPD:" + speed + ", MAF:" + maf + ", LTFT:" + ltft); if (speed > 1 && maf > 1 && ltft != 0) { FuelEconomyWithMAFObdCommand fuelEconCmd = new FuelEconomyWithMAFObdCommand( FuelType.DIESEL, speed, maf, ltft, false /* TODO */); TextView tvMpg = (TextView) findViewById(R.id.fuel_econ_text); String liters100km = String.format("%.2f", fuelEconCmd.getLitersPer100Km()); tvMpg.setText("" + liters100km); Log.d(TAG, "FUELECON:" + liters100km); } if (mServiceConnection.isRunning()) queueCommands(); // run again in 2s mHandler.postDelayed(mQueueCommands, 2000); } }; /** * */ private void queueCommands() { final ObdCommandJob airTemp = new ObdCommandJob( new AmbientAirTemperatureObdCommand()); final ObdCommandJob speed = new ObdCommandJob(new SpeedObdCommand()); final ObdCommandJob fuelEcon = new ObdCommandJob( new FuelEconomyObdCommand()); final ObdCommandJob rpm = new ObdCommandJob(new EngineRPMObdCommand()); final ObdCommandJob maf = new ObdCommandJob(new MassAirFlowObdCommand()); final ObdCommandJob fuelLevel = new ObdCommandJob( new FuelLevelObdCommand()); final ObdCommandJob ltft1 = new ObdCommandJob(new FuelTrimObdCommand( FuelTrim.LONG_TERM_BANK_1)); final ObdCommandJob ltft2 = new ObdCommandJob(new FuelTrimObdCommand( FuelTrim.LONG_TERM_BANK_2)); final ObdCommandJob stft1 = new ObdCommandJob(new FuelTrimObdCommand( FuelTrim.SHORT_TERM_BANK_1)); final ObdCommandJob stft2 = new ObdCommandJob(new FuelTrimObdCommand( FuelTrim.SHORT_TERM_BANK_2)); final ObdCommandJob equiv = new ObdCommandJob(new CommandEquivRatioObdCommand()); // mServiceConnection.addJobToQueue(airTemp); mServiceConnection.addJobToQueue(speed); // mServiceConnection.addJobToQueue(fuelEcon); mServiceConnection.addJobToQueue(rpm); mServiceConnection.addJobToQueue(maf); mServiceConnection.addJobToQueue(fuelLevel); // mServiceConnection.addJobToQueue(equiv); mServiceConnection.addJobToQueue(ltft1); // mServiceConnection.addJobToQueue(ltft2); // mServiceConnection.addJobToQueue(stft1); // mServiceConnection.addJobToQueue(stft2); } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/activity/MainActivity.java
Java
asf20
14,301
/* * TODO put header */ package eu.lighthouselabs.obd.reader.activity; import java.util.ArrayList; import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.widget.Toast; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.reader.R; import eu.lighthouselabs.obd.reader.config.ObdConfig; /** * Configuration activity. */ public class ConfigActivity extends PreferenceActivity implements OnPreferenceChangeListener { public static final String BLUETOOTH_LIST_KEY = "bluetooth_list_preference"; public static final String UPLOAD_URL_KEY = "upload_url_preference"; public static final String UPLOAD_DATA_KEY = "upload_data_preference"; public static final String UPDATE_PERIOD_KEY = "update_period_preference"; public static final String VEHICLE_ID_KEY = "vehicle_id_preference"; public static final String ENGINE_DISPLACEMENT_KEY = "engine_displacement_preference"; public static final String VOLUMETRIC_EFFICIENCY_KEY = "volumetric_efficiency_preference"; public static final String IMPERIAL_UNITS_KEY = "imperial_units_preference"; public static final String COMMANDS_SCREEN_KEY = "obd_commands_screen"; public static final String ENABLE_GPS_KEY = "enable_gps_preference"; public static final String MAX_FUEL_ECON_KEY = "max_fuel_econ_preference"; public static final String CONFIG_READER_KEY = "reader_config_preference"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * Read preferences resources available at res/xml/preferences.xml */ addPreferencesFromResource(R.xml.preferences); ArrayList<CharSequence> pairedDeviceStrings = new ArrayList<CharSequence>(); ArrayList<CharSequence> vals = new ArrayList<CharSequence>(); ListPreference listBtDevices = (ListPreference) getPreferenceScreen() .findPreference(BLUETOOTH_LIST_KEY); String[] prefKeys = new String[] { ENGINE_DISPLACEMENT_KEY, VOLUMETRIC_EFFICIENCY_KEY, UPDATE_PERIOD_KEY, MAX_FUEL_ECON_KEY }; for (String prefKey : prefKeys) { EditTextPreference txtPref = (EditTextPreference) getPreferenceScreen() .findPreference(prefKey); txtPref.setOnPreferenceChangeListener(this); } /* * Available OBD commands * * TODO This should be read from preferences database */ ArrayList<ObdCommand> cmds = ObdConfig.getCommands(); PreferenceScreen cmdScr = (PreferenceScreen) getPreferenceScreen() .findPreference(COMMANDS_SCREEN_KEY); for (ObdCommand cmd : cmds) { CheckBoxPreference cpref = new CheckBoxPreference(this); cpref.setTitle(cmd.getName()); cpref.setKey(cmd.getName()); cpref.setChecked(true); cmdScr.addPreference(cpref); } /* * Let's use this device Bluetooth adapter to select which paired OBD-II * compliant device we'll use. */ final BluetoothAdapter mBtAdapter = BluetoothAdapter .getDefaultAdapter(); if (mBtAdapter == null) { listBtDevices.setEntries(pairedDeviceStrings .toArray(new CharSequence[0])); listBtDevices.setEntryValues(vals.toArray(new CharSequence[0])); // we shouldn't get here, still warn user Toast.makeText(this, "This device does not support Bluetooth.", Toast.LENGTH_LONG); return; } /* * Listen for preferences click. * * TODO there are so many repeated validations :-/ */ final Activity thisActivity = this; listBtDevices.setEntries(new CharSequence[1]); listBtDevices.setEntryValues(new CharSequence[1]); listBtDevices .setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { // see what I mean in the previous comment? if (mBtAdapter == null || !mBtAdapter.isEnabled()) { Toast.makeText( thisActivity, "This device does not support Bluetooth or it is disabled.", Toast.LENGTH_LONG); return false; } return true; } }); /* * Get paired devices and populate preference list. */ Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { pairedDeviceStrings.add(device.getName() + "\n" + device.getAddress()); vals.add(device.getAddress()); } } listBtDevices.setEntries(pairedDeviceStrings .toArray(new CharSequence[0])); listBtDevices.setEntryValues(vals.toArray(new CharSequence[0])); } /** * OnPreferenceChangeListener method that will validate a preferencen new * value when it's changed. * * @param preference * the changed preference * @param newValue * the value to be validated and set if valid */ public boolean onPreferenceChange(Preference preference, Object newValue) { if (UPDATE_PERIOD_KEY.equals(preference.getKey()) || VOLUMETRIC_EFFICIENCY_KEY.equals(preference.getKey()) || ENGINE_DISPLACEMENT_KEY.equals(preference.getKey()) || UPDATE_PERIOD_KEY.equals(preference.getKey()) || MAX_FUEL_ECON_KEY.equals(preference.getKey())) { try { Double.parseDouble(newValue.toString()); return true; } catch (Exception e) { Toast.makeText( this, "Couldn't parse '" + newValue.toString() + "' as a number.", Toast.LENGTH_LONG).show(); } } return false; } /** * * @param prefs * @return */ public static int getUpdatePeriod(SharedPreferences prefs) { String periodString = prefs.getString(ConfigActivity.UPDATE_PERIOD_KEY, "4"); // 4 as in seconds int period = 4000; // by default 4000ms try { period = Integer.parseInt(periodString) * 1000; } catch (Exception e) { } if (period <= 0) { period = 250; } return period; } /** * * @param prefs * @return */ public static double getVolumetricEfficieny(SharedPreferences prefs) { String veString = prefs.getString( ConfigActivity.VOLUMETRIC_EFFICIENCY_KEY, ".85"); double ve = 0.85; try { ve = Double.parseDouble(veString); } catch (Exception e) { } return ve; } /** * * @param prefs * @return */ public static double getEngineDisplacement(SharedPreferences prefs) { String edString = prefs.getString( ConfigActivity.ENGINE_DISPLACEMENT_KEY, "1.6"); double ed = 1.6; try { ed = Double.parseDouble(edString); } catch (Exception e) { } return ed; } /** * * @param prefs * @return */ public static ArrayList<ObdCommand> getObdCommands(SharedPreferences prefs) { ArrayList<ObdCommand> cmds = ObdConfig.getCommands(); ArrayList<ObdCommand> ucmds = new ArrayList<ObdCommand>(); for (int i = 0; i < cmds.size(); i++) { ObdCommand cmd = cmds.get(i); boolean selected = prefs.getBoolean(cmd.getName(), true); if (selected) { ucmds.add(cmd); } } return ucmds; } /** * * @param prefs * @return */ public static double getMaxFuelEconomy(SharedPreferences prefs) { String maxStr = prefs.getString(ConfigActivity.MAX_FUEL_ECON_KEY, "70"); double max = 70; try { max = Double.parseDouble(maxStr); } catch (Exception e) { } return max; } /** * * @param prefs * @return */ public static String[] getReaderConfigCommands(SharedPreferences prefs) { String cmdsStr = prefs.getString(CONFIG_READER_KEY, "atsp0\natz"); String[] cmds = cmdsStr.split("\n"); return cmds; } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/activity/ConfigActivity.java
Java
asf20
7,871