--- /dev/null
- /**
- * This API sets the error code for this response
- *
- * @param eCode error code to set
- */
- public native void setErrorCode(int eCode);
-
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base;
+
+import java.util.List;
+
+/**
+ * OcResourceResponse provides APIs to set the response details
+ */
+public class OcResourceResponse {
+
+ static {
+ System.loadLibrary("oc");
+ System.loadLibrary("ocstack-jni");
+ }
+
+ public OcResourceResponse() {
+ super();
+
+ create();
+ }
+
+ private OcResourceResponse(long nativeHandle) {
+ this.mNativeHandle = nativeHandle;
+ }
+
+ /**
+ * Gets new resource uri
+ *
+ * @return new resource uri
+ */
+ public native String getNewResourceUri();
+
+ /**
+ * Sets new resource uri
+ *
+ * @param newResourceUri new resource uri
+ */
+ public native void setNewResourceUri(String newResourceUri);
+
+ /**
+ * This API allows to set headerOptions in the response
+ *
+ * @param headerOptionList List of HeaderOption entries
+ */
+ public void setHeaderOptions(List<OcHeaderOption> headerOptionList) {
+ this.setHeaderOptions(headerOptionList.toArray(
+ new OcHeaderOption[headerOptionList.size()])
+ );
+ }
+
+ private native void setHeaderOptions(OcHeaderOption[] headerOptionList);
+
+ /**
+ * This API allows to set request handle
+ *
+ * @param ocRequestHandle request handle
+ */
+ public native void setRequestHandle(OcRequestHandle ocRequestHandle);
+
+ /**
+ * This API allows to set the resource handle
+ *
+ * @param ocResourceHandle resource handle
+ */
+ public native void setResourceHandle(OcResourceHandle ocResourceHandle);
+
+ /**
+ * This API allows to set the EntityHandler response result
+ *
+ * @param responseResult OcEntityHandlerResult type to set the result value
+ */
+ public void setResponseResult(EntityHandlerResult responseResult) {
+ this.setResponseResult(responseResult.getValue());
+ }
+
+ private native void setResponseResult(int responseResult);
+
+ /**
+ * API to set the entire resource attribute representation
+ *
+ * @param ocRepresentation the name value pairs representing the resource's attributes
+ * @param interfaceStr specifies the interface
+ */
+ public native void setResourceRepresentation(OcRepresentation ocRepresentation,
+ String interfaceStr);
+
+ /**
+ * API to set the entire resource attribute representation
+ *
+ * @param representation object containing the name value pairs representing the
+ * resource's attributes
+ */
+ public void setResourceRepresentation(OcRepresentation representation) {
+ this.setResourceRepresentation1(representation);
+ }
+
+ private native void setResourceRepresentation1(OcRepresentation representation);
+
+ @Override
+ protected void finalize() throws Throwable {
+ super.finalize();
+
+ dispose();
+ }
+
+ private native void create();
+
+ private native void dispose();
+
+ private long mNativeHandle;
+}
--- /dev/null
- response.setErrorCode(Resource.SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * DoorResource
+ * <p/>
+ * DoorResource is a sample OIC server resource created by the refrigerator.
+ */
+public class DoorResource extends Resource implements OcPlatform.EntityHandler {
+ DoorResource(String side, Context context) {
+ mContext = context;
+ mSide = side;
+
+ registerDoorResource();
+ }
+
+ private void registerDoorResource() {
+ String resourceURI = DOOR_URI + mSide;
+ logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
+ try {
+ mResourceHandle = OcPlatform.registerResource(
+ resourceURI,
+ RESOURCE_TYPEDOOR,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DoorResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * sample implementation of eventHandler for doorResource - this can be implemented in many
+ * different ways
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(
+ RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
- response.setErrorCode(Resource.SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case PUT:
- response.setErrorCode(204);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case DELETE:
+ response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DoorResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ /**
+ * helper function to update the current value of the door resource
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
+ mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
+ logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
+ " and door side is " + mSide);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of doorResource, depending on if door is open/ closed
+ *
+ * @param representation new state of a door
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mDoorState = representation.getValue(DOOR_STATE_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ // Note, we won't let the user change the door side!
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private String mSide;
+ private boolean mDoorState;
+ public static final String DOOR_URI = "/door/";
+ public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
+ private static String TAG = "DoorResource: ";
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra(Resource.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
- response.setErrorCode(Resource.SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+
+/**
+ * LightResource
+ * <p/>
+ * LightResource is a sample OIC server resource created by the refrigerator.
+ */
+public class LightResource extends Resource implements OcPlatform.EntityHandler {
+ LightResource(Context context) {
+ mContext = context;
+
+ registerLightResource();
+ }
+
+ private void registerLightResource() {
+ try {
+ logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
+ mResourceHandle = OcPlatform.registerResource(
+ LIGHT_URI,
+ RESOURCE_TYPELIGHT,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register LightResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * sample implementation of eventHandler for lightResource - this can be implemented in many
+ * different ways
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(
+ RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
- response.setErrorCode(Resource.SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ case PUT:
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ }
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ /**
+ * update the value of light (ON/ OFF) from the representation
+ *
+ * @param representation new state of light
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * helper function to update the current state of the light
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private boolean mIsLightOn = false;
+
+ private static String TAG = "LightResource: ";
+ public static final String LIGHT_URI = "/light";
+ public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
+ public static final String LIGHT_STATUS_KEY = "light";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra(Resource.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
- response.setErrorCode(SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * DeviceResource
+ * <p/>
+ * Creates a device resource and performs action based on client requests
+ */
+public class DeviceResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String DEVICE_URI = "/device";
+ public static final String RESOURCE_TYPENAME = "intel.fridge";
+ public static final String API_VERSION = "v.1.0";
+ public static final String CLIENT_TOKEN = "21ae43gf";
+ public static final String DEVICE_NAME = "device_name";
+ private static String TAG = "DeviceResource: ";
+ public static final int SUCCESS = 200;
+ public static final int API_VERSION_KEY = 2048;
+ public static final int CLIENT_VERSION_KEY = 3000;
+
+ private Context mContext;
+
+ /**
+ * constructor
+ *
+ * @param context to enable sending of broadcast messages to be displayed on the user screen
+ */
+ DeviceResource(Context context) {
+ mContext = context;
+ registerDeviceResource();
+ }
+
+ private void registerDeviceResource() {
+ try {
+ logMessage("RegisterDeviceResource " + DEVICE_URI + " : " + RESOURCE_TYPENAME);
+ mResourceHandle = OcPlatform.registerResource(
+ DEVICE_URI,
+ RESOURCE_TYPENAME,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DeviceResource");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * this is the main method which handles different incoming requests appropriately.
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ List<OcHeaderOption> headerOptions = ocResourceRequest.getHeaderOptions();
+ String clientAPIVersion = "";
+ String clientToken = "";
+ // search for header options map and look for API version and client token
+ for (OcHeaderOption headerOption : headerOptions) {
+ int optionId = headerOption.getOptionId();
+ if (API_VERSION_KEY == optionId) {
+ clientAPIVersion = headerOption.getOptionData();
+ logMessage(TAG + " Client API Version: " + clientAPIVersion);
+ } else if (CLIENT_VERSION_KEY == optionId) {
+ clientToken = headerOption.getOptionData();
+ logMessage(TAG + " Client Token: " + clientToken);
+ }
+ }
+ if (clientAPIVersion.equals(API_VERSION) &&
+ clientToken.equals(CLIENT_TOKEN)) {
+ List<OcHeaderOption> serverHeaderOptions = new LinkedList<>();
+ OcHeaderOption apiVersion = new OcHeaderOption(API_VERSION_KEY,
+ API_VERSION);
+ serverHeaderOptions.add(apiVersion);
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+ response.setHeaderOptions(serverHeaderOptions);
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
+ response.setResponseResult(EntityHandlerResult.OK);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DeviceResource");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ /**
+ * update state of device
+ *
+ * @return device representation
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DEVICE_NAME,
+ "Intel Powered 3 door, 1 light refrigerator");
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra("message", msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
- response.setErrorCode(SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * DoorResource
+ * <p/>
+ * Creates a door resource and performs actions based on the client requests
+ */
+public class DoorResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String DOOR_URI = "/door/";
+ public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+ private boolean mDoorState;
+ private String mSide;
+
+ /**
+ * Constructor
+ *
+ * @param side side of the door
+ * @param context to enable sending of broadcast messages to be displayed on the user screen
+ */
+ DoorResource(String side, Context context) {
+ mContext = context;
+ mSide = side;
+ registerDoorResource();
+ }
+
+ private void registerDoorResource() {
+ String resourceURI = DOOR_URI + mSide;
+ logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
+ try {
+ mResourceHandle = OcPlatform.registerResource(resourceURI,
+ RESOURCE_TYPEDOOR,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DoorResource");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * this is the main method which handles different incoming requests appropriately.
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
- response.setErrorCode(SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case PUT:
- response.setErrorCode(204);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case DELETE:
+ response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DoorResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ /**
+ * helper function to update the current value of the door resource
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
+ mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
+ logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
+ " and door side is " + mSide);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of doorResource, depending on if door is open/ closed
+ *
+ * @param representation new state of a door
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mDoorState = representation.getValue(DOOR_STATE_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ // Note, we won't let the user change the door side!
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private static String TAG = "DoorResource: ";
+
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra(FridgeServer.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
- response.setErrorCode(SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * LightResource
+ * <p/>
+ * Creates a light resource and performs actions based on the client requests
+ */
+public class LightResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String LIGHT_STATUS_KEY = "light";
+ public static final String LIGHT_URI = "/light";
+ public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
+ private boolean mIsLightOn = false;
+
+ /**
+ * constructor
+ *
+ * @param context to enable sending of broadcast messages to be displayed on the user screen
+ */
+ LightResource(Context context) {
+ mContext = context;
+ registerLightResource();
+ }
+
+ private void registerLightResource() {
+ try {
+ logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
+ mResourceHandle = OcPlatform.registerResource(LIGHT_URI,
+ RESOURCE_TYPELIGHT,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register LightResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * this is the main method which handles different incoming requests appropriately.
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
- response.setErrorCode(SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ case PUT:
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ }
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of LightResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ /**
+ * updates the current state of the light (on/ off)
+ *
+ * @return light is on or off
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of mIsOn from the representation
+ *
+ * @param representation get current state of light
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private static String TAG = "LightResource: ";
+
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra(FridgeServer.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.CompoundButton;
+import android.widget.ScrollView;
+import android.widget.TextView;
+import android.widget.ToggleButton;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcPresenceHandle;
+import org.iotivity.base.OcPresenceStatus;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+
+/**
+ * A client example for presence notification
+ */
+public class PresenceClient extends Activity implements
+ OcPlatform.OnResourceFoundListener,
+ OcPlatform.OnPresenceListener {
+ private final static String TAG = PresenceClient.class.getSimpleName();
+ private OcResource mResource;
+ private OcPresenceHandle mPresenceHandle;
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ private void startPresenceClient() {
+ Context context = this;
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ context,
+ ServiceType.IN_PROC,
+ ModeType.CLIENT,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ QualityOfService.LOW
+ );
+
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+
++ try {
++ msg("Subscribing to multicast presence");
++ OcPlatform.subscribePresence(OcPlatform.PRESENCE_URI,
++ EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
++ } catch (OcException e) {
++ Log.e(TAG, e.toString());
++ msg("Failed to subscribe to multicast presence");
++ }
++
+ try {
+ msg("Finding Resource...");
+ OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to find resource(s). ");
+ }
+ printLine();
+ enableStartStopButton();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ @Override
+ public synchronized void onResourceFound(OcResource foundResource) {
+ String resourceUri = foundResource.getUri();
+ if (null != mResource || !resourceUri.equals("/a/light")) {
+ msg("Found resource, ignoring");
+ return;
+ }
+
+ msg("Found Resource");
+ String hostAddress = foundResource.getHost();
+ msg("\tResource URI : " + resourceUri);
+ msg("\tResource Host : " + hostAddress);
+ msg("\tResource Interfaces : ");
+ for (String resInterface : foundResource.getResourceInterfaces()) {
+ msg("\t\t" + resInterface);
+ }
+ msg("\tResource Type : ");
+ for (String resTypes : foundResource.getResourceTypes()) {
+ msg("\t\t" + resTypes);
+ }
+
+ try {
+ msg("Subscribing to unicast address:" + hostAddress);
+ OcPlatform.subscribePresence(hostAddress,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to subscribe to unicast address:" + hostAddress);
+ }
+ mResource = foundResource;
+ printLine();
+ }
+
+ @Override
+ public synchronized void onFindResourceFailed(Throwable throwable, String uri) {
+ msg("findResource request has failed");
+ Log.e(TAG, throwable.toString());
+ }
+
+ @Override
+ public void onPresence(OcPresenceStatus ocPresenceStatus, int nonce, String hostAddress) {
+ msg("Received presence notification from : " + hostAddress);
+ switch (ocPresenceStatus) {
+ case OK:
+ msg("Nonce# " + nonce);
+ break;
+ case STOPPED:
+ msg("Presence Stopped");
+ break;
+ case TIMEOUT:
+ msg("Presence Timeout");
+ break;
+ case DO_NOT_HANDLE:
+ msg("Presence Do Not Handle");
+ break;
+ }
+ }
+
+ private void stopPresenceClient() {
+ if (null != mPresenceHandle) {
+ try {
+ msg("Unsubscribing from the presence notifications.");
+ OcPlatform.unsubscribePresence(mPresenceHandle);
+ mPresenceHandle = null;
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to unsubscribe from the presence notifications" + e.toString());
+ }
+ }
+ mResource = null;
+ printLine();
+ enableStartStopButton();
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_presence_client);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+
+ if (null == savedInstanceState) {
+ toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ toggleButton.setEnabled(false);
+ if (isChecked) {
+ new Thread(new Runnable() {
+ public void run() {
+ startPresenceClient();
+ }
+ }).start();
+ } else {
+ new Thread(new Runnable() {
+ public void run() {
+ stopPresenceClient();
+ }
+ }).start();
+ }
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+
+ private void msg(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+
+ private void enableStartStopButton() {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ toggleButton.setEnabled(true);
+ }
+ });
+ }
+}
--- /dev/null
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.CompoundButton;
+import android.widget.ScrollView;
+import android.widget.TextView;
+import android.widget.ToggleButton;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ResourceProperty;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+
+/**
+ * A server example for presence notification
+ */
+public class PresenceServer extends Activity {
+ private OcResourceHandle mResourceHandle;
++ private int mPresenceCount = 0;
++ private final int mMaxCount = 10;
+
+ private void startPresenceServer() {
+ Context context = this;
+
+ PlatformConfig platformConfig = new PlatformConfig(
+ context,
+ ServiceType.IN_PROC,
+ ModeType.SERVER,
+ "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+ 0, // Uses randomly available port
+ QualityOfService.LOW
+ );
+
+ msg("Configuring platform.");
+ OcPlatform.Configure(platformConfig);
+
+ try {
+ msg("Creating resource of type \"core.light\".");
+ createResource();
+ sleep(1);
+
+ msg("Starting presence notifications.");
+ OcPlatform.startPresence(OcPlatform.DEFAULT_PRESENCE_TTL);
+ sleep(1);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Error: " + e.toString());
+ }
+ printLine();
+ enableStartStopButton();
+ }
+
++ private void startPresence()
++ {
++ try {
++ msg("Starting presence notifications (" + mPresenceCount + " / " + mMaxCount + ")");
++ OcPlatform.startPresence(OcPlatform.DEFAULT_PRESENCE_TTL);
++ sleep(3);
++ } catch (OcException e) {
++ Log.e(TAG, e.toString());
++ msg("Error: " + e.toString());
++ }
++ }
++
+ /**
+ * This function internally calls registerResource API.
+ */
+ private void createResource() {
+ String resourceUri = "/a/light"; // URI of the resource
+ String resourceTypeName = "core.light"; // resource type name.
+ String resourceInterface = OcPlatform.DEFAULT_INTERFACE; // resource interface.
+
+ try {
+ // This will internally create and register the resource.
+ mResourceHandle = OcPlatform.registerResource(
+ resourceUri,
+ resourceTypeName,
+ resourceInterface,
+ null, //Use default entity handler
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ msg("Resource creation was unsuccessful.");
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void stopPresenceServer() {
+ try {
+ msg("Stopping presence notifications.");
+ OcPlatform.stopPresence();
+
+ msg("Unregister resource.");
+ if (null != mResourceHandle) OcPlatform.unregisterResource(mResourceHandle);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Error: " + e.toString());
+ }
+
+ printLine();
+ enableStartStopButton();
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ private final static String TAG = PresenceServer.class.getSimpleName();
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_presence_server);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+
+ if (null == savedInstanceState) {
+ toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+ toggleButton.setEnabled(false);
+ if (isChecked) {
+ new Thread(new Runnable() {
+ public void run() {
+ startPresenceServer();
++
++ mPresenceCount = 0;
++ while(mPresenceCount++ < mMaxCount)
++ {
++ startPresence();
++ }
++ stopPresenceServer();
+ }
+ }).start();
+ } else {
+ new Thread(new Runnable() {
+ public void run() {
++ mPresenceCount = 10;
+ stopPresenceServer();
+ }
+ }).start();
+ }
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ outState.putBoolean("toggleButtonChecked", toggleButton.isChecked());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+
+ final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ boolean buttonCheked = savedInstanceState.getBoolean("toggleButtonChecked");
+ toggleButton.setChecked(buttonCheked);
+ }
+
+ private void msg(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private void printLine() {
+ msg("------------------------------------------------------------------------");
+ }
+
+ private void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void enableStartStopButton() {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
+ toggleButton.setEnabled(true);
+ }
+ });
+ }
+}
--- /dev/null
- private final Pattern ADDRESS_PORT
- = Pattern.compile(
- "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])" +
- "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)" +
- "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)" +
- "\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])" +
- ":([0-9]{1,5}))");
+/*
+ * ******************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Fragment;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
++import android.util.Patterns;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.LinearLayout;
++import android.widget.RadioButton;
++import android.widget.RadioGroup;
+import android.widget.ScrollView;
+import android.widget.Switch;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import org.iotivity.base.AclGroupType;
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.ModeType;
+import org.iotivity.base.ObserveType;
+import org.iotivity.base.OcAccountManager;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcPresenceHandle;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+import org.iotivity.base.ResourceProperty;
+import org.iotivity.base.ServiceType;
+
++import java.net.InetAddress;
++import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+/**
+ * This class is for messaging between the cloud server and the client.
+ * It can handle cloud API manually.
+ */
+public class CloudFragment extends Fragment implements
+ View.OnClickListener, CompoundButton.OnCheckedChangeListener,
+ OcResource.OnObserveListener,
+ OcResource.OnMQTopicFoundListener, OcResource.OnMQTopicCreatedListener,
+ OcResource.OnMQTopicSubscribeListener,
+ OcPlatform.EntityHandler {
+
+ private static final String TAG = "OIC_SIMPLE_CLOUD";
+ private final String EOL = System.getProperties().getProperty("line.separator");
- response.setErrorCode(Common.SUCCESS);
++ private final Pattern PORT_NUMBER = Pattern.compile("(\\d{1,5})");
+
+ private Activity mActivity;
+ private Context mContext;
+
+ private QualityOfService mQos = QualityOfService.LOW;
+ private boolean mSecured = false;
+
+ private LinearLayout mAccountLayout;
+ private LinearLayout mRDLayout;
+ private LinearLayout mMQLayout;
+
+ private TextView mAccountText;
+ private TextView mRDText;
+ private TextView mMQText;
+ private ScrollView mScrollView;
+ private TextView mActionLog;
+ private TextView mResultLog;
+
+ private OcAccountManager mAccountManager;
+ private String mAccessToken;
+ private String mRefreshToken;
+ private String mUserUuid;
+ private String mGroupId;
+ private String mGroupMasterId;
+ private String mInviterUserId;
+ private String mInviteeUuid;
+ private final int REQUEST_LOGIN = 1;
+
+ private OcResource mFoundResource = null;
+ private OcResourceHandle localLightResourceHandle = null;
+ private List<OcResourceHandle> mResourceHandleList = new LinkedList<>();
+ private OcPresenceHandle mOcPresenceHandle = null;
+ private Button mDevicePresenceButton;
+
+ private OcResource MQbrokerResource = null;
+ private OcResource currentTopicResource = null;
+ private boolean switchingFlag = true;
+ private int roomNum = 1;
+ private String defaultTopicFullName = Common.MQ_DEFAULT_TOPIC_URI;
+
+ // variables related observer
+ private int maxSequenceNumber = 0xFFFFFF;
+ private Thread mObserverNotifier;
+ private int mPower = 0; // light power
+ private boolean mState = false; // light state
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ mActivity = getActivity();
+ mContext = mActivity.getBaseContext();
+ initOcPlatform(ModeType.CLIENT_SERVER);
+ }
+
+ private void initOcPlatform(ModeType type) {
+ PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
+ ServiceType.IN_PROC,
+ type,
+ Common.IP_ADDRESS,
+ Common.IP_PORT,
+ mQos);
+ OcPlatform.Configure(cfg);
+ }
+
+ private void signUp() {
+ try {
+ mAccountManager = OcPlatform.constructAccountManagerObject(
+ Common.HOST,
+ EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP));
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+
+ Intent intentLogin = new Intent(mContext, LoginActivity.class);
+ startActivityForResult(intentLogin, REQUEST_LOGIN);
+ }
+
+ private void signIn() {
+ try {
+ msg("signIn");
+ mAccountManager.signIn(mUserUuid, mAccessToken, onSignIn);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void signOut() {
+ try {
+ msg("signOut");
+ mAccountManager.signOut(onSignOut);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void createGroup() {
+ try {
+ msg("createGroup");
+ mAccountManager.createGroup(AclGroupType.PUBLIC, onCreateGroup);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void inviteUser() {
+ if (mGroupId == null) {
+ msg("there is no any group");
+ } else {
+ showInviteUser();
+ }
+ }
+
+ private void leaveGroup() {
+ try {
+ if (mGroupId == null) {
+ msg("there is no any group");
+ } else {
+ msg("leaveGroup");
+ mAccountManager.leaveGroup(mGroupId, onLeaveGroup);
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ // FOR WEB-VIEW
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_LOGIN) {
+ String authCode = data.getStringExtra("authCode");
+ msg("\tauthCode: " + authCode);
+
+ try {
+ msg("Sign Up");
+ mAccountManager.signUp("github", authCode, onSignUp);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ OcAccountManager.OnPostListener onSignUp = new OcAccountManager.OnPostListener() {
+ @Override
+ public synchronized void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("signUp was successful");
+ try {
+ mUserUuid = ocRepresentation.getValue("uid");
+ mAccessToken = ocRepresentation.getValue("accesstoken");
+ mRefreshToken = ocRepresentation.getValue("refreshtoken");
+ String tokenType = ocRepresentation.getValue("tokentype");
+ msg("\tuserID: " + mUserUuid);
+ msg("\taccessToken: " + mAccessToken);
+ msg("\trefreshToken: " + mRefreshToken);
+ msg("\ttokenType: " + tokenType);
+
+ if (ocRepresentation.hasAttribute("expiresin")) {
+ int expiresIn = ocRepresentation.getValue("expiresin");
+ msg("\texpiresIn: " + expiresIn);
+ }
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ @Override
+ public synchronized void onPostFailed(Throwable throwable) {
+ msg("Failed to signUp");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnPostListener onSignIn = new OcAccountManager.OnPostListener() {
+ @Override
+ public synchronized void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("signIn was successful");
+ try {
+ msg("observeInvitation");
+ mAccountManager.observeInvitation(onObserveInvitation);
+ msg("getGroupList");
+ mAccountManager.getGroupList(onGetGroupList);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ @Override
+ public synchronized void onPostFailed(Throwable throwable) {
+ msg("Failed to signIn");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnPostListener onSignOut = new OcAccountManager.OnPostListener() {
+ @Override
+ public synchronized void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("signOut was successful");
+ }
+
+ @Override
+ public synchronized void onPostFailed(Throwable throwable) {
+ msg("Failed to signOut");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnGetListener onGetGroupList = new OcAccountManager.OnGetListener() {
+ @Override
+ public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
+ msg("getGroupList was successful");
+ try {
+ String[] gidlist = ocRepresentation.getValue("gidlist");
+ if (gidlist == null) {
+ msg("\tgroup list is empty");
+ mGroupId = null;
+ } else {
+ msg("\tgroup list");
+ for (String group : gidlist) {
+ msg("\t\t" + group);
+ mGroupId = group;
+ }
+ msg("\tcurrent group is " + mGroupId);
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void onGetFailed(Throwable throwable) {
+ msg("Failed to getGroupList");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnObserveListener onObserveInvitation =
+ new OcAccountManager.OnObserveListener() {
+ @Override
+ public void onObserveCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation, int i) {
+ msg("observeInvitation was successful");
+ try {
+ if (REGISTER == i) {
+ msg("REGISTER was successful");
+
+ OcRepresentation[] sendInvitationList =
+ ocRepresentation.getValue("invite");
+ if (sendInvitationList != null) {
+ msg("\tList of invitation that I sent");
+ for (OcRepresentation invitation : sendInvitationList) {
+ String gid = invitation.getValue("gid");
+ String mid = invitation.getValue("mid");
+ msg("\t\t-GroupID : " + gid);
+ msg("\t\t InviteeID : " + mid);
+ }
+ }
+
+ OcRepresentation[] receiveInvitationList =
+ ocRepresentation.getValue("invited");
+ if (receiveInvitationList != null) {
+ msg("\tList of invitation that I received");
+ for (OcRepresentation invitation : receiveInvitationList) {
+ String gid = invitation.getValue("gid");
+ String mid = invitation.getValue("mid");
+ msg("\t\t-GroupID : " + gid);
+ msg("\t\t InviterID : " + mid);
+ }
+ }
+ } else if (DEREGISTER == i) {
+ msg("DEREGISTER was successful");
+ } else {
+ OcRepresentation[] sendInvitationList =
+ ocRepresentation.getValue("invite");
+ if (sendInvitationList != null) {
+ msg("\tList of invitation that I sent");
+ for (OcRepresentation invitation : sendInvitationList) {
+ String gid = invitation.getValue("gid");
+ String mid = invitation.getValue("mid");
+ msg("\t\t-GroupID : " + gid);
+ msg("\t\t InviteeID : " + mid);
+ }
+ }
+
+ OcRepresentation[] receivInvitationList =
+ ocRepresentation.getValue("invited");
+ if (receivInvitationList != null) {
+ msg("\tList of invitation that I received");
+ for (OcRepresentation invitation : receivInvitationList) {
+ mGroupId = invitation.getValue("gid");
+ mGroupMasterId = invitation.getValue("mid");
+ msg("\t\t-GroupID : " + mGroupId);
+ msg("\t\t InviterID : " + mGroupMasterId);
+ }
+ msg("searchUser");
+ mAccountManager.searchUser(mGroupMasterId, onSearchUserForInvitee);
+ }
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void onObserveFailed(Throwable throwable) {
+ msg("Failed to observeInvitation");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnGetListener onSearchUserForInvitee = new OcAccountManager.OnGetListener() {
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("searchUser was successful");
+ try {
+ OcRepresentation[] userList = ocRepresentation.getValue("ulist");
+ for (OcRepresentation user : userList) {
+ String inviterUuid = user.getValue("uid");
+ Log.d(TAG, "inviterUuid : " + inviterUuid);
+
+ OcRepresentation userInfo = user.getValue("uinfo");
+ mInviterUserId = userInfo.getValue("userid");
+ }
+
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ showInviteMsg(mInviterUserId);
+ }
+ });
+
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ msg("Failed to searchUser");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnPostListener onJoinGroup = new OcAccountManager.OnPostListener() {
+ @Override
+ public synchronized void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("joinGroup was successful");
+ try {
+ msg("observeGroup");
+ mAccountManager.observeGroup(mGroupId, onObserveGroup);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ @Override
+ public synchronized void onPostFailed(Throwable throwable) {
+ msg("Failed to joinGroup");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnDeleteListener onDeleteInvitation = new OcAccountManager.OnDeleteListener() {
+ @Override
+ public void onDeleteCompleted(List<OcHeaderOption> list) {
+ msg("deleteInvitation was successful");
+ try {
+ mAccountManager.getGroupList(onGetGroupList);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void onDeleteFailed(Throwable throwable) {
+ msg("Failed to deleteInvitation");
+ }
+ };
+
+ OcAccountManager.OnGetListener onSearchUserForInviter = new OcAccountManager.OnGetListener() {
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("searchUser was successful");
+ try {
+ OcRepresentation[] userList = ocRepresentation.getValue("ulist");
+ for (OcRepresentation user : userList) {
+ mInviteeUuid = user.getValue("uid");
+ OcRepresentation userInfo = user.getValue("uinfo");
+ String inviteeUserId = userInfo.getValue("userid");
+ Log.d(TAG, "inviteeUserId : " + inviteeUserId);
+ }
+ msg("sendInvitation");
+ mAccountManager.sendInvitation(mGroupId, mInviteeUuid, onSendInvitation);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ msg("Failed to searchUser");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnPostListener onCreateGroup = new OcAccountManager.OnPostListener() {
+ @Override
+ public synchronized void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("createGroup was successful");
+ try {
+ mGroupId = ocRepresentation.getValue("gid");
+ msg("\tgroupId: " + mGroupId);
+
+ msg("observeGroup");
+ mAccountManager.observeGroup(mGroupId, onObserveGroup);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ @Override
+ public synchronized void onPostFailed(Throwable throwable) {
+ msg("Failed to createGroup");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnObserveListener onObserveGroup = new OcAccountManager.OnObserveListener() {
+ @Override
+ public void onObserveCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation, int i) {
+ msg("observeGroup was successful");
+ try {
+ if (REGISTER == i) {
+ msg("REGISTER was successful");
+ } else if (DEREGISTER == i) {
+ msg("DEREGISTER was successful");
+ } else {
+ String gid = ocRepresentation.getValue("gid");
+ msg("\tGroupID: " + gid);
+
+ String gmid = ocRepresentation.getValue("gmid");
+ msg("\tGroupMasterID: " + gmid);
+
+ String[] midlist = ocRepresentation.getValue("midlist");
+ if (midlist == null) {
+ msg("\tMember List is empty");
+ } else {
+ msg("\tMember List(" + midlist.length + ")");
+ for (String mid : midlist) {
+ msg("\t : " + mid);
+ }
+ }
+
+ String[] dilist = ocRepresentation.getValue("dilist");
+ if (dilist == null) {
+ msg("\tDevice List is empty");
+ } else {
+ msg("\tDevice List(" + dilist.length + ")");
+ for (String di : dilist) {
+ msg("\t : " + di);
+ }
+ }
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void onObserveFailed(Throwable throwable) {
+ msg("Failed to observeGroup");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnPostListener onSendInvitation = new OcAccountManager.OnPostListener() {
+ @Override
+ public synchronized void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ msg("sendInvitation was successful");
+ }
+
+ @Override
+ public synchronized void onPostFailed(Throwable throwable) {
+ msg("Failed to sendInvitation");
+ if (throwable instanceof OcException) {
+ OcException ocEx = (OcException) throwable;
+ Log.e(TAG, ocEx.toString());
+ ErrorCode errCode = ocEx.getErrorCode();
+ msg("Error code: " + errCode);
+ }
+ }
+ };
+
+ OcAccountManager.OnDeleteListener onLeaveGroup = new OcAccountManager.OnDeleteListener() {
+ @Override
+ public void onDeleteCompleted(List<OcHeaderOption> list) {
+ msg("leaveGroup was successful");
+ try {
+ msg("getGroupList");
+ mAccountManager.getGroupList(onGetGroupList);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void onDeleteFailed(Throwable throwable) {
+ msg("Failed to leaveGroup");
+ }
+ };
+
+ // ******************************************************************************
+ // End of the Account Manager specific code
+ // ******************************************************************************
+
+ OcPlatform.OnPublishResourceListener resourcePublishListener =
+ new OcPlatform.OnPublishResourceListener() {
+ @Override
+ public void onPublishResourceCompleted(OcRepresentation ocRepresentation) {
+ msg("onPublishResourceCompleted");
+
+ for (OcRepresentation child : ocRepresentation.getChildren()) {
+ try {
+ msg("\tPublished Resource URI : " + child.getValue("href"));
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void onPublishResourceFailed(Throwable throwable) {
+ msg("onPublishResourceFailed has failed");
+ }
+ };
+
+ OcPlatform.OnDeleteResourceListener resourceDeleteListener =
+ new OcPlatform.OnDeleteResourceListener() {
+ @Override
+ public void onDeleteResourceCompleted(int resultCode) {
+ msg("onDeleteResourceCompleted, result is " + resultCode);
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource ocResource) {
+ synchronized (mActivity) {
+ final String resourceUri = ocResource.getUri();
+
+ if (mFoundResource == null) {
+ if (resourceUri.contains(Common.RESOURCE_URI)) {
+ msg("onResourceFound : " + ocResource.getUri());
+ mFoundResource = ocResource;
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable throwable, String uri) {
+ synchronized (mActivity) {
+ msg("findResource request has failed");
+ }
+ }
+ };
+
+ @Override
+ public synchronized EntityHandlerResult handleEntity(final OcResourceRequest request) {
+ EntityHandlerResult ehResult = EntityHandlerResult.ERROR;
+ if (null == request) {
+ msg("Server request is invalid");
+ return ehResult;
+ }
+ // Get the request flags
+ EnumSet<RequestHandlerFlag> requestFlags = request.getRequestHandlerFlagSet();
+ if (requestFlags.contains(RequestHandlerFlag.INIT)) {
+ msg("\t\tRequest Flag: Init");
+ ehResult = EntityHandlerResult.OK;
+ }
+ if (requestFlags.contains(RequestHandlerFlag.REQUEST)) {
+ msg("\t\tRequest Flag: Request");
+ ehResult = handleRequest(request);
+ }
+ if (requestFlags.contains(RequestHandlerFlag.OBSERVER)) {
+ msg("\t\tRequest Flag: Observer");
+ ehResult = handleObserver(request);
+ }
+
+ return ehResult;
+ }
+
+ private EntityHandlerResult handleRequest(OcResourceRequest request) {
+ EntityHandlerResult ehResult = EntityHandlerResult.ERROR;
+ // Check for query params (if any)
+ Map<String, String> queries = request.getQueryParameters();
+ if (!queries.isEmpty()) {
+ msg("Query processing is up to entityHandler");
+ } else {
+ msg("No query parameters in this request");
+ }
+
+ for (Map.Entry<String, String> entry : queries.entrySet()) {
+ msg("Query key: " + entry.getKey() + " value: " + entry.getValue());
+ }
+
+ //Get the request type
+ RequestType requestType = request.getRequestType();
+ switch (requestType) {
+ case GET:
+ msg("\t\t\tRequest Type is GET");
+ ehResult = handleGetRequest(request);
+ break;
+ case PUT:
+ msg("\t\t\tRequest Type is PUT");
+ ehResult = handlePutRequest(request);
+ break;
+ case POST:
+ msg("\t\t\tRequest Type is POST");
+ break;
+ case DELETE:
+ msg("\t\t\tRequest Type is DELETE");
+ break;
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handleGetRequest(final OcResourceRequest request) {
+ EntityHandlerResult ehResult;
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
- response.setErrorCode(Common.SUCCESS);
+ response.setResponseResult(EntityHandlerResult.OK);
+ response.setResourceRepresentation(getOcRepresentation());
+ return sendResponse(response);
+ }
+
+ private EntityHandlerResult handlePutRequest(OcResourceRequest request) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
+ setOcRepresentation(request.getResourceRepresentation());
+ response.setResourceRepresentation(getOcRepresentation());
+ response.setResponseResult(EntityHandlerResult.OK);
- isSecured.setVisibility(View.VISIBLE);
- isSecured.setChecked(mSecured);
-
+ return sendResponse(response);
+ }
+
+ public void setOcRepresentation(OcRepresentation rep) {
+ try {
+ if (rep.hasAttribute(Common.LIGHT_STATE_KEY)) {
+ mState = rep.getValue(Common.LIGHT_STATE_KEY);
+ }
+ if (rep.hasAttribute(Common.LIGHT_POWER_KEY)) {
+ mPower = rep.getValue(Common.LIGHT_POWER_KEY);
+ }
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to get representation values");
+ }
+ }
+
+ public OcRepresentation getOcRepresentation() {
+ OcRepresentation rep = new OcRepresentation();
+ try {
+ rep.setValue(Common.LIGHT_STATE_KEY, mState);
+ rep.setValue(Common.LIGHT_POWER_KEY, mPower);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to set representation values");
+ }
+ return rep;
+ }
+
+ private EntityHandlerResult handleObserver(final OcResourceRequest request) {
+ // Observation happens on a different thread in notifyObservers method.
+ // If we have not created the thread already, we will create one here.
+ if (null == mObserverNotifier) {
+ mObserverNotifier = new Thread(new Runnable() {
+ public void run() {
+ notifyObservers(request);
+ }
+ });
+ mObserverNotifier.start();
+ }
+ return EntityHandlerResult.OK;
+ }
+
+ private void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void notifyObservers(OcResourceRequest request) {
+ while (true) {
+ // increment current power value by 10 every 2 seconds
+ mPower += 10;
+ sleep(2);
+
+ msg("Notifying observers...");
+ msg(this.toString());
+ try {
+ OcPlatform.notifyAllObservers(localLightResourceHandle);
+ } catch (OcException e) {
+ ErrorCode errorCode = e.getErrorCode();
+ if (ErrorCode.NO_OBSERVERS == errorCode) {
+ msg("No more observers, stopping notifications");
+ mObserverNotifier = null;
+ }
+ return;
+ }
+ }
+ }
+
+ private EntityHandlerResult sendResponse(OcResourceResponse response) {
+ try {
+ OcPlatform.sendResponse(response);
+ return EntityHandlerResult.OK;
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to send response");
+ return EntityHandlerResult.ERROR;
+ }
+ }
+
+ private void createResource() {
+ if (localLightResourceHandle == null) {
+ try {
+ localLightResourceHandle = OcPlatform.registerResource(
+ Common.RESOURCE_URI, //resource URI
+ Common.RESOURCE_TYPE, //resource type name
+ Common.RESOURCE_INTERFACE, //using default interface
+ this, //use default entity handler
+ EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE)
+ );
+ mResourceHandleList.add(localLightResourceHandle);
+ msg("Create Local Resource is success.");
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+ }
+
+ private void publishResourceToRD() {
+ // Create Local Resource.
+ createResource();
+
+ try {
+ // Publish Virtual Resource to Resource-Directory.
+ Log.d(TAG, "Publish Virtual Resource to Resource-Directory.");
+ OcPlatform.publishResourceToRD(
+ Common.HOST, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP),
+ resourcePublishListener
+ );
+
+ // Publish Local Resource to Resource-Directory.
+ Log.d(TAG, "Publish Local Resource to Resource-Directory.");
+ OcPlatform.publishResourceToRD(
+ Common.HOST, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), mResourceHandleList,
+ resourcePublishListener
+ );
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void deleteResourceFromRD() {
+ try {
+ // Delete Resource from Resource-Directory.
+ Log.d(TAG, "Delete Resource from Resource-Directory.");
+ OcPlatform.deleteResourceFromRD(
+ Common.HOST, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP),
+ resourceDeleteListener
+ );
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void subscribeDevicePresence() {
+ try {
+ if (null == mOcPresenceHandle) {
+ List<String> di = new ArrayList<>();
+ mOcPresenceHandle = OcPlatform.subscribeDevicePresence(
+ Common.HOST, di, EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), this);
+ mDevicePresenceButton.setText(R.string.unsub_presence);
+ } else {
+ OcPlatform.unsubscribePresence(mOcPresenceHandle);
+ mOcPresenceHandle = null;
+ mDevicePresenceButton.setText(R.string.sub_presence);
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void onObserveCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation, int sequenceNumber) {
+ if (sequenceNumber != maxSequenceNumber + 1) {
+ msg("OBSERVE Result:");
+ msg("\tSequenceNumber:" + sequenceNumber);
+ try {
+ if (ocRepresentation.hasAttribute("prslist")) {
+ OcRepresentation[] prslist = ocRepresentation.getValue("prslist");
+ if (prslist != null) {
+ msg("\tDevice Presence");
+ for (OcRepresentation prs : prslist) {
+ msg("\t\tDevice ID : " + prs.getValue("di"));
+ msg("\t\tState : " + prs.getValue("state"));
+ }
+ }
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ } else {
+ msg("Successful unsubscribePresence");
+ }
+ }
+
+ @Override
+ public void onObserveFailed(Throwable throwable) {
+
+ }
+
+ private void findResourceFromRD() {
+ try {
+ // Find Resource from Resource-Directory.
+ Log.d(TAG, "Find Resource from Resource-Directory.");
+ OcPlatform.findResource(
+ Common.HOST,
+ OcPlatform.WELL_KNOWN_QUERY,
+ EnumSet.of(OcConnectivityType.CT_ADAPTER_IP),
+ resourceFoundListener, mQos
+ );
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void registerObserveToRS() {
+ try {
+ // Register Observe to Resource-Server.
+ Log.d(TAG, "Register Observe to Resource-Server.");
+ if (mFoundResource != null) {
+ mFoundResource.observe(ObserveType.OBSERVE, new HashMap<String, String>(), this);
+ }
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void deregisterObserveToRS() {
+ try {
+ // Deregister Observe to Resource-Server.
+ Log.d(TAG, "Deregister Observe to Resource-Server.");
+ if (mFoundResource != null) {
+ mFoundResource.cancelObserve();
+ }
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ // ******************************************************************************
+ // End of the Resource Directory specific code
+ // ******************************************************************************
+
+ void getMQBroker() {
+ List<String> resourceTypeList = new ArrayList<>();
+ List<String> resourceInterfaceList = new ArrayList<>();
+ resourceInterfaceList.add(Common.RESOURCE_INTERFACE);
+ resourceTypeList.add("ocf.wk.ps");
+ try {
+ MQbrokerResource = OcPlatform.constructResourceObject(
+ Common.HOST,
+ Common.MQ_BROKER_URI,
+ EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP, OcConnectivityType.CT_IP_USE_V4),
+ false,
+ resourceTypeList, resourceInterfaceList);
+
+ msg("found MQ broker : " + MQbrokerResource.getHost());
+
+ discoveryMQTopics();
+
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ void discoveryMQTopics() {
+ try {
+ if (null != MQbrokerResource) {
+ MQbrokerResource.discoveryMQTopics(
+ new HashMap<String, String>(),
+ this, QualityOfService.LOW);
+ }
+
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ synchronized public void onTopicDiscoveried(OcResource ocResource) {
+ synchronized (this) {
+ String resourceUri = ocResource.getUri();
+
+ msg("onTopicDiscoveried : " + resourceUri + " found");
+ }
+ }
+
+ @Override
+ public void onDiscoveryTopicFailed(Throwable ex, String uri) {
+ Log.e(TAG, "onFindTopicFailed : ", ex);
+
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ Log.d(TAG, "onFindTopicFailed Code: " + errCode);
+ Log.d(TAG, "onFindTopicFailed Code: " + errCode.ordinal());
+ Log.d(TAG, "onFindTopicFailed uri: " + uri);
+
+ } else {
+ Log.e(TAG, ex.getMessage());
+ }
+ }
+
+ void createMQTopic() {
+ try {
+ if (null != MQbrokerResource) {
+ Map<String, String> queryParameters = new HashMap<>();
+ queryParameters.put("rt", "light");
+ MQbrokerResource.createMQTopic(
+ new OcRepresentation(),
+ defaultTopicFullName,
+ queryParameters,
+ this,
+ QualityOfService.LOW);
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ synchronized public void onTopicResourceCreated(OcResource ocResource) {
+ synchronized (this) {
+ Log.d(TAG, "onTopicResourceCreated");
+ currentTopicResource = ocResource;
+
+ msg("onTopicResourceCreated : " + currentTopicResource.getUri());
+ }
+ }
+
+ @Override
+ public void onCreateTopicFailed(Throwable ex, String uri) {
+ Log.e(TAG, "onCreateTopicFailed : ", ex);
+
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ Log.d(TAG, "onCreateTopicFailed error Code: " + errCode);
+ Log.d(TAG, "onCreateTopicFailed error Code: " + errCode.ordinal());
+ Log.d(TAG, "onCreateTopicFailed error uri: " + uri);
+
+ // retry to create after increase room number
+ defaultTopicFullName = Common.MQ_DEFAULT_TOPIC_URI + (roomNum++);
+ createMQTopic();
+ } else {
+ Log.e(TAG, ex.getMessage());
+ }
+ }
+
+ void subscribeMQTopic() {
+ Map<String, String> queryParameters = new HashMap<>();
+ queryParameters.put("rt", "light");
+
+ try {
+ if (null != currentTopicResource) {
+ currentTopicResource.subscribeMQTopic(
+ queryParameters,
+ this,
+ QualityOfService.LOW);
+ }
+
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ synchronized public void onSubScribeCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation,
+ int sequenceNumber) {
+ synchronized (this) {
+ String resourceUri = ocRepresentation.getUri();
+ Log.d(TAG, "onSubScribeCompleted sequenceNumber : " + sequenceNumber);
+
+ try {
+ int subFlag;
+ OcRepresentation val = ocRepresentation.getValue("message");
+
+ if (sequenceNumber == 0) {
+ Log.d(TAG, "onSubScribeCompleted : " + resourceUri);
+ subFlag = 0;
+ } else {
+ subFlag = 1;
+ }
+
+ if (subFlag == 0) {
+ msg("onSubScribeCompleted : " + resourceUri);
+ } else {
+ Log.d(TAG, "onSubScribeCompleted : " + resourceUri);
+ Log.d(TAG, "onSubScribeCompleted : " + val.getValue("blue"));
+ Log.d(TAG, "onSubScribeCompleted : " + val.getValue("red"));
+
+ msg("onSubScribeCompleted : " + resourceUri + ", blue light is "
+ + val.getValue("blue").toString());
+ msg("onSubScribeCompleted : " + resourceUri + ", red light is "
+ + val.getValue("red").toString());
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ synchronized public void onUnsubScribeCompleted(OcRepresentation ocRepresentation,
+ int sequenceNumber) {
+ synchronized (this) {
+ String resourceUri = ocRepresentation.getUri();
+ Log.d(TAG, "onUnsubScribeCompleted sequenceNumber : " + sequenceNumber);
+
+ if (sequenceNumber == maxSequenceNumber + 1) {
+ Log.d(TAG, "onUnsubScribeCompleted : " + resourceUri);
+ msg("onUnsubScribeCompleted : " + resourceUri);
+ }
+ }
+ }
+
+ @Override
+ public void onSubScribeFailed(Throwable ex) {
+ Log.d(TAG, "onSubScribeFailed : ", ex);
+
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ Log.d(TAG, "onSubScribeFailed error Code: " + errCode);
+ Log.d(TAG, "onSubScribeFailed error Code: " + errCode.ordinal());
+
+
+ } else {
+ Log.e(TAG, ex.getMessage());
+ }
+ }
+
+
+ void unsubscribeMQTopic() {
+
+ try {
+ if (null != currentTopicResource) {
+ currentTopicResource.unsubscribeMQTopic(QualityOfService.LOW);
+ }
+
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ void publishMQTopic() {
+
+ try {
+ OcRepresentation rep = new OcRepresentation();
+ OcRepresentation msg = new OcRepresentation();
+
+ if (switchingFlag) {
+ msg.setValue("blue", "on");
+ msg.setValue("red", "off");
+ switchingFlag = false;
+ } else {
+ msg.setValue("blue", "off");
+ msg.setValue("red", "on");
+ switchingFlag = true;
+ }
+ rep.setValue("message", msg);
+
+ if (null != currentTopicResource) {
+ currentTopicResource.publishMQTopic(rep,
+ new HashMap<String, String>(),
+ mqPublishListener,
+ QualityOfService.LOW);
+ }
+
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ OcResource.OnPostListener mqPublishListener =
+ new OcResource.OnPostListener() {
+ @Override
+ public void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ Log.i(TAG, "onPublish completed");
+ msg("onPublish completed");
+ }
+
+ @Override
+ public void onPostFailed(Throwable throwable) {
+ Log.e(TAG, "onPublish failed");
+ msg("onPublish failed");
+ }
+ };
+
+ void requestMQPublish() {
+
+ try {
+ if (null != currentTopicResource) {
+ currentTopicResource.requestMQPublish(
+ new HashMap<String, String>(),
+ mqReqPubListener,
+ QualityOfService.LOW);
+ }
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+
+ OcResource.OnPostListener mqReqPubListener =
+ new OcResource.OnPostListener() {
+ @Override
+ public void onPostCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ Log.i(TAG, "onRequestPublish completed");
+ msg("onPublish completed");
+ }
+
+ @Override
+ public void onPostFailed(Throwable throwable) {
+ Log.e(TAG, "onRequestPublish failed");
+ msg("onRequestPublish failed");
+ }
+ };
+
+ // ******************************************************************************
+ // End of the Message Queue specific code
+ // ******************************************************************************
+
+ private void showTCPInput() {
+
+ LayoutInflater layoutInflater = LayoutInflater.from(mContext);
+ View inputView = layoutInflater.inflate(R.layout.input, null);
+ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
+ alertDialogBuilder.setView(inputView);
+
++ final RadioGroup radioGroup = (RadioGroup) inputView.getRootView().findViewById(R.id.radioGroup);
++ final RadioButton radioIP = (RadioButton) inputView.getRootView().findViewById(R.id.radioIP);
+ final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.inputText);
+ final CheckBox isSecured = (CheckBox) inputView.getRootView().findViewById(R.id.secured);
+
++ radioGroup.setVisibility(View.VISIBLE);
++ isSecured.setVisibility(View.VISIBLE);
++ isSecured.setChecked(mSecured);
++
+ StringBuilder sb = new StringBuilder();
+ sb.append(Common.TCP_ADDRESS);
+ sb.append(Common.PORT_SEPARATOR);
+ sb.append(Common.TCP_PORT);
+ editText.setText(sb.toString());
+
- if (editText.getText().length() != 0) {
- final String hosts = editText.getText().toString();
- boolean isValid = ADDRESS_PORT.matcher(hosts).matches();
- if (isValid) {
- final String host[] = hosts.split(Common.PORT_SEPARATOR);
- Common.TCP_ADDRESS = host[0];
- Common.TCP_PORT = host[1];
- mSecured = isSecured.isChecked();
-
- StringBuilder sb = new StringBuilder();
- if (mSecured) {
- sb.append(Common.COAPS_TCP);
+ alertDialogBuilder
+ .setCancelable(true)
+ .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
- sb.append(Common.COAP_TCP);
++
++ final String hosts = editText.getText().toString();
++ boolean isValid = false;
++
++ if (!hosts.isEmpty() && hosts.contains(Common.PORT_SEPARATOR)) {
++ isValid = true;
++ }
++
++ if (isValid) {
++ final String host[] = hosts.split(Common.PORT_SEPARATOR);
++ mSecured = isSecured.isChecked();
++
++ if (2 > host.length || !PORT_NUMBER.matcher(host[1]).matches()) {
++ isValid = false;
++ } else if (radioIP.isChecked()) {
++ if (Patterns.IP_ADDRESS.matcher(host[0]).matches()) {
++ Common.TCP_ADDRESS = host[0];
++ Common.TCP_PORT = host[1];
+ } else {
- sb.append(Common.TCP_ADDRESS);
- sb.append(Common.PORT_SEPARATOR);
- sb.append(Common.TCP_PORT);
- Common.HOST = sb.toString();
++ isValid = false;
+ }
- Toast.makeText(mContext, "Invalid IP", Toast.LENGTH_SHORT).show();
- showTCPInput();
+ } else {
++ if (Patterns.DOMAIN_NAME.matcher(host[0]).matches()
++ && !Patterns.IP_ADDRESS.matcher(host[0]).matches()) {
++ Thread thread = new Thread() {
++ @Override
++ public void run() {
++ try {
++ Common.TCP_ADDRESS = InetAddress
++ .getByName(host[0]).getHostAddress();
++ Common.TCP_PORT = host[1];
++ } catch (UnknownHostException e) {
++ e.printStackTrace();
++ msg("Failed to get host address.");
++ }
++ }
++ };
++ thread.start();
++ try {
++ thread.join();
++ } catch (InterruptedException e) {
++ e.printStackTrace();
++ }
++ } else {
++ isValid = false;
++ }
+ }
+ }
++
++ if (isValid) {
++ StringBuilder sb = new StringBuilder();
++ if (mSecured) {
++ sb.append(Common.COAPS_TCP);
++ } else {
++ sb.append(Common.COAP_TCP);
++ }
++ sb.append(Common.TCP_ADDRESS);
++ sb.append(Common.PORT_SEPARATOR);
++ sb.append(Common.TCP_PORT);
++ Common.HOST = sb.toString();
++ msg("Set Host : " + Common.HOST);
++ } else {
++ Toast.makeText(mContext, "Invalid input", Toast.LENGTH_SHORT).show();
++ showTCPInput();
++ }
+ }
+ })
+ .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ dialog.cancel();
+ }
+ });
+
+ AlertDialog alert = alertDialogBuilder.create();
+ alert.show();
+ }
+
+ private void showInviteUser() {
+
+ LayoutInflater layoutInflater = LayoutInflater.from(mContext);
+ View inputView = layoutInflater.inflate(R.layout.input, null);
+ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
+ alertDialogBuilder.setView(inputView);
+
+ final TextView textView = (TextView) inputView.getRootView().findViewById(R.id.inputView);
+ textView.setText("Please enter user ID to invite.");
+ final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.inputText);
+
+ alertDialogBuilder
+ .setCancelable(true)
+ .setPositiveButton("OK", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ if (editText.getText().length() != 0) {
+ final String userID = editText.getText().toString();
+
+ try {
+ Map<String, String> option = new HashMap<>();
+ option.put("userid", userID);
+
+ msg("searchUser (User ID: " + userID + ")");
+ mAccountManager.searchUser(option, onSearchUserForInviter);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ })
+ .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ dialog.cancel();
+ }
+ });
+
+ AlertDialog alert = alertDialogBuilder.create();
+ alert.show();
+ }
+
+ private void showInviteMsg(String userID) {
+
+ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
+ alertDialogBuilder.setTitle("Invitation");
+ StringBuilder sb = new StringBuilder();
+ sb.append("Invited from ");
+ sb.append(userID);
+ sb.append(EOL);
+ sb.append("Accept?");
+ alertDialogBuilder.setMessage(sb.toString());
+ alertDialogBuilder
+ .setCancelable(true)
+ .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ try {
+ msg("joinGroup");
+ mAccountManager.joinGroup(mGroupId, onJoinGroup);
+ msg("deleteInvitation");
+ mAccountManager.deleteInvitation(mGroupId, onDeleteInvitation);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+ })
+ .setNegativeButton("No", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ dialog.cancel();
+ try {
+ msg("gid: " + mGroupId);
+ msg("deleteInvitation");
+ mAccountManager.deleteInvitation(mGroupId, onDeleteInvitation);
+ } catch (OcException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+
+ AlertDialog alert = alertDialogBuilder.create();
+ alert.show();
+ }
+
+ private void msg(final String text) {
+ mActivity.runOnUiThread(new Runnable() {
+ public void run() {
+ mResultLog.append(EOL);
+ mResultLog.append(text);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ @Override
+ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+
+ int visible;
+ if (isChecked) {
+ visible = View.VISIBLE;
+ } else {
+ visible = View.GONE;
+ }
+
+ switch (buttonView.getId()) {
+ case R.id.account_switch:
+ mAccountLayout.setVisibility(visible);
+ break;
+ case R.id.rd_switch:
+ mRDLayout.setVisibility(visible);
+ break;
+ case R.id.mq_switch:
+ mMQLayout.setVisibility(visible);
+ break;
+ }
+ }
+
+ @Override
+ public void onClick(View view) {
+ mActionLog.setText("[Action Log]" + EOL);
+
+ int viewID = view.getId();
+ if (mAccountManager == null && (viewID == R.id.signin_button
+ || viewID == R.id.signout_button || viewID == R.id.creategroup_button
+ || viewID == R.id.invite_button || viewID == R.id.leavegroup_button)) {
+ mActionLog.append("Do 'SignUp' first" + EOL);
+ return;
+ }
+
+ switch (viewID) {
+ // Account
+ case R.id.setip_button:
+ mActionLog.append("Set IP" + EOL);
+ showTCPInput();
+ break;
+ case R.id.signup_button:
+ mActionLog.append("Sign Up" + EOL);
+ signUp();
+ break;
+ case R.id.signin_button:
+ mActionLog.append("Sign In" + EOL);
+ signIn();
+ break;
+ case R.id.signout_button:
+ mActionLog.append("Sign Out" + EOL);
+ signOut();
+ break;
+ case R.id.creategroup_button:
+ mActionLog.append("Create Group" + EOL);
+ createGroup();
+ break;
+ case R.id.invite_button:
+ mActionLog.append("Invite User" + EOL);
+ inviteUser();
+ break;
+ case R.id.leavegroup_button:
+ mActionLog.append("Leave Group" + EOL);
+ leaveGroup();
+ break;
+
+ // RD
+ case R.id.rdpub_button:
+ mActionLog.append("Publish Resource To RD" + EOL);
+ publishResourceToRD();
+ break;
+ case R.id.rddel_button:
+ mActionLog.append("Delete Resource From RD" + EOL);
+ deleteResourceFromRD();
+ break;
+ case R.id.rddp_button:
+ mActionLog.append("Subscribe Device Presence" + EOL);
+ subscribeDevicePresence();
+ break;
+ case R.id.findresource_button:
+ mActionLog.append("Find Resource From RD" + EOL);
+ findResourceFromRD();
+ break;
+ case R.id.registerobserve_button:
+ mActionLog.append("Register Observe to RS" + EOL);
+ registerObserveToRS();
+ break;
+ case R.id.deregisterobserve_button:
+ mActionLog.append("Deregister Observe to RS" + EOL);
+ deregisterObserveToRS();
+ break;
+
+ // MQ
+ case R.id.mqget_button:
+ mActionLog.append("Get MQ Broker" + EOL);
+ getMQBroker();
+ break;
+ case R.id.mqcreate_button:
+ mActionLog.append("Create MQ Topic" + EOL);
+ createMQTopic();
+ break;
+ case R.id.mqsub_button:
+ mActionLog.append("Subscribe MQ Topic" + EOL);
+ subscribeMQTopic();
+ break;
+ case R.id.mqunsub_button:
+ mActionLog.append("Un-subscribe MQ Topic" + EOL);
+ unsubscribeMQTopic();
+ break;
+ case R.id.mqpub_button:
+ mActionLog.append("Publish MQ Topic" + EOL);
+ publishMQTopic();
+ break;
+ case R.id.mqreq_button:
+ mActionLog.append("Request MQ Publish" + EOL);
+ requestMQPublish();
+ break;
+ }
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View rootView = inflater.inflate(R.layout.fragment_cloud, container, false);
+
+ mAccountLayout = (LinearLayout) rootView.findViewById(R.id.account_layout);
+ mRDLayout = (LinearLayout) rootView.findViewById(R.id.rd_layout);
+ mMQLayout = (LinearLayout) rootView.findViewById(R.id.mq_layout);
+
+ Switch accountSwitch = (Switch) rootView.findViewById(R.id.account_switch);
+ Switch RDSwitch = (Switch) rootView.findViewById(R.id.rd_switch);
+ Switch MQSwitch = (Switch) rootView.findViewById(R.id.mq_switch);
+ accountSwitch.setOnCheckedChangeListener(this);
+ RDSwitch.setOnCheckedChangeListener(this);
+ MQSwitch.setOnCheckedChangeListener(this);
+
+ mAccountText = (TextView) rootView.findViewById(R.id.account_view);
+ mRDText = (TextView) rootView.findViewById(R.id.rd_view);
+ mMQText = (TextView) rootView.findViewById(R.id.mq_view);
+ mScrollView = (ScrollView) rootView.findViewById(R.id.scroll_view);
+ mActionLog = (TextView) rootView.findViewById(R.id.action_log_view);
+ mResultLog = (TextView) rootView.findViewById(R.id.result_log_view);
+
+ Button setIPButton = (Button) rootView.findViewById(R.id.setip_button);
+ Button signUpButton = (Button) rootView.findViewById(R.id.signup_button);
+ Button signInButton = (Button) rootView.findViewById(R.id.signin_button);
+ Button signOutButton = (Button) rootView.findViewById(R.id.signout_button);
+ Button createGroupButton = (Button) rootView.findViewById(R.id.creategroup_button);
+ Button inviteButton = (Button) rootView.findViewById(R.id.invite_button);
+ Button leaveGroupButton = (Button) rootView.findViewById(R.id.leavegroup_button);
+ setIPButton.setOnClickListener(this);
+ signUpButton.setOnClickListener(this);
+ signInButton.setOnClickListener(this);
+ signOutButton.setOnClickListener(this);
+ createGroupButton.setOnClickListener(this);
+ inviteButton.setOnClickListener(this);
+ leaveGroupButton.setOnClickListener(this);
+
+ Button rdPubButton = (Button) rootView.findViewById(R.id.rdpub_button);
+ Button rdDelButton = (Button) rootView.findViewById(R.id.rddel_button);
+ mDevicePresenceButton = (Button) rootView.findViewById(R.id.rddp_button);
+ rdPubButton.setOnClickListener(this);
+ rdDelButton.setOnClickListener(this);
+ mDevicePresenceButton.setOnClickListener(this);
+
+ Button mfindResButton = (Button) rootView.findViewById(R.id.findresource_button);
+ Button mRegObsButton = (Button) rootView.findViewById(R.id.registerobserve_button);
+ Button mDeRegObsButton = (Button) rootView.findViewById(R.id.deregisterobserve_button);
+ mfindResButton.setOnClickListener(this);
+ mRegObsButton.setOnClickListener(this);
+ mDeRegObsButton.setOnClickListener(this);
+
+ Button mqBrokerButton = (Button) rootView.findViewById(R.id.mqget_button);
+ Button createTopicButton = (Button) rootView.findViewById(R.id.mqcreate_button);
+ Button subTopicButton = (Button) rootView.findViewById(R.id.mqsub_button);
+ Button unsubTopicButton = (Button) rootView.findViewById(R.id.mqunsub_button);
+ Button pubToicButton = (Button) rootView.findViewById(R.id.mqpub_button);
+ mqBrokerButton.setOnClickListener(this);
+ createTopicButton.setOnClickListener(this);
+ subTopicButton.setOnClickListener(this);
+ unsubTopicButton.setOnClickListener(this);
+ pubToicButton.setOnClickListener(this);
+
+ return rootView;
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ }
+
+}
--- /dev/null
- android:orientation="horizontal"
- android:layout_marginBottom="2dp">
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/activity_vertical_margin"
+ android:paddingLeft="0dp"
+ android:paddingRight="0dp"
+ android:paddingTop="@dimen/activity_vertical_margin"
+ tools:context=".CloudFragment">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical">
+
+ <Switch
+ android:id="@+id/account_switch"
+ android:layout_width="match_parent"
+ android:layout_height="28dp"
+ android:background="#BBBBBB"
+ android:checked="true"
+ android:gravity="center_vertical"
+ android:paddingLeft="10dp"
+ android:text="Account Manager"
+ android:textColor="#FFFFFF"
+ android:textSize="14sp" />
+
+ <LinearLayout
+ android:id="@+id/account_layout"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:focusable="true"
+ android:focusableInTouchMode="true"
+ android:gravity="center_horizontal"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/account_view"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingBottom="10dp"
+ android:paddingLeft="20dp"
+ android:paddingTop="5dp"
+ android:text="@string/account_view" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_marginTop="2dp"
+ android:gravity="center_horizontal"
+ android:orientation="horizontal">
+
+ <Button
+ android:id="@+id/setip_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Set\nIP" />
+
+ <Button
+ android:id="@+id/signup_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Sign\nUp" />
+
+ <Button
+ android:id="@+id/signin_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Sign\nIn" />
+
+ <Button
+ android:id="@+id/signout_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Sign\nOut" />
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_marginBottom="2dp"
+ android:gravity="center_horizontal"
+ android:orientation="horizontal">
+
+ <Button
+ android:id="@+id/creategroup_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="CREATE\nGROUP" />
+
+ <Button
+ android:id="@+id/invite_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="INVITE\nUSER" />
+
+ <Button
+ android:id="@+id/leavegroup_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="LEAVE\nGROUP" />
+ </LinearLayout>
+ </LinearLayout>
+
+ <Switch
+ android:id="@+id/rd_switch"
+ android:layout_width="match_parent"
+ android:layout_height="28dp"
+ android:background="#AAAAAA"
+ android:gravity="center_vertical"
+ android:paddingLeft="10dp"
+ android:text="Resource Directory"
+ android:textColor="#FFFFFF"
+ android:textSize="14sp" />
+
+ <LinearLayout
+ android:id="@+id/rd_layout"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:focusable="true"
+ android:focusableInTouchMode="true"
+ android:gravity="center_horizontal"
+ android:orientation="vertical"
+ android:visibility="gone">
+
+ <TextView
+ android:id="@+id/rd_view"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingBottom="10dp"
+ android:paddingLeft="20dp"
+ android:paddingTop="5dp"
+ android:text="@string/rd_view" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_marginTop="2dp"
+ android:gravity="center_horizontal"
+ android:orientation="horizontal">
+
+ <Button
+ android:id="@+id/rdpub_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Publish\nResource" />
+
+ <Button
+ android:id="@+id/rddel_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Delete\nResource" />
+
+ <Button
+ android:id="@+id/rddp_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Sub Device\nPresence" />
+ </LinearLayout>
++
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
++ android:layout_marginBottom="2dp"
+ android:gravity="center_horizontal"
++ android:orientation="horizontal">
+
+ <Button
+ android:id="@+id/findresource_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="FIND\nRESOURCE" />
+
+ <Button
+ android:id="@+id/registerobserve_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="REGISTER\nOBSERVE" />
+
+ <Button
+ android:id="@+id/deregisterobserve_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_weight="1"
+ android:text="DEREGISTER\nOBSERVE" />
+ </LinearLayout>
+ </LinearLayout>
+
+ <Switch
+ android:id="@+id/mq_switch"
+ android:layout_width="match_parent"
+ android:layout_height="28dp"
+ android:background="#BBBBBB"
+ android:gravity="center_vertical"
+ android:paddingLeft="10dp"
+ android:text="Message Queue"
+ android:textColor="#FFFFFF"
+ android:textSize="14sp" />
+
+ <LinearLayout
+ android:id="@+id/mq_layout"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:focusable="true"
+ android:focusableInTouchMode="true"
+ android:gravity="center_horizontal"
+ android:orientation="vertical"
+ android:visibility="gone">
+
+ <TextView
+ android:id="@+id/mq_view"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingBottom="10dp"
+ android:paddingLeft="20dp"
+ android:paddingTop="5dp"
+ android:text="@string/mq_view" />
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_marginTop="2dp"
+ android:gravity="center_horizontal"
+ android:orientation="horizontal">
+
+ <Button
+ android:id="@+id/mqget_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Get\nBroker" />
+
+ <Button
+ android:id="@+id/mqcreate_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Create\nTopic" />
+
+ <Button
+ android:id="@+id/mqsub_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="SUB\nTopic" />
+
+ <Button
+ android:id="@+id/mqunsub_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="Unsub\nTopic" />
+
+ <Button
+ android:id="@+id/mqpub_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="PUB\nTopic" />
+
+ <Button
+ android:id="@+id/mqreq_button"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_weight="1"
+ android:text="REQ\nPUB"
+ android:visibility="gone" />
+ </LinearLayout>
+ </LinearLayout>
+
+ <TextView
+ android:layout_width="match_parent"
+ android:layout_height="28dp"
+ android:background="#AAAAAA"
+ android:gravity="center_vertical"
+ android:paddingLeft="10dp"
+ android:text="Log"
+ android:textColor="#FFFFFF"
+ android:textSize="14sp" />
+
+ <TextView
+ android:id="@+id/action_log_view"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingBottom="5dp"
+ android:paddingLeft="20dp"
+ android:paddingTop="5dp"
+ android:text="@string/action_log_view" />
+
+ <ScrollView
+ android:id="@+id/scroll_view"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent">
+
+ <TextView
+ android:id="@+id/result_log_view"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingLeft="20dp"
+ android:paddingTop="5dp"
+ android:text="@string/result_log_view" />
+ </ScrollView>
+ </LinearLayout>
+
+</RelativeLayout>
--- /dev/null
- android:text="Input Server IP and Port"
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical"
+ android:padding="@dimen/activity_vertical_margin">
+
+ <TextView
+ android:id="@+id/inputView"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
++ android:text="Enter the server information"
+ android:textAppearance="?android:attr/textAppearanceMedium" />
+
++ <RadioGroup
++ android:id="@+id/radioGroup"
++ android:layout_width="match_parent"
++ android:layout_height="wrap_content"
++ android:visibility="gone">
++
++ <RadioButton
++ android:id="@+id/radioIP"
++ android:layout_width="match_parent"
++ android:layout_height="wrap_content"
++ android:checked="true"
++ android:text="Use IP and Port" />
++
++ <RadioButton
++ android:id="@+id/radioDomain"
++ android:layout_width="match_parent"
++ android:layout_height="wrap_content"
++ android:text="Use Domain and Port" />
++ </RadioGroup>
++
+ <EditText
+ android:id="@+id/inputText"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:padding="@dimen/activity_vertical_margin" />
+
+ <CheckBox
+ android:id="@+id/secured"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="SECURED"
+ android:visibility="gone" />
+
+</LinearLayout>
--- /dev/null
- response.setErrorCode(SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.ObservationInfo;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Light
+ * <p/>
+ * This class represents a light resource
+ */
+public class Light implements OcPlatform.EntityHandler {
+ private static final String NAME_KEY = "name";
+ private static final String STATE_KEY = "state";
+ private static final String POWER_KEY = "power";
+
+ private String mResourceUri; //resource URI
+ private String mResourceTypeName; //resource type name.
+ private String mResourceInterface; //resource interface.
+ private OcResourceHandle mResourceHandle; //resource handle
+
+ private String mName; //light name
+ private boolean mState; //light state
+ private int mPower; //light power
+
+ public Light(String resourceUri, String name, boolean state, int power) {
+ mResourceUri = resourceUri;
+ mResourceTypeName = "core.light";
+ mResourceInterface = OcPlatform.DEFAULT_INTERFACE;
+ mResourceHandle = null; //this is set when resource is registered
+
+ mName = name;
+ mState = state;
+ mPower = power;
+ }
+
+ public synchronized void registerResource() throws OcException {
+ if (null == mResourceHandle) {
+ mResourceHandle = OcPlatform.registerResource(
+ mResourceUri,
+ mResourceTypeName,
+ mResourceInterface,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE)
+ );
+ }
+ }
+
+ /**
+ * NOTE: This is just a sample implementation of entity handler. Entity handler can be
+ * implemented in several ways by the manufacturer.
+ *
+ * @param request
+ * @return
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(final OcResourceRequest request) {
+ EntityHandlerResult ehResult = EntityHandlerResult.ERROR;
+ if (null == request) {
+ msg("Server request is invalid");
+ return ehResult;
+ }
+ // Get the request flags
+ EnumSet<RequestHandlerFlag> requestFlags = request.getRequestHandlerFlagSet();
+ if (requestFlags.contains(RequestHandlerFlag.INIT)) {
+ msg("\t\tRequest Flag: Init");
+ ehResult = EntityHandlerResult.OK;
+ }
+ if (requestFlags.contains(RequestHandlerFlag.REQUEST)) {
+ msg("\t\tRequest Flag: Request");
+ ehResult = handleRequest(request);
+ }
+ if (requestFlags.contains(RequestHandlerFlag.OBSERVER)) {
+ msg("\t\tRequest Flag: Observer");
+ ehResult = handleObserver(request);
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handleRequest(OcResourceRequest request) {
+ EntityHandlerResult ehResult = EntityHandlerResult.ERROR;
+ // Check for query params (if any)
+ Map<String, String> queries = request.getQueryParameters();
+ if (!queries.isEmpty()) {
+ msg("Query processing is up to entityHandler");
+ } else {
+ msg("No query parameters in this request");
+ }
+
+ for (Map.Entry<String, String> entry : queries.entrySet()) {
+ msg("Query key: " + entry.getKey() + " value: " + entry.getValue());
+ }
+
+ //Get the request type
+ RequestType requestType = request.getRequestType();
+ switch (requestType) {
+ case GET:
+ msg("\t\t\tRequest Type is GET");
+ ehResult = handleGetRequest(request);
+ break;
+ case PUT:
+ msg("\t\t\tRequest Type is PUT");
+ ehResult = handlePutRequest(request);
+ break;
+ case POST:
+ msg("\t\t\tRequest Type is POST");
+ ehResult = handlePostRequest(request);
+ break;
+ case DELETE:
+ msg("\t\t\tRequest Type is DELETE");
+ ehResult = handleDeleteRequest();
+ break;
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handleGetRequest(final OcResourceRequest request) {
+ EntityHandlerResult ehResult;
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
+ if (mIsSlowResponse) { // Slow response case
+ new Thread(new Runnable() {
+ public void run() {
+ handleSlowResponse(request);
+ }
+ }).start();
+ ehResult = EntityHandlerResult.SLOW;
+ } else { // normal response case.
- response.setErrorCode(SUCCESS);
+ response.setResponseResult(EntityHandlerResult.OK);
+ response.setResourceRepresentation(getOcRepresentation());
+ ehResult = sendResponse(response);
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handlePutRequest(OcResourceRequest request) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
+ setOcRepresentation(request.getResourceRepresentation());
+ response.setResourceRepresentation(getOcRepresentation());
+ response.setResponseResult(EntityHandlerResult.OK);
- response.setErrorCode(SUCCESS);
+ return sendResponse(response);
+ }
+
+ private static int sUriCounter = 1;
+ private EntityHandlerResult handlePostRequest(OcResourceRequest request) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+ String newUri = "/a/light" + (++sUriCounter);
+ if(null != mContext && mContext instanceof SimpleServer) {
+ ((SimpleServer) mContext).createNewLightResource(newUri, "John's light " + sUriCounter);
+ }
+ OcRepresentation rep_post = getOcRepresentation();
+ try {
+ rep_post.setValue(OcResource.CREATED_URI_KEY, newUri);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ }
+ response.setResourceRepresentation(rep_post);
- response.setErrorCode(SUCCESS);
+ response.setNewResourceUri(newUri);
+ response.setResponseResult(EntityHandlerResult.RESOURCE_CREATED);
+ return sendResponse(response);
+ }
+
+ private EntityHandlerResult handleDeleteRequest() {
+ try {
+ this.unregisterResource();
+ return EntityHandlerResult.RESOURCE_DELETED;
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to unregister a light resource");
+ return EntityHandlerResult.ERROR;
+ }
+ }
+
+ private void handleSlowResponse(OcResourceRequest request) {
+ sleep(10);
+ msg("Sending slow response...");
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
- response.setErrorCode(SUCCESS);
+ response.setResponseResult(EntityHandlerResult.OK);
+ response.setResourceRepresentation(getOcRepresentation());
+ sendResponse(response);
+ }
+
+ private List<Byte> mObservationIds; //IDs of observes
+
+ private EntityHandlerResult handleObserver(final OcResourceRequest request) {
+ ObservationInfo observationInfo = request.getObservationInfo();
+ switch (observationInfo.getObserveAction()) {
+ case REGISTER:
+ if (null == mObservationIds) {
+ mObservationIds = new LinkedList<>();
+ }
+ mObservationIds.add(observationInfo.getOcObservationId());
+ break;
+ case UNREGISTER:
+ mObservationIds.remove((Byte)observationInfo.getOcObservationId());
+ break;
+ }
+ // Observation happens on a different thread in notifyObservers method.
+ // If we have not created the thread already, we will create one here.
+ if (null == mObserverNotifier) {
+ mObserverNotifier = new Thread(new Runnable() {
+ public void run() {
+ notifyObservers(request);
+ }
+ });
+ mObserverNotifier.start();
+ }
+ return EntityHandlerResult.OK;
+ }
+
+ private void notifyObservers(OcResourceRequest request) {
+ while (true) {
+ // increment current power value by 10 every 2 seconds
+ mPower += 10;
+ sleep(2);
+
+ msg("Notifying observers...");
+ msg(this.toString());
+ try {
+ if (mIsListOfObservers) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setResourceRepresentation(getOcRepresentation());
+ OcPlatform.notifyListOfObservers(
+ mResourceHandle,
+ mObservationIds,
+ response);
+ } else {
+ OcPlatform.notifyAllObservers(mResourceHandle);
+ }
+ } catch (OcException e) {
+ ErrorCode errorCode = e.getErrorCode();
+ if (ErrorCode.NO_OBSERVERS == errorCode) {
+ msg("No more observers, stopping notifications");
+ mObserverNotifier = null;
+ }
+ return;
+ }
+ }
+ }
+
+ private EntityHandlerResult sendResponse(OcResourceResponse response) {
+ try {
+ OcPlatform.sendResponse(response);
+ return EntityHandlerResult.OK;
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to send response");
+ return EntityHandlerResult.ERROR;
+ }
+ }
+
+ public synchronized void unregisterResource() throws OcException {
+ if (null != mResourceHandle) {
+ OcPlatform.unregisterResource(mResourceHandle);
+ }
+ }
+
+ public void setOcRepresentation(OcRepresentation rep) {
+ try {
+ if (rep.hasAttribute(NAME_KEY)) mName = rep.getValue(NAME_KEY);
+ if (rep.hasAttribute(STATE_KEY)) mState = rep.getValue(STATE_KEY);
+ if (rep.hasAttribute(POWER_KEY)) mPower = rep.getValue(POWER_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to get representation values");
+ }
+ }
+
+ public OcRepresentation getOcRepresentation() {
+ OcRepresentation rep = new OcRepresentation();
+ try {
+ rep.setValue(NAME_KEY, mName);
+ rep.setValue(STATE_KEY, mState);
+ rep.setValue(POWER_KEY, mPower);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ msg("Failed to set representation values");
+ }
+ return rep;
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ public void setSlowResponse(boolean isSlowResponse) {
+ mIsSlowResponse = isSlowResponse;
+ }
+
+ public void useListOfObservers(boolean isListOfObservers) {
+ mIsListOfObservers = isListOfObservers;
+ }
+
+ public void setContext(Context context) {
+ mContext = context;
+ }
+
+ @Override
+ public String toString() {
+ return "\t" + "URI" + ": " + mResourceUri +
+ "\n\t" + NAME_KEY + ": " + mName +
+ "\n\t" + STATE_KEY + ": " + mState +
+ "\n\t" + POWER_KEY + ": " + mPower;
+ }
+
+ private void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ Log.e(TAG, e.toString());
+ }
+ }
+
+ private void msg(String text) {
+ if (null != mContext) {
+ Intent intent = new Intent("org.iotivity.base.examples.simpleserver");
+ intent.putExtra("message", text);
+ mContext.sendBroadcast(intent);
+ }
+ }
+
+ private final static String TAG = Light.class.getSimpleName();
+ private final static int SUCCESS = 200;
+ private boolean mIsSlowResponse = false;
+ private boolean mIsListOfObservers = false;
+ private Thread mObserverNotifier;
+ private Context mContext;
+}
--- /dev/null
- response.setErrorCode(Resource.SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * DoorResource
+ * <p/>
+ * DoorResource is a sample OIC server resource created by the refrigerator.
+ */
+public class DoorResource extends Resource implements OcPlatform.EntityHandler {
+ DoorResource(String side, Context context) {
+ mContext = context;
+ mSide = side;
+
+ registerDoorResource();
+ }
+
+ private void registerDoorResource() {
+ String resourceURI = DOOR_URI + mSide;
+ logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
+ try {
+ mResourceHandle = OcPlatform.registerResource(
+ resourceURI,
+ RESOURCE_TYPEDOOR,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DoorResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * sample implementation of eventHandler for doorResource - this can be implemented in many
+ * different ways
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(
+ RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
- response.setErrorCode(Resource.SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case PUT:
- response.setErrorCode(204);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case DELETE:
+ response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DoorResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ /**
+ * helper function to update the current value of the door resource
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
+ mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
+ logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
+ " and door side is " + mSide);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of doorResource, depending on if door is open/ closed
+ *
+ * @param representation new state of a door
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mDoorState = representation.getValue(DOOR_STATE_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ // Note, we won't let the user change the door side!
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private String mSide;
+ private boolean mDoorState;
+ public static final String DOOR_URI = "/door/";
+ public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
+ private static String TAG = "DoorResource: ";
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra(Resource.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
- response.setErrorCode(Resource.SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+
+/**
+ * LightResource
+ * <p/>
+ * LightResource is a sample OIC server resource created by the refrigerator.
+ */
+public class LightResource extends Resource implements OcPlatform.EntityHandler {
+ LightResource(Context context) {
+ mContext = context;
+
+ registerLightResource();
+ }
+
+ private void registerLightResource() {
+ try {
+ logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
+ mResourceHandle = OcPlatform.registerResource(
+ LIGHT_URI,
+ RESOURCE_TYPELIGHT,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register LightResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * sample implementation of eventHandler for lightResource - this can be implemented in many
+ * different ways
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(
+ RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
- response.setErrorCode(Resource.SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ case PUT:
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ }
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ /**
+ * update the value of light (ON/ OFF) from the representation
+ *
+ * @param representation new state of light
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * helper function to update the current state of the light
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private boolean mIsLightOn = false;
+
+ private static String TAG = "LightResource: ";
+ public static final String LIGHT_URI = "/light";
+ public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
+ public static final String LIGHT_STATUS_KEY = "light";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra(Resource.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
- response.setErrorCode(SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * DeviceResource
+ * <p/>
+ * Creates a device resource and performs action based on client requests
+ */
+public class DeviceResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String DEVICE_URI = "/device";
+ public static final String RESOURCE_TYPENAME = "intel.fridge";
+ public static final String API_VERSION = "v.1.0";
+ public static final String CLIENT_TOKEN = "21ae43gf";
+ public static final String DEVICE_NAME = "device_name";
+ private static String TAG = "DeviceResource: ";
+ public static final int SUCCESS = 200;
+ public static final int API_VERSION_KEY = 2048;
+ public static final int CLIENT_VERSION_KEY = 3000;
+
+ private Context mContext;
+
+ /**
+ * constructor
+ *
+ * @param context to enable sending of broadcast messages to be displayed on the user screen
+ */
+ DeviceResource(Context context) {
+ mContext = context;
+ registerDeviceResource();
+ }
+
+ private void registerDeviceResource() {
+ try {
+ logMessage("RegisterDeviceResource " + DEVICE_URI + " : " + RESOURCE_TYPENAME);
+ mResourceHandle = OcPlatform.registerResource(
+ DEVICE_URI,
+ RESOURCE_TYPENAME,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DeviceResource");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * this is the main method which handles different incoming requests appropriately.
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ List<OcHeaderOption> headerOptions = ocResourceRequest.getHeaderOptions();
+ String clientAPIVersion = "";
+ String clientToken = "";
+ // search for header options map and look for API version and client token
+ for (OcHeaderOption headerOption : headerOptions) {
+ int optionId = headerOption.getOptionId();
+ if (API_VERSION_KEY == optionId) {
+ clientAPIVersion = headerOption.getOptionData();
+ logMessage(TAG + " Client API Version: " + clientAPIVersion);
+ } else if (CLIENT_VERSION_KEY == optionId) {
+ clientToken = headerOption.getOptionData();
+ logMessage(TAG + " Client Token: " + clientToken);
+ }
+ }
+ if (clientAPIVersion.equals(API_VERSION) &&
+ clientToken.equals(CLIENT_TOKEN)) {
+ List<OcHeaderOption> serverHeaderOptions = new LinkedList<>();
+ OcHeaderOption apiVersion = new OcHeaderOption(API_VERSION_KEY,
+ API_VERSION);
+ serverHeaderOptions.add(apiVersion);
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+ response.setHeaderOptions(serverHeaderOptions);
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
+ response.setResponseResult(EntityHandlerResult.OK);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DeviceResource");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ /**
+ * update state of device
+ *
+ * @return device representation
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DEVICE_NAME,
+ "Intel Powered 3 door, 1 light refrigerator");
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra("message", msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
- response.setErrorCode(SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * DoorResource
+ * <p/>
+ * Creates a door resource and performs actions based on the client requests
+ */
+public class DoorResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String DOOR_URI = "/door/";
+ public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+ private boolean mDoorState;
+ private String mSide;
+
+ /**
+ * Constructor
+ *
+ * @param side side of the door
+ * @param context to enable sending of broadcast messages to be displayed on the user screen
+ */
+ DoorResource(String side, Context context) {
+ mContext = context;
+ mSide = side;
+ registerDoorResource();
+ }
+
+ private void registerDoorResource() {
+ String resourceURI = DOOR_URI + mSide;
+ logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
+ try {
+ mResourceHandle = OcPlatform.registerResource(resourceURI,
+ RESOURCE_TYPEDOOR,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DoorResource");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * this is the main method which handles different incoming requests appropriately.
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
- response.setErrorCode(SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case PUT:
- response.setErrorCode(204);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case DELETE:
+ response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DoorResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ /**
+ * helper function to update the current value of the door resource
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
+ mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
+ logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
+ " and door side is " + mSide);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of doorResource, depending on if door is open/ closed
+ *
+ * @param representation new state of a door
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mDoorState = representation.getValue(DOOR_STATE_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ // Note, we won't let the user change the door side!
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private static String TAG = "DoorResource: ";
+
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra(FridgeServer.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
- response.setErrorCode(SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples.fridgeserver;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * LightResource
+ * <p/>
+ * Creates a light resource and performs actions based on the client requests
+ */
+public class LightResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String LIGHT_STATUS_KEY = "light";
+ public static final String LIGHT_URI = "/light";
+ public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
+ private boolean mIsLightOn = false;
+
+ /**
+ * constructor
+ *
+ * @param context to enable sending of broadcast messages to be displayed on the user screen
+ */
+ LightResource(Context context) {
+ mContext = context;
+ registerLightResource();
+ }
+
+ private void registerLightResource() {
+ try {
+ logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
+ mResourceHandle = OcPlatform.registerResource(LIGHT_URI,
+ RESOURCE_TYPELIGHT,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register LightResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * this is the main method which handles different incoming requests appropriately.
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
- response.setErrorCode(SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ case PUT:
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ }
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of LightResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ /**
+ * updates the current state of the light (on/ off)
+ *
+ * @return light is on or off
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of mIsOn from the representation
+ *
+ * @param representation get current state of light
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private static String TAG = "LightResource: ";
+
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra(FridgeServer.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
- response.setErrorCode(SUCCESS);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base.examples;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.ErrorCode;
+import org.iotivity.base.ObservationInfo;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.RequestType;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Light
+ * <p/>
+ * This class represents a light resource
+ */
+public class Light implements OcPlatform.EntityHandler {
+ private static final String NAME_KEY = "name";
+ private static final String STATE_KEY = "state";
+ private static final String POWER_KEY = "power";
+
+ private String mResourceUri; //resource URI
+ private String mResourceTypeName; //resource type name.
+ private String mResourceInterface; //resource interface.
+ private OcResourceHandle mResourceHandle; //resource handle
+
+ private String mName; //light name
+ private boolean mState; //light state
+ private int mPower; //light power
+
+ public Light(String resourceUri, String name, boolean state, int power) {
+ mResourceUri = resourceUri;
+ mResourceTypeName = "core.light";
+ mResourceInterface = OcPlatform.DEFAULT_INTERFACE;
+ mResourceHandle = null; //this is set when resource is registered
+
+ mName = name;
+ mState = state;
+ mPower = power;
+ }
+
+ public synchronized void registerResource() throws OcException {
+ if (null == mResourceHandle) {
+ mResourceHandle = OcPlatform.registerResource(
+ mResourceUri,
+ mResourceTypeName,
+ mResourceInterface,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE)
+ );
+ }
+ }
+
+ /**
+ * NOTE: This is just a sample implementation of entity handler. Entity handler can be
+ * implemented in several ways by the manufacturer.
+ *
+ * @param request
+ * @return
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(final OcResourceRequest request) {
+ EntityHandlerResult ehResult = EntityHandlerResult.ERROR;
+ if (null == request) {
+ msg("Server request is invalid");
+ return ehResult;
+ }
+ // Get the request flags
+ EnumSet<RequestHandlerFlag> requestFlags = request.getRequestHandlerFlagSet();
+ if (requestFlags.contains(RequestHandlerFlag.INIT)) {
+ msg("\t\tRequest Flag: Init");
+ ehResult = EntityHandlerResult.OK;
+ }
+ if (requestFlags.contains(RequestHandlerFlag.REQUEST)) {
+ msg("\t\tRequest Flag: Request");
+ ehResult = handleRequest(request);
+ }
+ if (requestFlags.contains(RequestHandlerFlag.OBSERVER)) {
+ msg("\t\tRequest Flag: Observer");
+ ehResult = handleObserver(request);
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handleRequest(OcResourceRequest request) {
+ EntityHandlerResult ehResult = EntityHandlerResult.ERROR;
+ // Check for query params (if any)
+ Map<String, String> queries = request.getQueryParameters();
+ if (!queries.isEmpty()) {
+ msg("Query processing is up to entityHandler");
+ } else {
+ msg("No query parameters in this request");
+ }
+
+ for (Map.Entry<String, String> entry : queries.entrySet()) {
+ msg("Query key: " + entry.getKey() + " value: " + entry.getValue());
+ }
+
+ //Get the request type
+ RequestType requestType = request.getRequestType();
+ switch (requestType) {
+ case GET:
+ msg("\t\t\tRequest Type is GET");
+ ehResult = handleGetRequest(request);
+ break;
+ case PUT:
+ msg("\t\t\tRequest Type is PUT");
+ ehResult = handlePutRequest(request);
+ break;
+ case POST:
+ msg("\t\t\tRequest Type is POST");
+ ehResult = handlePostRequest(request);
+ break;
+ case DELETE:
+ msg("\t\t\tRequest Type is DELETE");
+ ehResult = handleDeleteRequest();
+ break;
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handleGetRequest(final OcResourceRequest request) {
+ EntityHandlerResult ehResult;
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
+ if (mIsSlowResponse) { // Slow response case
+ new Thread(new Runnable() {
+ public void run() {
+ handleSlowResponse(request);
+ }
+ }).start();
+ ehResult = EntityHandlerResult.SLOW;
+ } else { // normal response case.
- response.setErrorCode(SUCCESS);
+ response.setResponseResult(EntityHandlerResult.OK);
+ response.setResourceRepresentation(getOcRepresentation());
+ ehResult = sendResponse(response);
+ }
+ return ehResult;
+ }
+
+ private EntityHandlerResult handlePutRequest(OcResourceRequest request) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
+ setOcRepresentation(request.getResourceRepresentation());
+ response.setResourceRepresentation(getOcRepresentation());
+ response.setResponseResult(EntityHandlerResult.OK);
- response.setErrorCode(SUCCESS);
+ return sendResponse(response);
+ }
+
+ private static int sUriCounter = 1;
+ private EntityHandlerResult handlePostRequest(OcResourceRequest request) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+ String newUri = "/a/light" + (++sUriCounter);
+ SimpleServer.createNewLightResource(newUri, "John's light " + sUriCounter);
+ OcRepresentation rep_post = getOcRepresentation();
+ try {
+ rep_post.setValue(OcResource.CREATED_URI_KEY, newUri);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ }
+ response.setResourceRepresentation(rep_post);
- response.setErrorCode(SUCCESS);
+ response.setNewResourceUri(newUri);
+ response.setResponseResult(EntityHandlerResult.RESOURCE_CREATED);
+ return sendResponse(response);
+ }
+
+ private EntityHandlerResult handleDeleteRequest() {
+ try {
+ this.unregisterResource();
+ return EntityHandlerResult.RESOURCE_DELETED;
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to unregister a light resource");
+ return EntityHandlerResult.ERROR;
+ }
+ }
+
+ private void handleSlowResponse(OcResourceRequest request) {
+ sleep(10);
+ msg("Sending slow response...");
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(request.getRequestHandle());
+ response.setResourceHandle(request.getResourceHandle());
+
- response.setErrorCode(SUCCESS);
+ response.setResponseResult(EntityHandlerResult.OK);
+ response.setResourceRepresentation(getOcRepresentation());
+ sendResponse(response);
+ }
+
+ private List<Byte> mObservationIds; //IDs of observes
+
+ private EntityHandlerResult handleObserver(final OcResourceRequest request) {
+ ObservationInfo observationInfo = request.getObservationInfo();
+ switch (observationInfo.getObserveAction()) {
+ case REGISTER:
+ if (null == mObservationIds) {
+ mObservationIds = new LinkedList<>();
+ }
+ mObservationIds.add(observationInfo.getOcObservationId());
+ break;
+ case UNREGISTER:
+ mObservationIds.remove((Byte)observationInfo.getOcObservationId());
+ break;
+ }
+ // Observation happens on a different thread in notifyObservers method.
+ // If we have not created the thread already, we will create one here.
+ if (null == mObserverNotifier) {
+ mObserverNotifier = new Thread(new Runnable() {
+ public void run() {
+ notifyObservers(request);
+ }
+ });
+ mObserverNotifier.start();
+ }
+ return EntityHandlerResult.OK;
+ }
+
+ private void notifyObservers(OcResourceRequest request) {
+ while (true) {
+ // increment current power value by 10 every 2 seconds
+ mPower += 10;
+ sleep(2);
+
+ msg("Notifying observers...");
+ msg(this.toString());
+ try {
+ if (mIsListOfObservers) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setResourceRepresentation(getOcRepresentation());
+ OcPlatform.notifyListOfObservers(
+ mResourceHandle,
+ mObservationIds,
+ response);
+ } else {
+ OcPlatform.notifyAllObservers(mResourceHandle);
+ }
+ } catch (OcException e) {
+ ErrorCode errorCode = e.getErrorCode();
+ if (ErrorCode.NO_OBSERVERS == errorCode) {
+ msg("No more observers, stopping notifications");
+ }
+ return;
+ }
+ }
+ }
+
+ private EntityHandlerResult sendResponse(OcResourceResponse response) {
+ try {
+ OcPlatform.sendResponse(response);
+ return EntityHandlerResult.OK;
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to send response");
+ return EntityHandlerResult.ERROR;
+ }
+ }
+
+ public synchronized void unregisterResource() throws OcException {
+ if (null != mResourceHandle) {
+ OcPlatform.unregisterResource(mResourceHandle);
+ }
+ }
+
+ public void setOcRepresentation(OcRepresentation rep) {
+ try {
+ if (rep.hasAttribute(NAME_KEY)) mName = rep.getValue(NAME_KEY);
+ if (rep.hasAttribute(STATE_KEY)) mState = rep.getValue(STATE_KEY);
+ if (rep.hasAttribute(POWER_KEY)) mPower = rep.getValue(POWER_KEY);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to get representation values");
+ }
+ }
+
+ public OcRepresentation getOcRepresentation() {
+ OcRepresentation rep = new OcRepresentation();
+ try {
+ rep.setValue(NAME_KEY, mName);
+ rep.setValue(STATE_KEY, mState);
+ rep.setValue(POWER_KEY, mPower);
+ } catch (OcException e) {
+ msgError(TAG, e.toString());
+ msg("Failed to set representation values");
+ }
+ return rep;
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+
+ public void setSlowResponse(boolean isSlowResponse) {
+ mIsSlowResponse = isSlowResponse;
+ }
+
+ public void useListOfObservers(boolean isListOfObservers) {
+ mIsListOfObservers = isListOfObservers;
+ }
+
+ @Override
+ public String toString() {
+ return "\t" + "URI" + ": " + mResourceUri +
+ "\n\t" + NAME_KEY + ": " + mName +
+ "\n\t" + STATE_KEY + ": " + mState +
+ "\n\t" + POWER_KEY + ": " + mPower;
+ }
+
+ private void sleep(int seconds) {
+ try {
+ Thread.sleep(seconds * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ msgError(TAG, e.toString());
+ }
+ }
+
+ private void msg(String text) {
+ SimpleServer.msg(text);
+ }
+
+ private void msgError(String tag, String text) {
+ SimpleServer.msgError(tag, text);
+ }
+
+ private final static String TAG = Light.class.getSimpleName();
+ private final static int SUCCESS = 200;
+ private boolean mIsSlowResponse = false;
+ private boolean mIsListOfObservers = false;
+ private Thread mObserverNotifier;
+}
--- /dev/null
- if (WITH_CLOUD == "0" || SECURED == "0") {\r
+/*\r
+ *******************************************************************\r
+ *\r
+ * Copyright 2015 Intel Corporation.\r
+ *\r
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+ */\r
+\r
+\r
+\r
+buildscript {\r
+ repositories {\r
+ jcenter()\r
+ }\r
+ dependencies {\r
+ classpath 'com.android.tools.build:gradle:1.3.0'\r
+\r
+ // NOTE: Do not place your application dependencies here; they belong\r
+ // in the individual module build.gradle files\r
+ }\r
+}\r
+\r
+allprojects {\r
+ repositories {\r
+ jcenter()\r
+ }\r
+}\r
+\r
+\r
+apply plugin: 'com.android.library'\r
+ \r
+android {\r
+ sourceSets {\r
+ main {\r
+ java {\r
+ srcDirs 'src/main/java', '../common/src/main/java'\r
+ }\r
+ manifest.srcFile 'src/main/AndroidManifest.xml'\r
+ jniLibs.srcDir "$buildDir/native-libs"\r
+ jni.srcDirs = [] //disable automatic ndk-build call\r
+ }\r
+ }\r
+\r
+ compileSdkVersion 21\r
+ buildToolsVersion "20.0.0"\r
+ archivesBaseName = "iotivity-base"\r
+\r
+ libraryVariants.all { variant ->\r
+ variant.outputs.each { output ->\r
+ def outputFile = output.outputFile\r
+ if (outputFile != null && outputFile.name.endsWith('.aar')) {\r
+ def fileName = "${archivesBaseName}-${TARGET_ARCH}-${RELEASE}.aar"\r
+ output.outputFile = new File(outputFile.parent, fileName)\r
+ }\r
+ }\r
+ }\r
+\r
+ defaultConfig {\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ versionCode 1\r
+ versionName "1.2.0"\r
+ buildConfigField 'int', 'SECURED', SECURED\r
+ buildConfigField 'int', 'WITH_TCP', WITH_TCP\r
+ buildConfigField 'int', 'WITH_CLOUD', WITH_CLOUD\r
+ buildConfigField "int", 'WITH_MQ_PUB', WITH_MQ_PUB\r
+ buildConfigField "int", 'WITH_MQ_SUB', WITH_MQ_SUB\r
+ buildConfigField "int", 'WITH_MQ_BROKER', WITH_MQ_BROKER\r
+ buildConfigField "String", 'RD_MODE', "\"RD_MODE\""\r
+ buildConfigField "int", 'WITH_TRANSPORT_EDR', WITH_TRANSPORT_EDR\r
+ buildConfigField "int", 'WITH_TRANSPORT_BLE', WITH_TRANSPORT_BLE\r
+ buildConfigField "int", 'WITH_TRANSPORT_NFC', WITH_TRANSPORT_NFC\r
+ }\r
+ buildTypes {\r
+ release {\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+ }\r
+ }\r
+\r
+ lintOptions {\r
+ abortOnError false\r
+ }\r
+\r
+ sourceSets {\r
+ main {\r
+ manifest.srcFile 'src/main/AndroidManifest.xml'\r
+ jniLibs.srcDir '$buildDir/native-libs'\r
+ jni.srcDirs = [] //disable automatic ndk-build call\r
+ java{\r
+ if (WITH_TRANSPORT_EDR == "0") {\r
+ exclude "**/ca/CaBtPairingInterface.java"\r
+ exclude "**/ca/CaEdrInterface.java"\r
+ println 'excluded EDR interface'\r
+ }\r
+ if (WITH_TRANSPORT_BLE == "0") {\r
+ exclude "**/ca/CaLeClientInterface.java"\r
+ exclude "**/ca/CaLeServerInterface.java"\r
+ println 'excluded BLE interface'\r
+ }\r
+ if (WITH_TRANSPORT_NFC == "0") {\r
+ exclude "**/ca/CaNfcInterface.java"\r
+ println 'excluded NFC interface'\r
+ }\r
++ if (WITH_TCP == "0" || SECURED == "0") {\r
+ exclude "**/base/OcCloudProvisioning.java"\r
+ println 'excluded secure files'\r
+ }\r
+ }\r
+ }\r
+ }\r
+}\r
+\r
+dependencies {\r
+ compile fileTree(dir: 'libs', include: ['*.jar'])\r
+}\r
+\r
+task copyNativeLibs(type: Copy) {\r
+ String[] libraries = [\r
+ 'libca-interface.so',\r
+ 'libconnectivity_abstraction.so',\r
+ 'libgnustl_shared.so',\r
+ 'liboc_logger.so',\r
+ 'liboc.so',\r
+ 'libocstack-jni.so',\r
+ 'liboctbstack.so'\r
+ ]\r
+ if ("$SECURED" == '1')\r
+ libraries += [\r
+ 'libocprovision.so',\r
+ 'libocpmapi.so'\r
+ ]\r
+ from(new File("$BUILD_DIR")) { include libraries }\r
+ into new File(buildDir, "native-libs/$TARGET_ARCH")\r
+}\r
+\r
+tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyNativeLibs }\r
+\r
+tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->\r
+ pkgTask.jniFolders = new HashSet<File>()\r
+ pkgTask.jniFolders.add(new File(buildDir, 'native-libs'))\r
+}\r
+\r
+task buildNative(type: Exec) {\r
+ if (System.env.ANDROID_NDK_HOME != null) {\r
+ //for windows use 'ndk-build.cmd'\r
+ //def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')\r
+ def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
+ commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", "SECURE=$SECURED", "WITH_CLOUD=$WITH_CLOUD", "RD_MODE=$RD_MODE", "WITH_MQ_PUB=$WITH_MQ_PUB", "WITH_MQ_SUB=$WITH_MQ_SUB", "WITH_MQ_BROKER=$WITH_MQ_BROKER", "WITH_TCP=$WITH_TCP"\r
+ } else {\r
+ println '##################'\r
+ println 'Skipping NDK build'\r
+ println 'Reason: ANDROID_NDK_HOME not set.'\r
+ println '##################'\r
+ }\r
+}\r
--- /dev/null
- ocResourceResponse.setErrorCode(200);
+/*
+ *******************************************************************
+ *
+ * Copyright 2015 Intel Corporation.
+ *
+ *-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ *
+ * 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.iotivity.base;
+
+import android.test.InstrumentationTestCase;
+import android.util.Log;
+
+import java.util.Arrays;
+import java.util.Date;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+public class SmokeTest extends InstrumentationTestCase {
+ private static final String TAG = "SmokeTest";
+ private Random rnd = new Random();
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ PlatformConfig cfg = new PlatformConfig(
+ getInstrumentation().getContext(),
+ ServiceType.IN_PROC,
+ ModeType.CLIENT_SERVER,
+ "0.0.0.0",
+ 0,
+ QualityOfService.LOW);
+
+ OcPlatform.Configure(cfg);
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testResourceRegisterUnregister() throws InterruptedException {
+ final String resourceType = "unit.test.resource" +
+ new Date().getTime();
+ final CountDownLatch signal = new CountDownLatch(1);
+
+ OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ return EntityHandlerResult.OK;
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ Log.i(TAG, "Host: " + resource.getHost());
+ Log.i(TAG, "Server ID: " + resource.getServerId());
+ Log.i(TAG, "Connectivity Types: ");
+ for (OcConnectivityType connectivityType : resource.getConnectivityTypeSet()) {
+ Log.i(TAG, " " + connectivityType);
+ }
+ signal.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ entityHandler,
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testStartStopListenForPresence() throws InterruptedException {
+ final String resourceType = "unit.test.resource" +
+ new Date().getTime();
+ final CountDownLatch signal = new CountDownLatch(1);
+
+ OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ return EntityHandlerResult.OK;
+ }
+ };
+
+ final OcPlatform.OnPresenceListener presenceListener = new OcPlatform.OnPresenceListener() {
+ @Override
+ public void onPresence(OcPresenceStatus ocPresenceStatus, int nonce, String hostAddress) {
+ Log.i(TAG, "onPresence status " + ocPresenceStatus.toString() + " nonce " + nonce);
+ signal.countDown();
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ try {
+ //client
+ OcPresenceHandle presenceHandle = OcPlatform.subscribePresence(
+ resource.getHost(),
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ presenceListener
+ );
+
+ //wait for onPresence event
+ assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+ //client
+ OcPlatform.unsubscribePresence(presenceHandle);
+ } catch (OcException e) {
+ assertTrue(false);
+ } catch (InterruptedException e) {
+ assertTrue(false);
+ }
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ entityHandler,
+ EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //server
++ //wait 2 seconds for the client's resourceFoundListener to set the presenceListener.
++ //the presenceListener must be set before startPresence() is called to get notified.
++ try {
++ Thread.sleep(2000);
++ } catch (InterruptedException e) {
++ Log.e(TAG, e.getMessage());
++ }
+ OcPlatform.startPresence(OcPlatform.DEFAULT_PRESENCE_TTL);
+
+ //wait for onPresence event
+ assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.stopPresence();
+
+ //client
+ OcPlatform.unregisterResource(resourceHandle);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testHandleGetRequest() throws InterruptedException {
+ final String someKey = "SomeKey";
+ final String someValue = "SomeValue";
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal1 = new CountDownLatch(1);
+ final CountDownLatch signal2 = new CountDownLatch(1);
+ final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+
+ //client
+ final OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
+ @Override
+ public void onGetCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+ if (!headerOptionList.isEmpty()) {
+ for (OcHeaderOption headerOption : headerOptionList) {
+ Log.i(TAG, "Header option " +
+ headerOption.getOptionId() +
+ " : " +
+ headerOption.getOptionData());
+ }
+ }
+ try {
+ Log.i(TAG, "Power: " + ocRepresentation.getValue("power"));
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ assertTrue(false);
+ }
+ signal2.countDown();
+ }
+
+ @Override
+ public void onGetFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ if (ErrorCode.NO_RESOURCE != errCode) {
+ Log.e(TAG, ocEx.getMessage());
+ assertTrue(false);
+ }
+ } else {
+ Log.e(TAG, ex.getMessage());
+ assertTrue(false);
+ }
+ }
+ };
+
+ //client
+ final OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ Map<String, String> queryParamsMap = new HashMap<String, String>();
+ queryParamsMap.put(someKey, someValue);
+
+ ocResourceList.add(resource);
+ try {
+ resource.get(queryParamsMap, onGetListener);
+// TODO there is a bug in the stack that prevents the usage of the following APIs
+// resource.get(resourceType, OcPlatform.DEFAULT_INTERFACE, queryParamsMap,
+// onGetListener);
+//
+// resource.get(queryParamsMap, onGetListener, QualityOfService.LOW);
+//
+// resource.get(resourceType, OcPlatform.DEFAULT_INTERFACE,queryParamsMap,
+// onGetListener, QualityOfService.LOW);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ assertTrue(false);
+ }
+ signal1.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ new OcPlatform.EntityHandler() {
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EnumSet<RequestHandlerFlag> handlerFlagSet =
+ ocResourceRequest.getRequestHandlerFlagSet();
+
+ RequestType requestType = ocResourceRequest.getRequestType();
+
+ if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse ocResourceResponse = new OcResourceResponse();
+ ocResourceResponse.setRequestHandle(
+ ocResourceRequest.getRequestHandle());
+ ocResourceResponse.setResourceHandle(
+ ocResourceRequest.getResourceHandle());
+
+ switch (requestType) {
+ case GET:
+ Map<String, String> queryParams =
+ ocResourceRequest.getQueryParameters();
+
+ if (!(queryParams.containsKey(someKey) &&
+ someValue.equals(queryParams.get(someKey)))) {
+ assertTrue(false);
+ }
+
- ocResourceResponse.setErrorCode(200);
+ ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
+ ocResourceResponse.setResourceRepresentation(
+ getRepresentation(74));
+ break;
+ }
+
+ try {
+ OcPlatform.sendResponse(ocResourceResponse);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+ }
+ return EntityHandlerResult.OK;
+ }
+ },
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource(null,
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+ //wait for onGetCompleted event
+ assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testHandlePutRequest() throws InterruptedException {
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal1 = new CountDownLatch(1);
+ final CountDownLatch signal2 = new CountDownLatch(3);
+ final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+
+ final OcResource.OnPutListener onPutListener = new OcResource.OnPutListener() {
+ @Override
+ public void onPutCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+ if (!headerOptionList.isEmpty()) {
+ for (OcHeaderOption headerOption : headerOptionList) {
+ Log.i(TAG, "Header option " +
+ headerOption.getOptionId() +
+ " : " +
+ headerOption.getOptionData());
+ }
+ }
+ try {
+ Log.i(TAG, "onPutCompleted Power: " + ocRepresentation.getValue("power"));
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ Log.i(TAG, "onPutCompleted Uri: " + ocRepresentation.getUri());
+ signal2.countDown();
+ }
+
+ @Override
+ public void onPutFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ if (ErrorCode.NO_RESOURCE != errCode) {
+ Log.e(TAG, ocEx.getMessage());
+ assertTrue(false);
+ }
+ } else {
+ Log.e(TAG, ex.getMessage());
+ assertTrue(false);
+ }
+ }
+ };
+
+ final OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ ocResourceList.add(resource);
+ try {
+ resource.put(
+ getRepresentation(),
+ new HashMap<String, String>(),
+ onPutListener);
+
+ resource.put(
+ getRepresentation(),
+ new HashMap<String, String>(),
+ onPutListener);
+
+ resource.put(
+ getRepresentation(),
+ new HashMap<String, String>(),
+ new OcResource.OnPutListener() {
+ @Override
+ public void onPutCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+ signal2.countDown();
+ }
+
+ @Override
+ public void onPutFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ if (ErrorCode.NO_RESOURCE != errCode) {
+ Log.e(TAG, ocEx.getMessage());
+ assertTrue(false);
+ }
+ } else {
+ Log.e(TAG, ex.getMessage());
+ assertTrue(false);
+ }
+ }
+ });
+
+ } catch (OcException e) {
+ assertTrue(false);
+ }
+ signal1.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ new OcPlatform.EntityHandler() {
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EnumSet<RequestHandlerFlag> handlerFlagSet = ocResourceRequest.getRequestHandlerFlagSet();
+ RequestType requestType = ocResourceRequest.getRequestType();
+
+ if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse ocResourceResponse = new OcResourceResponse();
+ ocResourceResponse.setRequestHandle(
+ ocResourceRequest.getRequestHandle());
+ ocResourceResponse.setResourceHandle(
+ ocResourceRequest.getResourceHandle());
+
+ switch (requestType) {
+ case GET:
+ assertTrue(false);
+ break;
+ case PUT:
+ OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
+ try {
+ Log.i(TAG, "Put res. power: " + rep.getValue("power"));
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ assertTrue(false);
+ }
+ Log.i(TAG, "URI: " + rep.getUri());
+
+ ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
- ocResourceResponse.setErrorCode(200);
+ ocResourceResponse.setResourceRepresentation(rep);
+ break;
+ case POST:
+ assertTrue(false);
+ break;
+ case DELETE:
+ break;
+ }
+
+ try {
+ OcPlatform.sendResponse(ocResourceResponse);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+ }
+ return EntityHandlerResult.OK;
+ }
+ },
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+ //wait for onGetCompleted event
+ assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testHandlePostRequest() throws InterruptedException {
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal1 = new CountDownLatch(1);
+ final CountDownLatch signal2 = new CountDownLatch(3);
+ final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+
+ final OcResource.OnPostListener onPostListener = new OcResource.OnPostListener() {
+ @Override
+ public void onPostCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+ if (!headerOptionList.isEmpty()) {
+ for (OcHeaderOption headerOption : headerOptionList) {
+ Log.i(TAG, "Header option " +
+ headerOption.getOptionId() +
+ " : " +
+ headerOption.getOptionData());
+ }
+ }
+ try {
+ Log.i(TAG, "onPostCompleted Power: " + ocRepresentation.getValue("power"));
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ assertTrue(false);
+ }
+ Log.i(TAG, "onPostCompleted Uri: " + ocRepresentation.getUri());
+ signal2.countDown();
+ }
+
+ @Override
+ public void onPostFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ if (ErrorCode.NO_RESOURCE != errCode) {
+ Log.e(TAG, ocEx.getMessage());
+ assertTrue(false);
+ }
+ } else {
+ Log.e(TAG, ex.getMessage());
+ assertTrue(false);
+ }
+ }
+ };
+
+ final OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ ocResourceList.add(resource);
+ try {
+ resource.post(
+ getRepresentation(),
+ new HashMap<String, String>(),
+ onPostListener);
+
+ resource.post(
+ getRepresentation(),
+ new HashMap<String, String>(),
+ onPostListener);
+
+ resource.post(
+ getRepresentation(),
+ new HashMap<String, String>(),
+ new OcResource.OnPostListener() {
+ @Override
+ public void onPostCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation ocRepresentation) {
+ signal2.countDown();
+ }
+
+ @Override
+ public void onPostFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ if (ErrorCode.NO_RESOURCE != errCode) {
+ Log.e(TAG, ocEx.getMessage());
+ assertTrue(false);
+ }
+ } else {
+ Log.e(TAG, ex.getMessage());
+ assertTrue(false);
+ }
+ }
+ });
+
+ } catch (OcException e) {
+ assertTrue(false);
+ }
+ signal1.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ new OcPlatform.EntityHandler() {
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EnumSet<RequestHandlerFlag> handlerFlagSet = ocResourceRequest.getRequestHandlerFlagSet();
+ RequestType requestType = ocResourceRequest.getRequestType();
+
+ if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse ocResourceResponse = new OcResourceResponse();
+ ocResourceResponse.setRequestHandle(
+ ocResourceRequest.getRequestHandle());
+ ocResourceResponse.setResourceHandle(
+ ocResourceRequest.getResourceHandle());
+
+ switch (requestType) {
+ case GET:
+ assertTrue(false);
+ break;
+ case PUT:
+ assertTrue(false);
+ break;
+ case POST:
+ OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
+ try {
+ Log.i(TAG, "Post res. power: " + rep.getValue("power"));
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ assertTrue(false);
+ }
+ Log.i(TAG, "URI: " + rep.getUri());
+
- ocResourceResponse.setErrorCode(200);
+ ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
+ ocResourceResponse.setResourceRepresentation(
+ getRepresentation(44));
+
+ break;
+ case DELETE:
+ assertTrue(false);
+ break;
+ }
+
+ try {
+ OcPlatform.sendResponse(ocResourceResponse);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+ }
+ return EntityHandlerResult.OK;
+ }
+ },
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+ //wait for onPostCompleted event
+ assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+
+ }
+
+ public void testHandleDeleteRequest() throws InterruptedException {
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal1 = new CountDownLatch(1);
+ final CountDownLatch signal2 = new CountDownLatch(1);
+ final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+
+ final OcResource.OnDeleteListener onDeleteListener = new OcResource.OnDeleteListener() {
+ @Override
+ public void onDeleteCompleted(List<OcHeaderOption> headerOptionList) {
+ signal2.countDown();
+ }
+
+ @Override
+ public void onDeleteFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ if (ErrorCode.NO_RESOURCE != errCode) {
+ Log.e(TAG, ocEx.getMessage());
+ assertTrue(false);
+ }
+ } else {
+ Log.e(TAG, ex.getMessage());
+ assertTrue(false);
+ }
+ }
+ };
+
+ final OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ ocResourceList.add(resource);
+ try {
+ resource.deleteResource(onDeleteListener);
+ } catch (OcException e) {
+ assertTrue(false);
+ }
+ signal1.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ new OcPlatform.EntityHandler() {
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EnumSet<RequestHandlerFlag> handlerFlagSet =
+ ocResourceRequest.getRequestHandlerFlagSet();
+ RequestType requestType = ocResourceRequest.getRequestType();
+
+ if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse ocResourceResponse = new OcResourceResponse();
+ ocResourceResponse.setRequestHandle(
+ ocResourceRequest.getRequestHandle());
+ ocResourceResponse.setResourceHandle(
+ ocResourceRequest.getResourceHandle());
+
+ switch (requestType) {
+ case DELETE:
- ocResourceResponse.setErrorCode(200);
+ ocResourceResponse.setResponseResult(
+ EntityHandlerResult.RESOURCE_DELETED);
+ break;
+ }
+
+ try {
+ OcPlatform.sendResponse(ocResourceResponse);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+ }
+ return EntityHandlerResult.OK;
+ }
+ },
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+ //wait for onDeleteCompleted event
+ assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testHandleGetPutPostDeleteFailures() throws InterruptedException {
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal1 = new CountDownLatch(1);
+ final CountDownLatch signal2 = new CountDownLatch(1);
+ final CountDownLatch signal3 = new CountDownLatch(1);
+ final CountDownLatch signal4 = new CountDownLatch(1);
+ final CountDownLatch signal5 = new CountDownLatch(1);
+
+ final List<OcResource> ocResourceList = new LinkedList<OcResource>();
+ final OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
+ @Override
+ public void onGetCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ assertTrue(false);
+ }
+
+ @Override
+ public void onGetFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ }
+ Log.i(TAG, ex.toString());
+ signal2.countDown();
+ }
+ };
+
+ final OcResource.OnPutListener onPutListener = new OcResource.OnPutListener() {
+ @Override
+ public void onPutCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ assertTrue(false);
+ }
+
+ @Override
+ public void onPutFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ }
+ Log.i(TAG, ex.toString());
+ signal3.countDown();
+ }
+ };
+ final OcResource.OnPostListener onPostListener = new OcResource.OnPostListener() {
+ @Override
+ public void onPostCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ assertTrue(false);
+ }
+
+ @Override
+ public void onPostFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ }
+ Log.i(TAG, ex.toString());
+ signal4.countDown();
+ }
+ };
+
+ final OcResource.OnDeleteListener onDeleteListener = new OcResource.OnDeleteListener() {
+ @Override
+ public void onDeleteCompleted(List<OcHeaderOption> headerOptionList) {
+ assertTrue(false);
+ }
+
+ @Override
+ public void onDeleteFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ }
+ Log.i(TAG, ex.toString());
+ signal5.countDown();
+ }
+ };
+
+ final OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ ocResourceList.add(resource);
+ try {
+ resource.get(new HashMap<String, String>(), onGetListener);
+ resource.put(new OcRepresentation(), new HashMap<String, String>(),
+ onPutListener);
+ resource.post(new OcRepresentation(), new HashMap<String, String>(),
+ onPostListener);
+ resource.deleteResource(onDeleteListener);
+ } catch (OcException e) {
+ assertTrue(false);
+ }
+ signal1.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ new OcPlatform.EntityHandler() {
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EnumSet<RequestHandlerFlag> handlerFlagSet =
+ ocResourceRequest.getRequestHandlerFlagSet();
+ RequestType requestType = ocResourceRequest.getRequestType();
+
+ if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse ocResourceResponse = new OcResourceResponse();
+ ocResourceResponse.setRequestHandle(
+ ocResourceRequest.getRequestHandle());
+ ocResourceResponse.setResourceHandle(
+ ocResourceRequest.getResourceHandle());
+
+ switch (requestType) {
+ case GET:
- ocResourceResponse.setErrorCode(200);
+ ocResourceResponse.setResponseResult(
+ EntityHandlerResult.ERROR);
+ break;
+ case PUT:
- ocResourceResponse.setErrorCode(200);
- ocResourceResponse.setResponseResult(
+ ocResourceResponse.setResponseResult(
+ EntityHandlerResult.ERROR);
+ break;
+ case POST:
- ocResourceResponse.setErrorCode(200);
++ ocResourceResponse.setResponseResult(
+ EntityHandlerResult.ERROR);
+ break;
+ case DELETE:
- ocResourceResponse.setErrorCode(200);
+ ocResourceResponse.setResponseResult(
+ EntityHandlerResult.ERROR);
+ break;
+ }
+ try {
+ OcPlatform.sendResponse(ocResourceResponse);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+ }
+ return EntityHandlerResult.OK;
+ }
+ },
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal1.await(60, TimeUnit.SECONDS));
+ //wait for onGetCompleted event
+ assertTrue(signal2.await(60, TimeUnit.SECONDS));
+ //wait for onPutCompleted event
+ assertTrue(signal3.await(60, TimeUnit.SECONDS));
+ //wait for onPostCompleted event
+ assertTrue(signal4.await(60, TimeUnit.SECONDS));
+ //wait for onDeleteCompleted event
+ assertTrue(signal5.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testPlatformInfo() throws InterruptedException {
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal = new CountDownLatch(1);
+
+ OcPlatform.OnPlatformFoundListener platformFoundListener = new OcPlatform.OnPlatformFoundListener() {
+ @Override
+ public void onPlatformFound(OcRepresentation ocRepresentation) {
+ Log.i(TAG, "Platform Info Received: ");
+ Log.i(TAG, "URI: " + ocRepresentation.getUri());
+ signal.countDown();
+ }
+ };
+
+ OcPlatformInfo platformInfo = null;
+
+ platformInfo = new OcPlatformInfo("myPlatformID", "myManuName", "myManuUrl");
+
+ platformInfo.setModelNumber("myModelNumber");
+ platformInfo.setDateOfManufacture("myDateOfManufacture");
+ platformInfo.setPlatformVersion("myPlatformVersion");
+ platformInfo.setOperatingSystemVersion("myOperatingSystemVersion");
+ platformInfo.setHardwareVersion("myHardwareVersion");
+ platformInfo.setFirmwareVersion("myFirmwareVersion");
+ platformInfo.setSupportUrl("mySupportUrl");
+ platformInfo.setSystemTime("mySystemTime");
+
+ try {
+ //server
+ OcPlatform.registerPlatformInfo(platformInfo);
+
+ //client
+ OcPlatform.getPlatformInfo(
+ "",
+ OcPlatform.WELL_KNOWN_PLATFORM_QUERY,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ platformFoundListener);
+
+ //wait for onPlatformFound event
+ assertTrue(signal.await(60, TimeUnit.SECONDS));
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage() + platformInfo.toString());
+ assertTrue(false);
+ }
+ }
+
+ public void testRegisterDeviceInfoGetDeviceInfo() throws InterruptedException {
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal = new CountDownLatch(1);
+
+ OcPlatform.OnDeviceFoundListener deviceFoundListener = new OcPlatform.OnDeviceFoundListener() {
+ @Override
+ public void onDeviceFound(OcRepresentation ocRepresentation) {
+ try {
+ Log.i(TAG, "Device Name: " + ocRepresentation.getValue("n"));
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ assertTrue(false);
+ }
+ boolean hasDeviceNameAtr = ocRepresentation.hasAttribute("n");
+ assertTrue(hasDeviceNameAtr);
+ boolean hasNonExistingAtr = ocRepresentation.hasAttribute("NonExisting");
+ assertFalse(hasNonExistingAtr);
+ Log.i(TAG, "URI: " + ocRepresentation.getUri());
+ signal.countDown();
+ }
+ };
+
+ OcDeviceInfo devInfo = new OcDeviceInfo(
+ "myDeviceName",
+ Arrays.asList(new String[]{"oic.d.test"})
+ );
+
+ try {
+ //server
+ OcPlatform.registerDeviceInfo(devInfo);
+ //client
+ OcPlatform.getDeviceInfo(
+ "",
+ OcPlatform.WELL_KNOWN_DEVICE_QUERY,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ deviceFoundListener);
+
+ //wait for onDeviceFound event
+ assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testBindUnbindResources() throws InterruptedException {
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal1 = new CountDownLatch(3);
+ final CountDownLatch signal2 = new CountDownLatch(2);
+ final CountDownLatch signal3 = new CountDownLatch(1);
+ final CountDownLatch signal4 = new CountDownLatch(3);
+ final CountDownLatch signal5 = new CountDownLatch(3);
+ final CountDownLatch signal6 = new CountDownLatch(1);
+
+ OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ return EntityHandlerResult.OK;
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener1 = new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ signal1.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener2 = new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ signal2.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener3 = new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ signal3.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener4 = new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ signal4.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener5 = new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ signal5.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener6 = new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ signal6.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+
+ //server
+ OcResourceHandle resourceHandleCollection = OcPlatform.registerResource(
+ "/a/unittest1",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ entityHandler,
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ OcResourceHandle resourceHandle1 = OcPlatform.registerResource(
+ "/a/unittest2",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ entityHandler,
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ OcResourceHandle resourceHandle2 = OcPlatform.registerResource(
+ "/a/unittest3",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ entityHandler,
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener1);
+
+ //wait for onResourceFound event to find 3 registered resources
+ assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.bindResource(resourceHandleCollection, resourceHandle1);
+ OcPlatform.bindResource(resourceHandleCollection, resourceHandle2);
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener3);
+
+ //wait for onResourceFound event to find 1 collection resources
+ assertTrue(signal3.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unbindResource(resourceHandleCollection, resourceHandle1);
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener2);
+
+ //wait for onResourceFound event to find 2 resources
+ assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unbindResource(resourceHandleCollection, resourceHandle2);
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener4);
+
+ //wait for onResourceFound event to find 3 registered resources
+ assertTrue(signal4.await(60, TimeUnit.SECONDS));
+
+ //Bind/unbind a list of resource handles
+ List<OcResourceHandle> resourceHandleList = new LinkedList<OcResourceHandle>();
+ resourceHandleList.add(resourceHandle1);
+ resourceHandleList.add(resourceHandle2);
+ OcPlatform.bindResources(resourceHandleCollection, resourceHandleList);
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener6);
+
+ //wait for onResourceFound event to find 1 collection resources
+ assertTrue(signal6.await(60, TimeUnit.SECONDS));
+
+ OcPlatform.unbindResources(resourceHandleCollection, resourceHandleList);
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener5);
+
+ //wait for onResourceFound event to find 1 collection resources
+ assertTrue(signal5.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandleCollection);
+ OcPlatform.unregisterResource(resourceHandle1);
+ OcPlatform.unregisterResource(resourceHandle2);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testResourceMethods() throws InterruptedException {
+ final String resourceType1 = "unit.test.resource" + new Date().getTime();
+ final String resourceType2 = "unit.test.resource" + new Date().getTime();
+
+ final CountDownLatch signal = new CountDownLatch(2);
+ final List<OcResource> resourceList = new LinkedList<>();
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public synchronized void onResourceFound(OcResource resource) {
+ resourceList.add(resource);
+ Log.i(TAG, "Host: " + resource.getHost());
+ Log.i(TAG, "Uri: " + resource.getUri());
+ Log.i(TAG, "Observable: " + resource.isObservable());
+
+ assertFalse(resource.getResourceTypes().isEmpty());
+ for (String resourceType : resource.getResourceTypes()) {
+ Log.i(TAG, "Type: " + resourceType);
+ }
+
+ assertFalse(resource.getResourceTypes().isEmpty());
+ for (String resourceInterface : resource.getResourceInterfaces()) {
+ Log.i(TAG, "Interface: " + resourceInterface);
+ }
+
+ List<OcHeaderOption> headerOptionList = new LinkedList<OcHeaderOption>();
+ headerOptionList.add(new OcHeaderOption(2885, "OptionData1"));
+ headerOptionList.add(new OcHeaderOption(2886, "OptionData2"));
+
+ try {
+ resource.setHeaderOptions(headerOptionList);
+ } catch (OcException e) {
+ Log.e(TAG, "onResourceFound, error in setHeaderOptions -- " + e.getMessage());
+ }
+
+ resource.unsetHeaderOptions();
+
+ OcResourceIdentifier resourceIdentifier = resource.getUniqueIdentifier();
+ OcResourceIdentifier resourceIdentifier2 = resource.getUniqueIdentifier();
+ assertTrue(resourceIdentifier.equals(resourceIdentifier2));
+
+ signal.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+ //server
+ OcResourceHandle resourceHandle1 = OcPlatform.registerResource(
+ "/a/unittest1",
+ resourceType1,
+ OcPlatform.DEFAULT_INTERFACE,
+ null,
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ OcResourceHandle resourceHandle2 = OcPlatform.registerResource(
+ "/a/unittest2",
+ resourceType2,
+ OcPlatform.DEFAULT_INTERFACE,
+ null,
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType1,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType2,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+ assertTrue(2 == resourceList.size());
+
+ OcResource res0 = resourceList.get(0);
+ OcResource res1 = resourceList.get(1);
+ assertFalse(res0.getUniqueIdentifier().equals(res1.getUniqueIdentifier()));
+ assertTrue(res0.getUniqueIdentifier().equals(res0.getUniqueIdentifier()));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle1);
+ OcPlatform.unregisterResource(resourceHandle2);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testCreateResourceProxy() throws InterruptedException {
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+ final CountDownLatch signal = new CountDownLatch(1);
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+
+ try {
+ //client: construct resource proxy
+ OcResource resourceProxy = OcPlatform.constructResourceObject(
+ resource.getHost(),
+ resource.getUri(),
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resource.isObservable(),
+ resource.getResourceTypes(),
+ resource.getResourceInterfaces());
+
+ //client: register resource proxy
+ OcResourceHandle resourceProxyHandle =
+ OcPlatform.registerResource(resourceProxy);
+
+ OcPlatform.unregisterResource(resourceProxyHandle);
+ } catch (OcException e) {
+ assertTrue(false);
+ }
+ signal.countDown();
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ null,
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ null,
+ EnumSet.of(ResourceProperty.DISCOVERABLE)
+ );
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ public void testObserveClientServer() throws InterruptedException {
+ final int NUM_OBSERVES = 20;
+ final Timer timer = new Timer();
+ final List<OcResource> resourceList = new LinkedList<OcResource>();
+ final List<OcResourceHandle> resourceHandleList = new LinkedList<OcResourceHandle>();
+ final CountDownLatch signal1 = new CountDownLatch(1);
+ final CountDownLatch signal2 = new CountDownLatch(NUM_OBSERVES);
+ final CountDownLatch signal3 = new CountDownLatch(1);
+
+ final String resourceType = "unit.test.resource" + new Date().getTime();
+
+ final OcResource.OnObserveListener observeListener = new OcResource.OnObserveListener() {
+ @Override
+ public void onObserveCompleted(
+ List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation,
+ int sequenceNumber) {
+
+ try {
+ Log.i(TAG, "Observe #" + sequenceNumber + " power: " +
+ ocRepresentation.getValue("power"));
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ assertTrue(false);
+ }
+ signal2.countDown();
+ }
+
+ @Override
+ public void onObserveFailed(Throwable ex) {
+ if (ex instanceof OcException) {
+ OcException ocEx = (OcException) ex;
+ ErrorCode errCode = ocEx.getErrorCode();
+ }
+ Log.e(TAG, ex.toString());
+ assertTrue(false);
+ }
+ };
+
+ final List<Byte> observationIdList = new LinkedList<Byte>();
+ OcPlatform.EntityHandler entityHandler = new OcPlatform.EntityHandler() {
+ @Override
+ public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EnumSet<RequestHandlerFlag> handlerFlagSet = ocResourceRequest.getRequestHandlerFlagSet();
+ RequestType requestType = ocResourceRequest.getRequestType();
+
+ if (handlerFlagSet.contains(RequestHandlerFlag.INIT)) {
+
+ }
+ if (handlerFlagSet.contains(RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse ocResourceResponse = new OcResourceResponse();
+ ocResourceResponse.setRequestHandle(ocResourceRequest.getRequestHandle());
+ ocResourceResponse.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (requestType) {
+ case GET:
+ ocResourceResponse.setResponseResult(EntityHandlerResult.OK);
+ ocResourceResponse.setResourceRepresentation(
+ getRepresentation(
+ rnd.nextInt(100)));
+ try {
+ OcPlatform.sendResponse(ocResourceResponse);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ break;
+ }
+ }
+
+ if (handlerFlagSet.contains(RequestHandlerFlag.OBSERVER)) {
+ ObservationInfo observationInfo = ocResourceRequest.getObservationInfo();
+
+ switch (observationInfo.getObserveAction()) {
+ case REGISTER:
+ synchronized (observationIdList) {
+ observationIdList.add(observationInfo.getOcObservationId());
+ timer.schedule(new TimerTask() {
+ int numNotified = 1;
+
+ @Override
+ public void run() {
+ if (0 < resourceHandleList.size()) {
+ synchronized (observationIdList) {
+ if (numNotified > NUM_OBSERVES) {
+ timer.cancel();
+ timer.purge();
+ signal3.countDown();
+ } else {
+ try {
+ OcPlatform.notifyAllObservers(
+ resourceHandleList.get(0));
+ } catch (OcException e) {
+ if (ErrorCode.NO_OBSERVERS == e.getErrorCode()) {
+ timer.cancel();
+ timer.purge();
+ signal3.countDown();
+ }
+ Log.e(TAG, e.getMessage());
+ }
+ numNotified++;
+ }
+ }
+ }
+
+ }
+ }, 0, 100);
+ }
+ break;
+ case UNREGISTER:
+ //TODO unregister isn't implemented in C++ API, yet
+ synchronized (observationIdList) {
+ timer.cancel();
+ break;
+ }
+ }
+ }
+ return EntityHandlerResult.OK;
+ }
+ };
+
+ OcPlatform.OnResourceFoundListener resourceFoundListener =
+ new OcPlatform.OnResourceFoundListener() {
+ @Override
+ public void onResourceFound(OcResource resource) {
+ resourceList.add(resource);
+ if (resource.isObservable()) {
+ try {
+ resource.observe(
+ ObserveType.OBSERVE,
+ new HashMap<String, String>(),
+ observeListener);
+
+ signal1.countDown();
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+ }
+
+ @Override
+ public void onFindResourceFailed(Throwable ex, String uri) {
+ Log.i(TAG, "Find Resource Failed for Uri: " + uri + " Error: " + ex.getMessage());
+ }
+ };
+ try {
+ //server
+ OcResourceHandle resourceHandle = OcPlatform.registerResource(
+ "/a/unittest",
+ resourceType,
+ OcPlatform.DEFAULT_INTERFACE,
+ entityHandler,
+ EnumSet.of(ResourceProperty.DISCOVERABLE, ResourceProperty.OBSERVABLE)
+ );
+
+ resourceHandleList.add(resourceHandle);
+
+ //client
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + resourceType,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ resourceFoundListener);
+
+ //wait for onResourceFound event
+ assertTrue(signal1.await(60, TimeUnit.SECONDS));
+
+ //wait for OnObserveListener event to observe 20 values
+ assertTrue(signal2.await(60, TimeUnit.SECONDS));
+
+ if (resourceList.size() > 0) {
+ OcResource resource = resourceList.get(0);
+ if (resource.isObservable()) {
+ resource.cancelObserve();
+ }
+ }
+
+ //wait for server to finish
+ assertTrue(signal3.await(60, TimeUnit.SECONDS));
+
+ //server
+ OcPlatform.unregisterResource(resourceHandle);
+
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ assertTrue(false);
+ }
+ }
+
+ private OcRepresentation getRepresentation(int value) {
+ OcRepresentation rep = new OcRepresentation();
+ try {
+ rep.setValue("power", value);
+ } catch (OcException e) {
+ Log.e(TAG, e.toString());
+ assertTrue(false);
+ }
+ return rep;
+ }
+
+ private OcRepresentation getRepresentation() {
+ return getRepresentation(74);
+ }
+}
--- /dev/null
- void JniOcResourceResponse::setErrorCode(const int eCode)
- {
- this->m_response->setErrorCode(eCode);
- }
-
+/*
+* //******************************************************************
+* //
+* // Copyright 2015 Intel Corporation.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // 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.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+#include "JniOcResourceResponse.h"
+#include "OCResourceResponse.h"
+#include "JniOcRepresentation.h"
+#include "JniOcRequestHandle.h"
+#include "JniOcResourceHandle.h"
+#include "JniUtils.h"
+
+using namespace OC;
+
+JniOcResourceResponse::JniOcResourceResponse
+(std::shared_ptr<OCResourceResponse> resourceResponse)
+: m_response(resourceResponse)
+{
+}
+
+JniOcResourceResponse::~JniOcResourceResponse()
+{
+}
+
- /*
- * Class: org_iotivity_base_OcResourceResponse
- * Method: setErrorCode
- * Signature: (I)V
- */
- JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setErrorCode
- (JNIEnv *env, jobject thiz, jint eCode)
- {
- LOGD("OcResourceResponse_setErrorCode");
- JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
- if (!response)
- {
- return;
- }
- response->setErrorCode(static_cast<int>(eCode));
- }
+std::string JniOcResourceResponse::getNewResourceUri(void)
+{
+ return this->m_response->getNewResourceUri();
+}
+
+void
+JniOcResourceResponse::setNewResourceUri(const std::string newResourceUri)
+{
+ this->m_response->setNewResourceUri(newResourceUri);
+}
+
+void JniOcResourceResponse::setHeaderOptions(const HeaderOptions& headerOptions)
+{
+ this->m_response->setHeaderOptions(headerOptions);
+}
+
+void JniOcResourceResponse::setRequestHandle(const OCRequestHandle& requestHandle)
+{
+ this->m_response->setRequestHandle(requestHandle);
+}
+
+void JniOcResourceResponse::setResourceHandle(const OCResourceHandle& resourceHandle)
+{
+ this->m_response->setResourceHandle(resourceHandle);
+}
+
+void JniOcResourceResponse::setResponseResult(const OCEntityHandlerResult& responseResult)
+{
+ this->m_response->setResponseResult(responseResult);
+}
+
+void JniOcResourceResponse::setResourceRepresentation(OCRepresentation& rep,
+ std::string interfaceStr)
+{
+ this->m_response->setResourceRepresentation(rep, interfaceStr);
+}
+
+void JniOcResourceResponse::setResourceRepresentation(OCRepresentation& rep)
+{
+ this->m_response->setResourceRepresentation(rep);
+}
+
+std::shared_ptr<OCResourceResponse> JniOcResourceResponse::getOCResourceResponse()
+{
+ return this->m_response;
+}
+
+JniOcResourceResponse* JniOcResourceResponse::getJniOcResourceResponsePtr
+(JNIEnv *env, jobject thiz)
+{
+ JniOcResourceResponse *request = GetHandle<JniOcResourceResponse>(env, thiz);
+ if (env->ExceptionCheck())
+ {
+ LOGE("Failed to get native handle from JniOcResourceResponse");
+ }
+ if (!request)
+ {
+ ThrowOcException(JNI_NO_NATIVE_POINTER, "");
+ }
+ return request;
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: getNewResourceUri
+* Signature: ()Ljava/lang/String;
+*/
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceResponse_getNewResourceUri
+(JNIEnv *env, jobject thiz)
+{
+ LOGD("OcResourceResponse_getNewResourceUri");
+ JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
+ if (!response)
+ {
+ return nullptr;
+ }
+ return env->NewStringUTF(response->getNewResourceUri().c_str());
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: setNewResourceUri
+* Signature: (Ljava/lang/String;)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setNewResourceUri
+(JNIEnv *env, jobject thiz, jstring jstr)
+{
+ LOGD("OcResourceResponse_setNewResourceUri");
+ JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
+ if (!response)
+ {
+ return;
+ }
+ response->setNewResourceUri(env->GetStringUTFChars(jstr, 0));
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: setHeaderOptions
+* Signature: (Ljava/util/List;)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setHeaderOptions
+(JNIEnv *env, jobject thiz, jobjectArray jHeaderOptions)
+{
+ LOGD("OcResourceResponse_setHeaderOptions");
+ if (!jHeaderOptions)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "headerOptionList cannot be null");
+ return;
+ }
+ JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
+ if (!jniResponse)
+ {
+ return;
+ }
+ HeaderOptions headerOptions;
+ JniUtils::convertJavaHeaderOptionsArrToVector(env, jHeaderOptions, headerOptions);
+
+ jniResponse->setHeaderOptions(headerOptions);
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: setRequestHandle
+* Signature: (Lorg/iotivity/base/OcRequestHandle;)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setRequestHandle
+(JNIEnv *env, jobject thiz, jobject jRequestHandle)
+{
+ LOGI("OcResourceResponse_setRequestHandle");
+ if (!jRequestHandle)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "requestHandle cannot be null");
+ return;
+ }
+ JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
+ if (!jniResponse)
+ {
+ return;
+ }
+ JniOcRequestHandle* jniOcRequestHandle = JniOcRequestHandle::getJniOcRequestHandlePtr(env, jRequestHandle);
+ if (!jniOcRequestHandle)
+ {
+ return;
+ }
+ jniResponse->setRequestHandle(jniOcRequestHandle->getOCRequestHandle());
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: setResourceHandle
+* Signature: (Lorg/iotivity/base/OcResourceHandle;)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceHandle
+(JNIEnv *env, jobject thiz, jobject jResourceHandle)
+{
+ LOGI("OcResourceResponse_setResourceHandle");
+ if (!jResourceHandle)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandle cannot be null");
+ return;
+ }
+ JniOcResourceResponse *jniResponse = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
+ if (!jniResponse)
+ {
+ return;
+ }
+ JniOcResourceHandle* jniOcResourceHandle = JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
+ if (!jniOcResourceHandle)
+ {
+ return;
+ }
+ jniResponse->setResourceHandle(jniOcResourceHandle->getOCResourceHandle());
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: setResponseResult
+* Signature: (I)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResponseResult
+(JNIEnv *env, jobject thiz, jint responseResult)
+{
+ LOGD("OcResourceResponse_setResponseResult");
+ JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
+ if (!response)
+ {
+ return;
+ }
+ response->setResponseResult(JniUtils::getOCEntityHandlerResult(env, static_cast<int>(responseResult)));
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: setResourceRepresentation
+* Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/lang/String;)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepresentation
+(JNIEnv *env, jobject thiz, jobject jRepresentation, jstring jstr)
+{
+ LOGD("OcResourceResponse_setResourceRepresentation");
+ if (!jRepresentation)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Representation cannot be null");
+ return;
+ }
+ if (!jstr)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "interface cannot be null");
+ return;
+ }
+
+ JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env,
+ thiz);
+ if (!response)
+ {
+ return;
+ }
+ OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,
+ jRepresentation);
+ if (!representation)
+ {
+ return;
+ }
+ response->setResourceRepresentation(*representation, env->GetStringUTFChars(jstr, 0));
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: setResourceRepresentation1
+* Signature: (Lorg/iotivity/base/OcRepresentation;)V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepresentation1
+(JNIEnv *env, jobject thiz, jobject jRepresentation)
+{
+ LOGD("OcResourceResponse_setResourceRepresentation");
+ if (!jRepresentation)
+ {
+ ThrowOcException(OC_STACK_INVALID_PARAM, "Representation cannot be null");
+ return;
+ }
+ JniOcResourceResponse *response = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
+ if (!response)
+ {
+ return;
+ }
+ OCRepresentation *representation = JniOcRepresentation::getOCRepresentationPtr(env,
+ jRepresentation);
+
+ if (representation)
+ {
+ response->setResourceRepresentation(*representation);
+ }
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: create
+* Signature: ()V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_create
+(JNIEnv *env, jobject thiz)
+{
+ LOGI("OcResourceResponse_create");
+ auto pResponse = std::make_shared<OC::OCResourceResponse>();
+ JniOcResourceResponse* jniResourceResponse = new JniOcResourceResponse(pResponse);
+ SetHandle<JniOcResourceResponse>(env, thiz, jniResourceResponse);
+ if (env->ExceptionCheck())
+ {
+ LOGE("Failed to create OcResourceResponse");
+ delete jniResourceResponse;
+ }
+}
+
+/*
+* Class: org_iotivity_base_OcResourceResponse
+* Method: dispose
+* Signature: ()V
+*/
+JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_dispose
+(JNIEnv *env, jobject thiz)
+{
+ LOGD("OcResourceResponse_dispose");
+ JniOcResourceResponse *resp = JniOcResourceResponse::getJniOcResourceResponsePtr(env, thiz);
+ delete resp;
+}
--- /dev/null
- void setErrorCode(const int eCode);
+/*
+* //******************************************************************
+* //
+* // Copyright 2015 Intel Corporation.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+* //
+* // 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.
+* //
+* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+*/
+#include "JniOcStack.h"
+#include "OCResourceResponse.h"
+
+#ifndef _Included_org_iotivity_base_OcResourceResponse
+#define _Included_org_iotivity_base_OcResourceResponse
+
+using namespace OC;
+
+class JniOcResourceResponse
+{
+public:
+ JniOcResourceResponse(std::shared_ptr<OCResourceResponse> resourceResponse);
+ ~JniOcResourceResponse();
- /*
- * Class: org_iotivity_base_OcResourceResponse
- * Method: setErrorCode
- * Signature: (I)V
- */
- JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setErrorCode
- (JNIEnv *, jobject, jint);
-
+ std::string getNewResourceUri(void);
+ void setNewResourceUri(const std::string newResourceUri);
+ void setHeaderOptions(const HeaderOptions& headerOptions);
+ void setRequestHandle(const OCRequestHandle& requestHandle);
+ void setResourceHandle(const OCResourceHandle& resourceHandle);
+ void setResponseResult(const OCEntityHandlerResult& responseResult);
+ void setResourceRepresentation(OCRepresentation& rep, std::string interfaceStr);
+ void setResourceRepresentation(OCRepresentation& rep);
+ std::shared_ptr<OCResourceResponse> getOCResourceResponse();
+ static JniOcResourceResponse* getJniOcResourceResponsePtr(JNIEnv *env, jobject thiz);
+private:
+ std::shared_ptr<OCResourceResponse> m_response;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
- #endif
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: getNewResourceUri
+ * Signature: ()Ljava/lang/String;
+ */
+ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcResourceResponse_getNewResourceUri
+ (JNIEnv *, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: setNewResourceUri
+ * Signature: (Ljava/lang/String;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setNewResourceUri
+ (JNIEnv *, jobject, jstring);
+
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: setHeaderOptions
+ * Signature: (Ljava/util/List;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setHeaderOptions
+ (JNIEnv *, jobject, jobjectArray);
+
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: setRequestHandle
+ * Signature: (Lorg/iotivity/base/OcRequestHandle;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setRequestHandle
+ (JNIEnv *, jobject, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: setResourceHandle
+ * Signature: (Lorg/iotivity/base/OcResourceHandle;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceHandle
+ (JNIEnv *, jobject, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: setResponseResult
+ * Signature: (I)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResponseResult
+ (JNIEnv *, jobject, jint);
+
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: setResourceRepresentation
+ * Signature: (Lorg/iotivity/base/OcRepresentation;Ljava/lang/String;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepresentation
+ (JNIEnv *, jobject, jobject, jstring);
+
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: setResourceRepresentation1
+ * Signature: (Lorg/iotivity/base/OcRepresentation;)V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_setResourceRepresentation1
+ (JNIEnv *, jobject, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: create
+ * Signature: ()V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_create
+ (JNIEnv *, jobject);
+
+ /*
+ * Class: org_iotivity_base_OcResourceResponse
+ * Method: dispose
+ * Signature: ()V
+ */
+ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResourceResponse_dispose
+ (JNIEnv *, jobject);
+#ifdef __cplusplus
+}
+#endif
++#endif
--- /dev/null
+/* ****************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * 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.
+ *
+ ******************************************************************/
+#include "JniOnPublishResourceListener.h"
+
+JniOnPublishResourceListener::JniOnPublishResourceListener(JNIEnv *env, jobject jListener,
+ RemoveListenerCallback removeListenerCallback)
+{
+ m_jwListener = env->NewWeakGlobalRef(jListener);
+ m_removeListenerCallback = removeListenerCallback;
+}
+
+JniOnPublishResourceListener::~JniOnPublishResourceListener()
+{
+ LOGI("~JniOnPublishResourceListener()");
+ if (m_jwListener)
+ {
+ jint ret = JNI_ERR;
+ JNIEnv *env = GetJNIEnv(ret);
+ if (nullptr == env)
+ {
+ return;
+ }
+ env->DeleteWeakGlobalRef(m_jwListener);
+ m_jwListener = nullptr;
+ if (JNI_EDETACHED == ret)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ }
+}
+
+void JniOnPublishResourceListener::onPublishResourceCallback(
+ const OCRepresentation& ocRepresentation,
+ const int eCode)
+{
+ jint envRet = JNI_ERR;
+ JNIEnv *env = GetJNIEnv(envRet);
+ if (nullptr == env)
+ {
+ return;
+ }
+
++ if (nullptr == m_jwListener)
++ {
++ LOGE("listener is not available");
++ if (JNI_EDETACHED == envRet)
++ {
++ g_jvm->DetachCurrentThread();
++ }
++ return;
++ }
++
+ jobject jListener = env->NewLocalRef(m_jwListener);
+ if (!jListener)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+ jclass clsL = env->GetObjectClass(jListener);
+
+ if (!clsL)
+ {
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+ return;
+ }
+
+ if (OC_STACK_OK != eCode && OC_STACK_RESOURCE_CREATED != eCode
+ && OC_STACK_RESOURCE_DELETED != eCode && OC_STACK_CONTINUE != eCode
+ && OC_STACK_RESOURCE_CHANGED != eCode)
+ {
+ jobject ex = GetOcException(eCode, "stack error in onPublishResourceCallback");
+ if (!ex)
+ {
+ goto CLEANUP;
+ }
+ jmethodID midL = env->GetMethodID(clsL, "onPublishResourceFailed",
+ "(Ljava/lang/Throwable;)V");
+ if (!midL)
+ {
+ goto CLEANUP;
+ }
+ env->CallVoidMethod(jListener, midL, ex);
+ }
+ else
+ {
+ OCRepresentation* rep = new OCRepresentation(ocRepresentation);
+ jlong handle = reinterpret_cast<jlong>(rep);
+ jobject jRepresentation = env->NewObject(g_cls_OcRepresentation,
+ g_mid_OcRepresentation_N_ctor_bool,
+ handle, true);
+ if (!jRepresentation)
+ {
+ delete rep;
+ goto CLEANUP;
+ }
+
+ jmethodID midL = env->GetMethodID(clsL, "onPublishResourceCompleted",
+ "(Lorg/iotivity/base/OcRepresentation;)V");
+ if (!midL)
+ {
+ delete rep;
+ goto CLEANUP;
+ }
+ env->CallVoidMethod(jListener, midL, jRepresentation);
+ if (env->ExceptionCheck())
+ {
+ LOGE("Java exception is thrown");
+ delete rep;
+ }
+ }
+
+CLEANUP:
+ checkExAndRemoveListener(env);
+ if (JNI_EDETACHED == envRet)
+ {
+ g_jvm->DetachCurrentThread();
+ }
+}
+
+void JniOnPublishResourceListener::checkExAndRemoveListener(JNIEnv* env)
+{
+ if (env->ExceptionCheck())
+ {
+ jthrowable ex = env->ExceptionOccurred();
+ env->ExceptionClear();
+ m_removeListenerCallback(env, m_jwListener);
+ env->Throw((jthrowable)ex);
+ }
+ else
+ {
+ m_removeListenerCallback(env, m_jwListener);
+ }
+}
#!/bin/bash
-BASE_PATH="../../android/android_api/base/src/main/java/"
+BASE_PATH="../../java/common/src/main/java/"
BASE_PKG="org.iotivity.base"
+ CA_SRCS="../../android/android_api/base/src/main/java/org/iotivity/ca/CaBtPairingInterface.java \
+ ../../android/android_api/base/src/main/java/org/iotivity/ca/CaInterface.java"
+
RE_PATH="../../service/resource-encapsulation/android/service/src/main/java/"
RE_COMMON_PKG=org.iotivity.service
RE_CLINET_PKG=org.iotivity.service.client