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 |
|---|---|---|---|---|---|
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;
}
} | 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/messages/CoapMediaType.java | Java | asf20 | 869 |
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();
}
}
}
| 11106027-gokul | 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 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;
}
}
| 11106027-gokul | 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 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;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/messages/CoapRequestCode.java | Java | asf20 | 828 |
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);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/rest/Resource.java | Java | asf20 | 1,011 |
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();
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/rest/CoapResource.java | Java | asf20 | 1,070 |
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;
}
}
| 11106027-gokul | 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.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;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/rest/BasicCoapResource.java | Java | asf20 | 4,441 |
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;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/rest/CoreResource.java | Java | asf20 | 3,985 |
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);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/rest/ResourceServer.java | Java | asf20 | 1,366 |
package org.ws4d.coap.rest;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public interface ResourceHandler {
public void onPost(byte[] data);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/rest/ResourceHandler.java | Java | asf20 | 181 |
/* 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;
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/Constants.java | Java | asf20 | 1,164 |
package org.ws4d.coap.interfaces;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public interface CoapServer extends CoapChannelListener {
public CoapServer onAccept(CoapRequest request);
public void onRequest(CoapServerChannel channel, CoapRequest request);
public void onSeparateResponseFailed(CoapServerChannel channel);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapServer.java | Java | asf20 | 373 |
/* 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.interfaces;
import org.ws4d.coap.messages.AbstractCoapMessage.CoapHeaderOptionType;
import org.ws4d.coap.messages.CoapBlockOption;
import org.ws4d.coap.messages.CoapMediaType;
import org.ws4d.coap.messages.CoapPacketType;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public interface CoapMessage {
public static final int RESPONSE_TIMEOUT_MS = 2000;
public static final double RESPONSE_RANDOM_FACTOR = 1.5;
public static final int MAX_RETRANSMIT = 4;
/* TODO: what is the right value? */
public static final int ACK_RST_RETRANS_TIMEOUT_MS = 120000;
/* returns the value of the internal message code
* in case of an error this function returns -1 */
public int getMessageCodeValue();
public int getMessageID();
public void setMessageID(int msgID);
public byte[] serialize();
public void incRetransCounterAndTimeout();
public CoapPacketType getPacketType();
public byte[] getPayload();
public void setPayload(byte[] payload);
public void setPayload(char[] payload);
public void setPayload(String payload);
public int getPayloadLength();
public void setContentType(CoapMediaType mediaType);
public CoapMediaType getContentType();
public byte[] getToken();
// public URI getRequestUri();
//
// public void setRequestUri(URI uri); //TODO:allow this method only for Clients, Define Token Type
CoapBlockOption getBlock1();
void setBlock1(CoapBlockOption blockOption);
CoapBlockOption getBlock2();
void setBlock2(CoapBlockOption blockOption);
public Integer getObserveOption();
public void setObserveOption(int sequenceNumber);
public void removeOption(CoapHeaderOptionType optionType); //TODO: could this compromise the internal state?
public String toString();
public CoapChannel getChannel();
public void setChannel(CoapChannel channel);
public int getTimeout();
public boolean maxRetransReached();
public boolean isReliable();
public boolean isRequest();
public boolean isResponse();
public boolean isEmpty();
/* unique by remote address, remote port, local port and message id */
public int hashCode();
public boolean equals(Object obj);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapMessage.java | Java | asf20 | 3,026 |
package org.ws4d.coap.interfaces;
import java.util.Vector;
import org.ws4d.coap.messages.CoapMediaType;
import org.ws4d.coap.messages.CoapRequestCode;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public interface CoapRequest extends CoapMessage{
public void setUriHost(String host);
public void setUriPort(int port);
public void setUriPath(String path);
public void setUriQuery(String query);
public void setProxyUri(String proxyUri);
public void setToken(byte[] token);
public void addAccept(CoapMediaType mediaType);
public Vector<CoapMediaType> getAccept(CoapMediaType mediaType);
public String getUriHost();
public int getUriPort();
public String getUriPath();
public Vector<String> getUriQuery();
public String getProxyUri();
public void addETag(byte[] etag);
public Vector<byte[]> getETag();
public CoapRequestCode getRequestCode();
public void setRequestCode(CoapRequestCode requestCode);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapRequest.java | Java | asf20 | 1,011 |
package org.ws4d.coap.interfaces;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
import org.ws4d.coap.messages.CoapMediaType;
import org.ws4d.coap.messages.CoapResponseCode;
public interface CoapServerChannel extends CoapChannel {
/* creates a normal response */
public CoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode);
/* creates a normal response */
public CoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode, CoapMediaType contentType);
/* creates a separate response and acks the current request witch an empty ACK in case of a CON.
* The separate response can be send later using sendSeparateResponse() */
public CoapResponse createSeparateResponse(CoapRequest request,
CoapResponseCode responseCode);
/* used by a server to send a separate response */
public void sendSeparateResponse(CoapResponse response);
/* used by a server to create a notification (observing resources), reliability is base on the request packet type (con or non) */
public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber);
/* used by a server to create a notification (observing resources) */
public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber, boolean reliable);
/* used by a server to send a notification (observing resources) */
public void sendNotification(CoapResponse response);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapServerChannel.java | Java | asf20 | 1,516 |
package org.ws4d.coap.interfaces;
import org.ws4d.coap.messages.CoapRequestCode;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public interface CoapClientChannel extends CoapChannel {
public CoapRequest createRequest(boolean reliable, CoapRequestCode requestCode);
public void setTrigger(Object o);
public Object getTrigger();
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapClientChannel.java | Java | asf20 | 383 |
package org.ws4d.coap.interfaces;
import org.ws4d.coap.messages.CoapResponseCode;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public interface CoapResponse extends CoapMessage{
/* TODO: Response Code is part of BasicCoapResponse */
public CoapResponseCode getResponseCode();
public void setMaxAge(int maxAge);
public long getMaxAge();
public void setETag(byte[] etag);
public byte[] getETag();
public void setResponseCode(CoapResponseCode responseCode);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapResponse.java | Java | asf20 | 514 |
package org.ws4d.coap.interfaces;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
import java.net.InetAddress;
import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize;
public interface CoapChannel {
public void sendMessage(CoapMessage msg);
/*TODO: close when finished, & abort()*/
public void close();
public InetAddress getRemoteAddress();
public int getRemotePort();
/* handles an incomming message */
public void handleMessage(CoapMessage message);
/*TODO: implement Error Type*/
public void lostConnection(boolean notReachable, boolean resetByServer);
public CoapBlockSize getMaxReceiveBlocksize();
public void setMaxReceiveBlocksize(CoapBlockSize maxReceiveBlocksize);
public CoapBlockSize getMaxSendBlocksize();
public void setMaxSendBlocksize(CoapBlockSize maxSendBlocksize);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapChannel.java | Java | asf20 | 908 |
/* 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.interfaces;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
import java.net.InetAddress;
import org.ws4d.coap.messages.BasicCoapRequest;
public interface CoapChannelManager {
public int getNewMessageID();
/* called by the socket Listener to create a new Server Channel
* the Channel Manager then asked the Server Listener if he wants to accept a new connection */
public CoapServerChannel createServerChannel(CoapSocketHandler socketHandler, CoapMessage message, InetAddress addr, int port);
/* creates a server socket listener for incoming connections */
public void createServerListener(CoapServer serverListener, int localPort);
/* called by a client to create a connection
* TODO: allow client to bind to a special port */
public CoapClientChannel connect(CoapClient client, InetAddress addr, int port);
/* This function is for testing purposes only, to have a determined message id*/
public void setMessageId(int globalMessageId);
public void initRandom();
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapChannelManager.java | Java | asf20 | 1,751 |
package org.ws4d.coap.interfaces;
import java.net.InetAddress;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public interface CoapSocketHandler {
// public void registerResponseListener(CoapResponseListener
// responseListener);
// public void unregisterResponseListener(CoapResponseListener
// responseListener);
// public int sendRequest(CoapMessage request);
// public void sendResponse(CoapResponse response);
// public void establish(DatagramSocket socket);
// public void testConfirmation(int msgID);
//
// public boolean isOpen();
/* TODO */
public CoapClientChannel connect(CoapClient client, InetAddress remoteAddress, int remotePort);
public void close();
public void sendMessage(CoapMessage msg);
public CoapChannelManager getChannelManager();
int getLocalPort();
void removeClientChannel(CoapClientChannel channel);
void removeServerChannel(CoapServerChannel channel);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapSocketHandler.java | Java | asf20 | 978 |
package org.ws4d.coap.interfaces;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public interface CoapChannelListener {
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapChannelListener.java | Java | asf20 | 158 |
package org.ws4d.coap.interfaces;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public interface CoapClient extends CoapChannelListener {
public void onResponse(CoapClientChannel channel, CoapResponse response);
public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer);
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapClient.java | Java | asf20 | 366 |
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;
}
}
| 11106027-gokul | ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ProxyResource.java | Java | asf20 | 569 |
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();
}
}
}
| 11106027-gokul | 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.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;
}
}
| 11106027-gokul | ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ProxyMessageContext.java | Java | asf20 | 6,941 |
/*
* 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;
}
}
}
| 11106027-gokul | 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 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
}
}
| 11106027-gokul | ws4d-jcoap-applications/src/org/ws4d/coap/proxy/CoapServerProxy.java | Java | asf20 | 5,742 |
/*
* 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();
}
}
}
| 11106027-gokul | ws4d-jcoap-applications/src/org/ws4d/coap/proxy/ModifiedAsyncNHttpServiceHandler.java | Java | asf20 | 26,831 |
/*
* 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);
}
}
}
}
| 11106027-gokul | 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 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();
}
}
| 11106027-gokul | 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 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();
}
}
| 11106027-gokul | 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.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;
}
}
| 11106027-gokul | 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 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);
}
}
}
| 11106027-gokul | 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 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"));
}
}
}
}
| 11106027-gokul | ws4d-jcoap-applications/src/org/ws4d/coap/proxy/HttpServerNIO.java | Java | asf20 | 6,394 |
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()));
}
}
| 11106027-gokul | 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");
}
}
| 11106027-gokul | 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");
}
}
}
}
| 11106027-gokul | ws4d-jcoap-applications/src/org/ws4d/coap/udp/UDPRelay.java | Java | asf20 | 3,828 |
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();
}
}
}
| 11106027-gokul | 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");
}
}
| 11106027-gokul | ws4d-jcoap-applications/src/org/ws4d/coap/server/SeparateResponseCoapServer.java | Java | asf20 | 2,697 |
/* 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.");
}
}
| 11106027-gokul | ws4d-jcoap-applications/src/org/ws4d/coap/server/BasicCoapServer.java | Java | asf20 | 2,460 |
#coding=utf8
from django.db import models
class Address(models.Model):
name = models.CharField(max_length=20)
address = models.CharField(max_length=100)
pub_date = models.DateField()
| 11blog | trunk/11blog/address/models.py | Python | bsd | 200 |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| 11blog | trunk/11blog/address/tests.py | Python | bsd | 399 |
from django.conf.urls.defaults import patterns, url
__author__ = 'Administrator'
urlpatterns = patterns('address.views',
url(r'^test/$','test')
) | 11blog | trunk/11blog/address/urls.py | Python | bsd | 155 |
from django.contrib import admin
from address.models import Address
__author__ = 'Administrator'
admin.site.register(Address) | 11blog | trunk/11blog/address/admin.py | Python | bsd | 130 |
# Create your views here.
import urllib2
from django.http import HttpResponse
from django.shortcuts import render_to_response
from models import Address
def latest_address(request):
addresslist = Address.objects.order_by('-pub_date')[:10]
return render_to_response('latest_address.html', {'addresslist':addresslist})
def test(request):
ret = urllib2.urlopen("http://friend.renren.com/GetFriendList.do?id=227638867").read()
print ret
return HttpResponse(ret) | 11blog | trunk/11blog/address/views.py | Python | bsd | 492 |
from BeautifulSoup import BeautifulSoup
__author__ = 'Administrator'
import urllib,urllib2,cookielib
from BeautifulSoup import BeautifulSoup
myCookie = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
openner = urllib2.build_opener(myCookie)
post_data = {'email':'yinjj472@nenu.edu.cn',
'password':'112074',
'origURL':'http://www.renren.com/Home.do',
'domain':'renren.com'}
req = urllib2.Request('http://www.renren.com/PLogin.do', urllib.urlencode(post_data))
html_src = openner.open(req).read()
#print(html_src),"####################"
#parser = BeautifulSoup(html_src)
#
#article_list = parser.find('div', 'feed-list').findAll('article')
#for my_article in article_list:
# state = []
# for my_tag in my_article.h3.contents:
# factor = my_tag.string
# if factor != None:
# factor = factor.replace(u'\xa0','')
# factor = factor.strip(u'\r\n')
# factor = factor.strip(u'\n')
# state.append(factor)
# print ' '.join(state)
req = urllib2.Request('http://friend.renren.com/GetFriendList.do?curpage=2&id=227638867')
html_src = openner.open(req).read()
print(html_src) | 11blog | trunk/11blog/address/login.py | Python | bsd | 1,203 |
#coding=utf8
from django.db import models
class Address(models.Model):
name = models.CharField(max_length=20)
address = models.CharField(max_length=100)
pub_date = models.DateField()
| 11blog | trunk/11blog/DjangoDemo/trunk/address/models.py | Python | bsd | 200 |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| 11blog | trunk/11blog/DjangoDemo/trunk/address/tests.py | Python | bsd | 399 |
from django.conf.urls.defaults import patterns, url
__author__ = 'Administrator'
urlpatterns = patterns('address.views',
url(r'^test/$','test')
) | 11blog | trunk/11blog/DjangoDemo/trunk/address/urls.py | Python | bsd | 155 |
from django.contrib import admin
from address.models import Address
__author__ = 'Administrator'
admin.site.register(Address) | 11blog | trunk/11blog/DjangoDemo/trunk/address/admin.py | Python | bsd | 130 |
# Create your views here.
import urllib2
from django.http import HttpResponse
from django.shortcuts import render_to_response
from models import Address
def latest_address(request):
addresslist = Address.objects.order_by('-pub_date')[:10]
return render_to_response('latest_address.html', {'addresslist':addresslist})
def test(request):
ret = urllib2.urlopen("http://friend.renren.com/GetFriendList.do?id=227638867").read()
print ret
return HttpResponse(ret) | 11blog | trunk/11blog/DjangoDemo/trunk/address/views.py | Python | bsd | 492 |
from BeautifulSoup import BeautifulSoup
__author__ = 'Administrator'
import urllib,urllib2,cookielib
from BeautifulSoup import BeautifulSoup
myCookie = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
openner = urllib2.build_opener(myCookie)
post_data = {'email':'yinjj472@nenu.edu.cn',
'password':'112074',
'origURL':'http://www.renren.com/Home.do',
'domain':'renren.com'}
req = urllib2.Request('http://www.renren.com/PLogin.do', urllib.urlencode(post_data))
html_src = openner.open(req).read()
#print(html_src),"####################"
#parser = BeautifulSoup(html_src)
#
#article_list = parser.find('div', 'feed-list').findAll('article')
#for my_article in article_list:
# state = []
# for my_tag in my_article.h3.contents:
# factor = my_tag.string
# if factor != None:
# factor = factor.replace(u'\xa0','')
# factor = factor.strip(u'\r\n')
# factor = factor.strip(u'\n')
# state.append(factor)
# print ' '.join(state)
req = urllib2.Request('http://friend.renren.com/GetFriendList.do?curpage=2&id=227638867')
html_src = openner.open(req).read()
print(html_src) | 11blog | trunk/11blog/DjangoDemo/trunk/address/login.py | Python | bsd | 1,203 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<h2>this is latest_address html</h2>
<ul>
{% for address in addresslist %}
<li>{{ address.name }}</li>
{% endfor %}
</ul>
</body>
</html> | 11blog | trunk/11blog/DjangoDemo/trunk/templates/latest_address.html | HTML | bsd | 351 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<h2>通讯录</h2>
<table border="1">
<tr>
<th>姓名</th>
<th>地址</th>
</tr>
{% for user in address %}
<tr>
<td>{{ user.name}}</td>
<td>{{ user.address}}</td>
</tr>
{% endfor %}
</table>
</body>
</html> | 11blog | trunk/11blog/DjangoDemo/trunk/templates/list.html | HTML | bsd | 510 |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| 11blog | trunk/11blog/DjangoDemo/trunk/manage.py | Python | bsd | 517 |
from django.db import models
# Create your models here.
| 11blog | trunk/11blog/DjangoDemo/trunk/TestApp/models.py | Python | bsd | 60 |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| 11blog | trunk/11blog/DjangoDemo/trunk/TestApp/tests.py | Python | bsd | 399 |
__author__ = 'Administrator'
from django.http import HttpResponse
def index(request):
return HttpResponse("hello, Django.\n jiajia.yin, you must work hard for programing!") | 11blog | trunk/11blog/DjangoDemo/trunk/TestApp/helloworld.py | Python | bsd | 181 |
__author__ = 'Administrator'
from django.http import HttpResponse
text = '''<form method="post" action="add">
<input type="text" name="a" value="%d"></input> + <input type="text" name="b" value="%d"></input>
<input type="submit" value="="></input> <input type="text" name="c" value="%d"></input>
</form>'''
def index(request):
if request.POST.has_key('a'):
a = int(request.POST['a'])
b = int(request.POST['b'])
else:
a = 0
b = 0
return HttpResponse(text %(a,b,a+b)) | 11blog | trunk/11blog/DjangoDemo/trunk/TestApp/add.py | Python | bsd | 534 |
#coding=utf-8
__author__ = 'Administrator'
from django.shortcuts import render_to_response
address = [
{'name':'张三', 'address':'地址一'},
{'name':'李四', 'address':'地址二'}
]
def index(request):
return render_to_response('list.html', {'address': address}) | 11blog | trunk/11blog/DjangoDemo/trunk/TestApp/list.py | Python | bsd | 292 |
# Create your views here.
| 11blog | trunk/11blog/DjangoDemo/trunk/TestApp/views.py | Python | bsd | 27 |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| 11blog | trunk/11blog/DjangoDemo/trunk/.svn/text-base/manage.py.svn-base | Python | bsd | 517 |
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'DjangoDemo.views.home', name='home'),
# url(r'^DjangoDemo/', include('DjangoDemo.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
#user add the url to python.file
url(r'^address/', include('address.urls')),
#this is commit words
)
| 11blog | trunk/11blog/DjangoDemo/trunk/urls.py | Python | bsd | 702 |
# Django settings for DjangoDemo project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'nothing', # Not used with sqlite3.
'HOST': '10.2.136.250', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '5)bs^k@wfsd!kyl*h-0*3psrpz(@i0ro-556bo4d9i8nq0)s!-'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
)
ROOT_URLCONF = 'DjangoDemo.urls'
TEMPLATE_DIRS = ('C:/Documents and Settings/Administrator/PycharmProjects/DjangoDemo/templates','./templates',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'DjangoDemo.TestApp',
'DjangoDemo.address',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| 11blog | trunk/11blog/DjangoDemo/trunk/settings.py | Python | bsd | 5,212 |
from django.db import models
# Create your models here.
class wiki(models.Model):
pagename = models.CharField(max_length=20, unique=True)
content = models.TextField()
| 11blog | trunk/11blog/DjangoDemo/trunk/wiki/models.py | Python | bsd | 182 |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| 11blog | trunk/11blog/DjangoDemo/trunk/wiki/tests.py | Python | bsd | 399 |
# Create your views here.
#coding=utf8
from wiki.models import wiki
from django.template import loader
from django.template import context
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def index(request, pagename=""):
if pagename:
pages = wiki.get_list(pagename__exact) | 11blog | trunk/11blog/DjangoDemo/trunk/wiki/views.py | Python | bsd | 377 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<h2>this is latest_address html</h2>
<ul>
{% for address in addresslist %}
<li>{{ address.name }}</li>
{% endfor %}
</ul>
</body>
</html> | 11blog | trunk/11blog/templates/latest_address.html | HTML | bsd | 351 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<h2>通讯录</h2>
<table border="1">
<tr>
<th>姓名</th>
<th>地址</th>
</tr>
{% for user in address %}
<tr>
<td>{{ user.name}}</td>
<td>{{ user.address}}</td>
</tr>
{% endfor %}
</table>
</body>
</html> | 11blog | trunk/11blog/templates/list.html | HTML | bsd | 510 |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| 11blog | trunk/11blog/manage.py | Python | bsd | 517 |
from django.db import models
# Create your models here.
| 11blog | trunk/11blog/TestApp/models.py | Python | bsd | 60 |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| 11blog | trunk/11blog/TestApp/tests.py | Python | bsd | 399 |
__author__ = 'Administrator'
from django.http import HttpResponse
def index(request):
return HttpResponse("hello, Django.\n jiajia.yin, you must work hard for programing!") | 11blog | trunk/11blog/TestApp/helloworld.py | Python | bsd | 181 |
__author__ = 'Administrator'
from django.http import HttpResponse
text = '''<form method="post" action="add">
<input type="text" name="a" value="%d"></input> + <input type="text" name="b" value="%d"></input>
<input type="submit" value="="></input> <input type="text" name="c" value="%d"></input>
</form>'''
def index(request):
if request.POST.has_key('a'):
a = int(request.POST['a'])
b = int(request.POST['b'])
else:
a = 0
b = 0
return HttpResponse(text %(a,b,a+b)) | 11blog | trunk/11blog/TestApp/add.py | Python | bsd | 534 |
#coding=utf-8
__author__ = 'Administrator'
from django.shortcuts import render_to_response
address = [
{'name':'张三', 'address':'地址一'},
{'name':'李四', 'address':'地址二'}
]
def index(request):
return render_to_response('list.html', {'address': address}) | 11blog | trunk/11blog/TestApp/list.py | Python | bsd | 292 |
# Create your views here.
| 11blog | trunk/11blog/TestApp/views.py | Python | bsd | 27 |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| 11blog | trunk/11blog/.svn/text-base/manage.py.svn-base | Python | bsd | 517 |
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'DjangoDemo.views.home', name='home'),
# url(r'^DjangoDemo/', include('DjangoDemo.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
#user add the url to python.file
url(r'^address/', include('address.urls'))
)
| 11blog | trunk/11blog/urls.py | Python | bsd | 674 |
# Django settings for DjangoDemo project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'nothing', # Not used with sqlite3.
'HOST': '10.2.136.250', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '5)bs^k@wfsd!kyl*h-0*3psrpz(@i0ro-556bo4d9i8nq0)s!-'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
)
ROOT_URLCONF = 'DjangoDemo.urls'
TEMPLATE_DIRS = ('C:/Documents and Settings/Administrator/PycharmProjects/DjangoDemo/templates','./templates',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'DjangoDemo.TestApp',
'DjangoDemo.address',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| 11blog | trunk/11blog/settings.py | Python | bsd | 5,212 |
from django.db import models
# Create your models here.
class wiki(models.Model):
pagename = models.CharField(max_length=20, unique=True)
content = models.TextField()
| 11blog | trunk/11blog/wiki/models.py | Python | bsd | 182 |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| 11blog | trunk/11blog/wiki/tests.py | Python | bsd | 399 |
# Create your views here.
#coding=utf8
from wiki.models import wiki
from django.template import loader
from django.template import context
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def index(request, pagename=""):
if pagename:
pages = wiki.get_list(pagename__exact) | 11blog | trunk/11blog/wiki/views.py | Python | bsd | 377 |
/*
ScriptName: channeltab.js
Author: Akai
Website: http://nhacuato.com/
*/
$(document).ready(function() {
function ncttabs(rel) {
$channelcontent.hide();
$channeltab.removeClass("selected");
var id = rel.attr("rel");
$("#" + id).show();
rel.addClass("selected");
}
$channeltab = $(".container #main .channel .tabs a");
$channelcontent = $(".container #main .channel .main .tab-content");
$(".container #main .channel .main .tab-content:not(:first)").hide();
$channeltab.click(function() {
ncttabs($(this));
});
$channelcontent.first().show();
}); | 123tivi | 123tv/js/channeltab.js | JavaScript | oos | 592 |
$(document).ready(function() {
$channelr = $(".container #channelr");
$channelm = $(".container #channelr #channel");
$channelb = $(".container #channelr #channelb");
$channelg = $(".container #channelg");
$channelv = 0;
function channelh() {
if ($.browser.msie && $.browser.version.slice(0, 3) == "7.0") $channelm.css({zIndex: 1}).fadeOut();
else {
setTimeout(function() {
$channelr.css({zIndex: -1});
}, 100);
setTimeout(function() {
$channelm.css({zIndex: -1});
}, 200);
setTimeout(function() {
$channelr.css({zIndex: ""});
}, 300);
}
$channelr.animate({marginTop: -$channelm.height() + 2}, 500);
$channelb.css({backgroundImage: "url(http://123tivi.googlecode.com/svn/123tv/images/channelu.png)"});
$channelv = 0;
}
function channels() {
if ($.browser.msie && $.browser.version.slice(0, 3) == "7.0") {
setTimeout(function() {
$channelm.css({zIndex: -1}).fadeIn();
}, 200);
setTimeout(function() {
$channelm.css({zIndex: 1});
}, 500);
} else {
setTimeout(function() {
$channelr.css({zIndex: -1});
}, 100);
setTimeout(function() {
$channelm.css({zIndex: 0});
}, 200);
setTimeout(function() {
$channelr.css({zIndex: 0});
}, 300);
}
$channelr.animate({marginTop: -$channelr.height() * 2}, 500);
$channelb.css({backgroundImage: "url(http://123tivi.googlecode.com/svn/123tv/images/channeld.png)"});
$channelv = 1;
}
function nctchanneli(rel) {
if ($.browser.msie && $.browser.version.slice(0, 3) == "7.0") $(".container #channelg:not(:first)").hide();
$channelg.hide();
$(".container #channelr #channel a").removeClass("selected");
var id = rel.attr("rel");
$("." + id).show();
rel.addClass("selected");
}
$channelb.click(function() {
if ($channelv == 1) channelh();
else channels();
});
$channelr.css({width: $channelg.width()});
if ($.browser.msie && $.browser.version.slice(0, 3) == "7.0") $channelm.before("<div style=\"height: 1px; background: #ff4e00; width:960px;\"></div>").hide();
else $channelm.css({zIndex: -1}).before("<div style=\"height: 1px; background: #ff4e00; width:960px;\"></div>");
$(".container #channelg:not(:first)").hide();
$(".container #channelr #channel a").click(function() {
nctchanneli($(this));
});
$channelg.first().show();
}); | 123tivi | 123tv/js/channel.js | JavaScript | oos | 2,300 |
/************************************************************************/
/* Rainbow Links Version 1.03 (2003.9.20) */
/* Script updated by Dynamicdrive.com for IE6 */
/* Copyright (C) 1999-2001 TAKANASHI Mizuki */
/* takanasi@hamal.freemail.ne.jp */
/*----------------------------------------------------------------------*/
/* Read it somehow even if my English text is a little wrong! ;-) */
/* */
/* Usage: */
/* Insert '<script src="rainbow.js"></script>' into the BODY section, */
/* right after the BODY tag itself, before anything else. */
/* You don't need to add "onMouseover" and "onMouseout" attributes!! */
/* */
/* If you'd like to add effect to other texts(not link texts), then */
/* add 'onmouseover="doRainbow(this);"' and */
/* 'onmouseout="stopRainbow();"' to the target tags. */
/* */
/* This Script works with IE4,Netscape6,Mozilla browser and above only, */
/* but no error occurs on other browsers. */
/************************************************************************/
////////////////////////////////////////////////////////////////////
// Setting
var rate = 20; // Increase amount(The degree of the transmutation)
////////////////////////////////////////////////////////////////////
// Main routine
if (document.getElementById)
window.onerror=new Function("return true")
var objActive; // The object which event occured in
var act = 0; // Flag during the action
var elmH = 0; // Hue
var elmS = 128; // Saturation
var elmV = 255; // Value
var clrOrg; // A color before the change
var TimerID; // Timer ID
if (document.all) {
document.onmouseover = doRainbowAnchor;
document.onmouseout = stopRainbowAnchor;
}
else if (document.getElementById) {
document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
document.onmouseover = Mozilla_doRainbowAnchor;
document.onmouseout = Mozilla_stopRainbowAnchor;
}
//=============================================================================
// doRainbow
// This function begins to change a color.
//=============================================================================
function doRainbow(obj)
{
if (act == 0) {
act = 1;
if (obj)
objActive = obj;
else
objActive = event.srcElement;
clrOrg = objActive.style.color;
TimerID = setInterval("ChangeColor()",100);
}
}
//=============================================================================
// stopRainbow
// This function stops to change a color.
//=============================================================================
function stopRainbow()
{
if (act) {
objActive.style.color = clrOrg;
clearInterval(TimerID);
act = 0;
}
}
//=============================================================================
// doRainbowAnchor
// This function begins to change a color. (of a anchor, automatically)
//=============================================================================
function doRainbowAnchor()
{
if (act == 0) {
var obj = event.srcElement;
while (obj.tagName != 'A' && obj.tagName != 'BODY') {
obj = obj.parentElement;
if (obj.tagName == 'A' || obj.tagName == 'BODY')
break;
}
if (obj.tagName == 'A' && obj.href != '') {
objActive = obj;
act = 1;
clrOrg = objActive.style.color;
TimerID = setInterval("ChangeColor()",100);
}
}
}
//=============================================================================
// stopRainbowAnchor
// This function stops to change a color. (of a anchor, automatically)
//=============================================================================
function stopRainbowAnchor()
{
if (act) {
if (objActive.tagName == 'A') {
objActive.style.color = clrOrg;
clearInterval(TimerID);
act = 0;
}
}
}
//=============================================================================
// Mozilla_doRainbowAnchor(for Netscape6 and Mozilla browser)
// This function begins to change a color. (of a anchor, automatically)
//=============================================================================
function Mozilla_doRainbowAnchor(e)
{
if (act == 0) {
obj = e.target;
while (obj.nodeName != 'A' && obj.nodeName != 'BODY') {
obj = obj.parentNode;
if (obj.nodeName == 'A' || obj.nodeName == 'BODY')
break;
}
if (obj.nodeName == 'A' && obj.href != '') {
objActive = obj;
act = 1;
clrOrg = obj.style.color;
TimerID = setInterval("ChangeColor()",100);
}
}
}
//=============================================================================
// Mozilla_stopRainbowAnchor(for Netscape6 and Mozilla browser)
// This function stops to change a color. (of a anchor, automatically)
//=============================================================================
function Mozilla_stopRainbowAnchor(e)
{
if (act) {
if (objActive.nodeName == 'A') {
objActive.style.color = clrOrg;
clearInterval(TimerID);
act = 0;
}
}
}
//=============================================================================
// Change Color
// This function changes a color actually.
//=============================================================================
function ChangeColor()
{
objActive.style.color = makeColor();
}
//=============================================================================
// makeColor
// This function makes rainbow colors.
//=============================================================================
function makeColor()
{
// Don't you think Color Gamut to look like Rainbow?
// HSVtoRGB
if (elmS == 0) {
elmR = elmV; elmG = elmV; elmB = elmV;
}
else {
t1 = elmV;
t2 = (255 - elmS) * elmV / 255;
t3 = elmH % 30;
t3 = (t1 - t2) * t3 / 30;
if (elmH < 60) {
elmR = t1; elmB = t2; elmG = t2 + t3;
}
else if (elmH < 120) {
elmG = t1; elmB = t2; elmR = t1 - t3;
}
else if (elmH < 180) {
elmG = t1; elmR = t2; elmB = t2 + t3;
}
else if (elmH < 240) {
elmB = t1; elmR = t2; elmG = t1 - t3;
}
else if (elmH < 300) {
elmB = t1; elmG = t2; elmR = t2 + t3;
}
else if (elmH < 360) {
elmR = t1; elmG = t2; elmB = t1 - t3;
}
else {
elmR = 0; elmG = 0; elmB = 0;
}
}
elmR = Math.floor(elmR).toString(16);
elmG = Math.floor(elmG).toString(16);
elmB = Math.floor(elmB).toString(16);
if (elmR.length == 1) elmR = "0" + elmR;
if (elmG.length == 1) elmG = "0" + elmG;
if (elmB.length == 1) elmB = "0" + elmB;
elmH = elmH + rate;
if (elmH >= 360)
elmH = 0;
return '#' + elmR + elmG + elmB;
}
| 123tivi | 123tv/js/link.js | JavaScript | oos | 7,546 |
function hm_play(linkxem) {
if (linkxem.indexOf('id="embed_tv"')!=-1) {
var play = linkxem;
}
else if (linkxem.indexOf("http://")!=-1) {
if (linkxem.indexOf("http://tv-msn.com")!=-1 || linkxem.indexOf("http://www2.k-tv.at")!=-1 || linkxem.indexOf("http://vtc.com.vn")!=-1 || linkxem.indexOf("http://tv24.vn")!=-1 || linkxem.indexOf("http://itv.vtc.vn/")!=-1 || linkxem.indexOf("http://megafun.vn/")!=-1 || linkxem.indexOf("http://farm.vtc.vn/")!=-1 || linkxem.indexOf("http://www.htvc.vn/")!=-1 || linkxem.indexOf("http://www.vpoptv.com")!=-1 ) {
var play = '<iframe src="'+linkxem+'" scrolling="no" frameborder="0" width="100%" height="100%"></iframe>'
}
else if (linkxem.indexOf("http://static.livestream.com")!=-1) {
var play = '<embed type="application/x-shockwave-flash" src="'+linkxem+'" quality="high" allowfullscreen="true" allowscriptaccess="always" wmode="opaque" width="100%" height="100%"/>';
}
else if (linkxem.indexOf("http://tikilive.com/public/")!=-1) {
var play = '<embed allowFullScreen="true" src="'+linkxem+'&advertisment=0&showChat=0&pwidth=100%&pheight=100%" type="application/x-shockwave-flash" width="100%" height="100%" allowScriptAccess="always"></embed>';
}
else if (linkxem.indexOf("file=http://")!=-1) {
var play = '<embed type="application/x-shockwave-flash" wmode="opaque" allowscriptaccess="always" allowfullscreen="true" src="https://123tivi.googlecode.com/svn/trunk/123tv/player.swf?'+linkxem+'&provider=http%3A%2F%2Fmegafun.vn%2Fcommon%2Fplayer%2FadaptiveProvider.swf&autostart=true&controlbar=bottom&skin=https://123tivi.googlecode.com/svn/trunk/123tv/skin.zip" width="100%" height="100%"/>';
}
else {
var play = '<EMBED EnableContextMenu="0" type="application/x-mplayer2" showstatusbar="1" SRC="'+linkxem+'" pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/" width="100%" height="100%">';
}
}
else if (linkxem.indexOf("rtmp://")!=-1 || linkxem.indexOf("&file=")!=-1 || linkxem.indexOf("&file=")!=-1) {
var play = '<embed type="application/x-shockwave-flash" src="https://123tivi.googlecode.com/svn/trunk/123tv/player.swf" quality="high" allowfullscreen="true" allowscriptaccess="always" wmode="opaque" flashvars="streamer='+linkxem+'&type=rtmp&fullscreen=true&autostart=true&controlbar=bottom&skin=https://123tivi.googlecode.com/svn/trunk/123tv/skin.zip&image=images/logo.png" width="100%" height="100%"/>';
}
else if (linkxem.indexOf("file=")!=-1) {
var play = '<embed type="application/x-shockwave-flash" wmode="opaque" allowscriptaccess="always" allowfullscreen="true" src="https://123tivi.googlecode.com/svn/trunk/123tv/player.swf?'+linkxem+'&provider=http%3A%2F%2Fmegafun.vn%2Fcommon%2Fplayer%2FadaptiveProvider.swf&autostart=true&controlbar=bottom&skin=https://123tivi.googlecode.com/svn/trunk/123tv/skin.zip" width="100%" height="100%"/>';
}
else if (linkxem.indexOf("mms://")!=-1 || linkxem.indexOf("rtsp://")!=-1) {
var play = '<EMBED EnableContextMenu="0" type="application/x-mplayer2" SRC="'+linkxem+'" pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/" showstatusbar="1" width="100%" height="100%"/>';
}
else {
var play='<div style="text-align:center;margin-top:30px;"><b>Rất tiếc, Server bạn chọn bị lỗi! Vui lòng chọn Server khác!</b><br><img src="https://123tivi.googlecode.com/svn/trunk/123tv/alert.png" width="300" height="250px"/></div>';
}
document.getElementById("HMPlayers").innerHTML = '<div id="HMPlayer">'+play+'</div>';
}
var a = document.getElementById("Blog1").innerHTML;
var a=a.replace(/\[m\]/gi,"<span style='display:none;' id='linkxem'>");
var a=a.replace(/\[\/m\]/gi,"</span>");
var a=a.replace(/\[st\]/gi,"<span style='display:none;'>");
var a=a.replace(/\[\/st\]/gi,"</span>");
document.getElementById("Blog1").innerHTML =a;
var b=document.getElementById('linkxem').innerHTML;
var h = b.split("|");
var l = h.length;
var link = location.href;
if (link.indexOf("?p=")!=-1) {
var ser = link.substring(link.indexOf("?p=")+3,link.indexOf("?p=")+4);
if (ser=="") {
hm_play(h[0]);
}
else {
if (h[ser]===undefined || h[ser]==""){
document.getElementById("HMPlayers").innerHTML = '<div id="HMPlayer"><div style="text-align:center;margin-top:30px;"><b>Server không tồn tại! Xin vui lòng chọn server khác!</b><br><img src="https://123tivi.googlecode.com/svn/trunk/123tv/alert.png" width="300" height="250px"/></div></div>';
}
else {
hm_play(h[ser]);
}
}
} else {
hm_play(h[0]);
}
document.write ('<div id="list_ser" style="display:none;">');
for (i=0;i<l;i++) {
var k= i+1;
if (h[i]!="") {
if (i==0) {
var server = '<a id="ser_'+i+'" href="?p='+i+'" class="selected">'+k+'</a>';
}
else {
var server = '<a id="ser_'+i+'" href="?p='+i+'">'+k+'</a>';
}
document.write (server);
}
}
document.write ('</div>');
if (link.indexOf("?p=")!=-1) {
if (ser!="" && ser!="0") {
if (h[ser]===undefined) {
$('#ser_0').removeClass('selected');
}
else {
$('#ser_0').removeClass('selected');
$('#ser_'+ser).addClass('selected');
}
}
}
var list_server = document.getElementById("list_ser").innerHTML;
document.getElementById("list_server").innerHTML = '<span style="float:left;margin-right:5px;font-size:14px;font-weight:bold;">Server: </span>'+list_server;
if (link.indexOf("?p=")==-1) {
$("#ser_0").removeAttr("href");
}
else {
if (ser=="" || ser=="0") {
$("#ser_0").removeAttr("href");
}
else {
$('#ser_'+ser).removeAttr("href");
}
} | 123tivi | trunk/123tv/zi.js | JavaScript | oos | 5,387 |
var titles=new Array();var titlesNum=0;var urls=new Array();var time=new Array();var titleh=new Array();
function related_results_labels(c){
for(var b=0;b<c.feed.entry.length;b++){
var d=c.feed.entry[b];
titles[titlesNum]=d.title.$t;
s=d.content.$t;
titleh[titlesNum]=s.substring(s.indexOf("[st]")+4,s.indexOf("[/st]"));
for(var a=0;a<d.link.length;a++){
if(d.link[a].rel=="alternate"){
urls[titlesNum]=d.link[a].href;
time[titlesNum]=d.published.$t;
titlesNum++;break}}}}
function removeRelatedDuplicates(){
var b=new Array(0);
var c=new Array(0);
var m=new Array(0);
e=new Array(0);
for(var a=0;a<urls.length;a++){
if(!contains(b,urls[a])){
b.length+=1;
b[b.length-1]=urls[a];
m.length+=1;
m[m.length-1]=titleh[a];
c.length+=1;
c[c.length-1]=titles[a];
e.length+=1;
e[e.length-1]=time[a];
}
}
titles=c;
urls=b;time=e;titleh=m;
}
function contains(b,d){
for(var c=0;c<b.length;c++){if(b[c]==d){return true}}return false}
function printRelatedLabels(a){
var y=a.indexOf('?m=0');
if(y!=-1){a=a.replace(/\?m=0/g,'')}
for(var b=0;b<urls.length;b++){
if(urls[b]==a){
urls.splice(b,1);
titles.splice(b,1);
titleh.splice(b,1);
time.splice(b,1)}}
var c=Math.floor((titles.length-1)*Math.random());
var b=0;
if(titles.length==0){document.write("<li>Không có bài viết liên quan</li>")}
else{
while(b<titles.length&&b<20&&b<maxresults){
if(y!=-1){
urls[c]=urls[c]+'?m=0'
}
document.write('<a href="'+urls[c]+'" title="'+titles[c]+'">'+titleh[c]+"</a>");
if(c<titles.length-1){c++}
else{c=0}b++
}
}
urls.splice(0,urls.length);titles.splice(0,titles.length)};
| 123tivi | trunk/123tv/lienquan1.js | JavaScript | oos | 1,617 |
imgr = new Array();
imgr[0] = "https://lh3.googleusercontent.com/-IBkOgk0LW6c/TqulPrgd6RI/AAAAAAAAAmg/VHnAiJCR4jc/s800/no_img.jpg";
showRandomImg = true;
aBold = true;
summaryPost = 70;
summaryTitle = 25;
numposts = 100;
function removeHtmlTag(strx,chop){
var s = strx.split("<");
for(var i=0;i<s.length;i++){
if(s[i].indexOf(">")!=-1){
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
s = s.join("");
s = s.substring(0,chop-1);
return s;
}
function gettv(json) {
j = (showRandomImg) ? Math.floor((imgr.length+1)*Math.random()) : 0;
img = new Array();
if (numposts <= json.feed.entry.length) {
maxpost = numposts;
}
else
{
maxpost=json.feed.entry.length;
}
for (var i = 0; i < maxpost; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var pcm;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') {
pcm = entry.link[k].title.split(" ")[0];
break;
}
}
if ("content" in entry) {
var postcontent = entry.content.$t;}
else
if ("summary" in entry) {
var postcontent = entry.summary.$t;}
else var postcontent = "";
postdate = entry.published.$t;
if(j>imgr.length-1) j=0;
img[i] = imgr[j];
s = postcontent ; a = s.indexOf("<img"); b = s.indexOf("src=\"",a); c = s.indexOf("\"",b+5); d = s.substr(b+5,c-b-5);
if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")) img[i] = d;
//cmtext = (text != 'no') ? '<i><font color="'+acolor+'">('+pcm+' '+text+')</font></i>' : '';
var month = [1,2,3,4,5,6,7,8,9,10,11,12];
var month2 = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var day = postdate.split("-")[2].substring(0,2);
var m = postdate.split("-")[1];
var y = postdate.split("-")[0];
for(var u2=0;u2<month.length;u2++){
if(parseInt(m)==month[u2]) {
m = month2[u2] ; break;
}
}
var daystr = day+ ' ' + m + ' ' + y ;
if (i>=0 && i <=32) {
var trtd = '<div class="gettv"><a rel="'+posttitle+'" href="'+posturl+'" style="font-weight:bold;"><img alt="'+posttitle+'" style="border:1px solid #CBCBCB;width:116px;height:130px;padding: 5px;background: transparent;" src="'+img[i]+'"/></a><br/><span style="color: #06C;font-size: 12px;font-weight: bold;">'+s+'</span><a rel="'+posttitle+'" href="'+posturl+'" style="font-weight:bold;">'+posttitle+'</a></div>';
document.write(trtd);
}
j++;
}
document.write('<div style="clear: both;"></div>');
} | 123tivi | trunk/kien/feed.js | JavaScript | oos | 2,780 |
imgr = new Array();
imgr[0] = "https://lh3.googleusercontent.com/-IBkOgk0LW6c/TqulPrgd6RI/AAAAAAAAAmg/VHnAiJCR4jc/s800/no_img.jpg";
showRandomImg = true;
aBold = true;
summaryPost = 70;
summaryTitle = 25;
numposts = 100;
function removeHtmlTag(strx,chop){
var s = strx.split("<");
for(var i=0;i<s.length;i++){
if(s[i].indexOf(">")!=-1){
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
s = s.join("");
s = s.substring(0,chop-1);
return s;
}
function gettv(json) {
j = (showRandomImg) ? Math.floor((imgr.length+1)*Math.random()) : 0;
img = new Array();
if (numposts <= json.feed.entry.length) {
maxpost = numposts;
}
else
{
maxpost=json.feed.entry.length;
}
for (var i = 0; i < maxpost; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var pcm;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') {
pcm = entry.link[k].title.split(" ")[0];
break;
}
}
if ("content" in entry) {
var postcontent = entry.content.$t;}
else
if ("summary" in entry) {
var postcontent = entry.summary.$t;}
else var postcontent = "";
postdate = entry.published.$t;
if(j>imgr.length-1) j=0;
img[i] = imgr[j];
s = postcontent ; a = s.indexOf("<img"); b = s.indexOf("src=\"",a); c = s.indexOf("\"",b+5); d = s.substr(b+5,c-b-5);
if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")) img[i] = d;
//cmtext = (text != 'no') ? '<i><font color="'+acolor+'">('+pcm+' '+text+')</font></i>' : '';
var month = [1,2,3,4,5,6,7,8,9,10,11,12];
var month2 = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var day = postdate.split("-")[2].substring(0,2);
var m = postdate.split("-")[1];
var y = postdate.split("-")[0];
for(var u2=0;u2<month.length;u2++){
if(parseInt(m)==month[u2]) {
m = month2[u2] ; break;
}
}
var daystr = day+ ' ' + m + ' ' + y ;
if (i>=0 && i <=32) {
var trtd = '<div class="gettv"><a rel="'+posttitle+'" href="'+posturl+'" style="font-weight:bold;"><img alt="'+posttitle+'" style="border:1px solid #CBCBCB;width:116px;height:130px;padding: 5px;background: transparent;" src="'+img[i]+'"/></a><br/><a rel="'+posttitle+'" href="'+posturl+'" style="font-weight:bold;">'+posttitle+'</a></div>';
document.write(trtd);
}
j++;
}
document.write('<div style="clear: both;"></div>');
} | 123tivi | trunk/kien/feedold.js | JavaScript | oos | 2,707 |
function postlabel(json) {
for (var i = 0; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var posturl;if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length;k++){
if(entry.link[k].rel=='replies'&&entry.link[k].type=='text/html'){
var commenttext=entry.link[k].title;
var commenturl=entry.link[k].href;
}
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;break;
}
}
if("content"in entry){
var postcontent=entry.content.$t;
}
var vidid = postcontent.substring(postcontent.indexOf("http://www.youtube.com/watch?v=")+31,postcontent.indexOf("endofvid"));
try {thumburl='http://i2.ytimg.com/vi/'+vidid+'/default.jpg';}catch (error){
thumburl='http://1.bp.blogspot.com/_u4gySN2ZgqE/SmWGbEU9sgI/AAAAAAAAAhc/1C_WxeHhfoA/s800/noimagethumb.png';
}
var postdate = entry.published.$t;
var cdyear = postdate.substring(0,4);
var cdmonth = postdate.substring(5,7);
var cdday = postdate.substring(8,10);
var monthnames = new Array();
monthnames[1] = "Jan";monthnames[2] = "Feb";monthnames[3] = "Mar";monthnames[4] = "Apr";monthnames[5] = "May";monthnames[6] = "Jun";monthnames[7] = "Jul";monthnames[8] = "Aug";monthnames[9] = "Sep";monthnames[10] = "Oct";monthnames[11] = "Nov";monthnames[12] = "Dec";
document.write('<div class="content-item"><a href="'+ posturl + '" class="video-img" title="'+posttitle+'"><img width="128px" height="72px" src="'+thumburl+'"/></a><div class="meta"><a title="'+posttitle+'" href="'+posturl+'" target ="_top">'+posttitle+'</a></div></div>');
}
} | 123tivi | trunk/thugian123/feed.js | JavaScript | oos | 1,653 |
using System;
using System.Collections.Generic;
using System.Text;
using Cores;
using DAOLayer;
using System.Data;
namespace BUSLayer
{
public class DatVeBus
{
private DatVeDao _dvDAO;
public DatVeDao DvDAO
{
get { return _dvDAO; }
set { _dvDAO = value; }
}
public DatVeBus()
{
DvDAO = new DatVeDao();
}
public void Xoa(int MaVe, int MaKH)
{
DvDAO.Xoa(MaVe, MaKH);
}
}
}
| 07hc114 | trunk/RapPhimRollRoyce/BUSLayer/DatVeBus.cs | C# | gpl2 | 541 |
using System;
using System.Collections.Generic;
using System.Text;
using Cores;
using DAOLayer;
using System.Data;
namespace BUSLayer
{
public class PhimBus
{
private PhimDao _phimDAO;
public PhimDao PhimDAO
{
get { return _phimDAO; }
set { _phimDAO = value; }
}
public PhimBus()
{
PhimDAO = new PhimDao();
}
~PhimBus()
{ }
public DataTable LayThongTinPhim(int maso)
{
PhimDAO.Conn.Connect();
return PhimDAO.LayThongTinPhim(maso);
}
public DataTable LayDsDienVienTrongPhim(int maso)
{
PhimDAO.Conn.Connect();
return PhimDAO.LayDsDienVienTrongPhim(maso);
}
public DataTable LayDsDaoDienTrongPhim(int maso)
{
PhimDAO.Conn.Connect();
return PhimDAO.LayDsDaoDienTrongPhim(maso);
}
public DataTable DSPhimTheoDV(string TenDV)
{
return PhimDAO.DanhSachPhimTheoDienVien(TenDV);
}
public DataTable LayDSPhim()
{
DateTime dt = DateTime.Now;
DayOfWeek firstday = DayOfWeek.Monday;
DayOfWeek today = dt.DayOfWeek;
int Fdiff = 0;
if (today == DayOfWeek.Sunday)
Fdiff = 6;
else
Fdiff = today - firstday;
DateTime NgayDT = dt.AddDays(-Fdiff);
PhimDAO = new PhimDao();
return PhimDAO.LayDSPhim(NgayDT);
}
}
}
| 07hc114 | trunk/RapPhimRollRoyce/BUSLayer/PhimBus.cs | C# | gpl2 | 1,647 |
using System;
using System.Collections.Generic;
using System.Text;
using Cores;
using DAOLayer;
using System.Data;
namespace BUSLayer
{
public class KhachHangBus
{
KhachHangDao KHdao;
public int LayMaKH(int MaTK)
{
KHdao = new KhachHangDao();
int kq = KHdao.LayMaKhachHang(MaTK);
return kq;
}
}
}
| 07hc114 | trunk/RapPhimRollRoyce/BUSLayer/KhachHangBus.cs | C# | gpl2 | 399 |
using System;
using System.Collections.Generic;
using System.Text;
using Cores;
using DAOLayer;
using System.Data;
namespace BUSLayer
{
public class TaiKhoanBus
{
TaiKhoanDao TKdao;
public static string Encrypte(string inputString)
{
return TaiKhoanDao.Encrypte(inputString);
}
public int KTUser(string username, string password)
{
if (username == "" || password =="")
return 0;
TKdao = new TaiKhoanDao();
return TKdao.KTUser(username, password);
}
public int LayMaTK(string username, string password)
{
TKdao = new TaiKhoanDao();
int kq = TKdao.LayMaTaiKhoan(username, password);
return kq;
}
}
}
| 07hc114 | trunk/RapPhimRollRoyce/BUSLayer/TaiKhoanBus.cs | C# | gpl2 | 824 |
using System;
using System.Collections.Generic;
using System.Text;
using Cores;
using DAOLayer;
using System.Data;
namespace BUSLayer
{
public class LichChieuBus
{
LichChieuDao LCdao;
public DataTable LayLichChieu(int maphim)
{
DateTime dt = DateTime.Now;
DayOfWeek firstday = DayOfWeek.Monday;
DayOfWeek today = dt.DayOfWeek;
int Fdiff = 0;
if (today == DayOfWeek.Sunday)
Fdiff = 6;
else
Fdiff = today - firstday;
DateTime NgayBD = dt.AddDays(-Fdiff);
DateTime NgayKT = NgayBD.AddDays(14);
LCdao = new LichChieuDao();
return LCdao.LayLichChieu(maphim, NgayBD, NgayKT);
}
}
}
| 07hc114 | trunk/RapPhimRollRoyce/BUSLayer/LichChieuBus.cs | C# | gpl2 | 812 |
using System;
using System.Collections.Generic;
using System.Text;
using Cores;
using DAOLayer;
using System.Data;
namespace BUSLayer
{
public class VeBus
{
private VeDao _veDAO;
public VeDao VeDAO
{
get { return _veDAO; }
set { _veDAO = value; }
}
public VeBus()
{
VeDAO = new VeDao();
}
public DataTable DanhSachVe(int MaKH)
{
return VeDAO.DanhSachVe(MaKH);
}
}
}
| 07hc114 | trunk/RapPhimRollRoyce/BUSLayer/VeBus.cs | C# | gpl2 | 536 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BUSLayer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BUSLayer")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5d6b7ec1-e94f-4e86-84b1-6ea001e8ab65")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 07hc114 | trunk/RapPhimRollRoyce/BUSLayer/Properties/AssemblyInfo.cs | C# | gpl2 | 1,387 |
using System;
using System.Collections.Generic;
using System.Text;
using Cores;
using DAOLayer;
using System.Data;
namespace BUSLayer
{
public class DienVienBus
{
DienVienDao DVdao = new DienVienDao();
public DataTable DanhSachDV()
{
return DVdao.DanhSachDienVien();
}
public DataTable DSDienVienTheoTen(string TenDV)
{
return DVdao.DanhSachDienVienTheoTen(TenDV);
}
}
}
| 07hc114 | trunk/RapPhimRollRoyce/BUSLayer/DienVienBus.cs | C# | gpl2 | 487 |
using System;
using System.Collections.Generic;
using System.Text;
using Cores;
using System.Security.Cryptography;
using System.Data;
using System.Data.SqlClient;
namespace DAOLayer
{
public class TaiKhoanDao
{
private Connection _conn;
public Connection Conn
{
get { return _conn; }
set { _conn = value; }
}
public TaiKhoanDao()
{
Conn = new Connection();
if (Conn.Connect().State == ConnectionState.Closed)
{
Conn.ConnObj.Open();
}
}
~TaiKhoanDao()
{
return;
}
public int KTUser(string username, string password)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn.ConnObj;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select dbo.fLayMaKH(@UserName,@Password)";
cmd.Parameters.AddWithValue("@UserName", username);
cmd.Parameters.AddWithValue("@Password", password);
SqlDataReader rd = cmd.ExecuteReader();
int result = 0;
if (rd.Read())
result = rd.GetInt32(0);
rd.Close();
Conn.Disconnect();
return result;
}
public static int KiemTraQuyenDangNhap(string userName)
{
TaiKhoanDao tk = new TaiKhoanDao();
Connection conn = tk.Conn;
if (conn.ConnObj.State == ConnectionState.Closed)
{
conn.ConnObj.Open();
}
SqlCommand cmd = new SqlCommand("spLayQuyenDangNhap", conn.ConnObj);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserName", userName);
int res = 0;
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
res = rd.GetInt32(0);
}
rd.Close();
conn.Disconnect();
return res;
}
public static string Encrypte(string inputString)
{
UTF32Encoding u = new UTF32Encoding();
byte[] bytes = u.GetBytes(inputString);
MD5 md = new MD5CryptoServiceProvider();
byte[] result = md.ComputeHash(bytes);
return Convert.ToBase64String(result);
}
public int LayMaTaiKhoan(string username, string password)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn.ConnObj;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select dbo.fTimKiemTaiKhoanKH(@UserName,@Password)";
cmd.Parameters.AddWithValue("@UserName", username);
cmd.Parameters.AddWithValue("@Password", password);
SqlDataReader rd = cmd.ExecuteReader();
int result = 0;
if (rd.Read())
result = rd.GetInt32(0);
rd.Close();
Conn.Disconnect();
return result;
}
}
}
| 07hc114 | trunk/RapPhimRollRoyce/DAOLayer/TaiKhoanDao.cs | C# | gpl2 | 3,175 |