added android sense code after testing

revert-dabc3590
ayyoob 9 years ago
parent 0b67c0f74a
commit 30578a9161

@ -20,12 +20,14 @@ import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.wso2.carbon.iot.android.sense.data.publisher.DataPublisherReceiver;
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.AndroidSenseMQTTHandler;
@ -37,6 +39,8 @@ import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.SupportedS
import org.wso2.carbon.iot.android.sense.util.LocalRegistry;
import org.wso2.carbon.iot.android.sense.util.SenseClient;
import org.wso2.carbon.iot.android.sense.util.SenseUtils;
import org.wso2.carbon.iot.android.sense.util.dto.RegisterInfo;
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
@ -51,6 +55,7 @@ public class RegisterActivity extends Activity {
private EditText mMqttPortView;
private View mProgressView;
private View mLoginFormView;
private Handler mUiHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -91,9 +96,9 @@ public class RegisterActivity extends Activity {
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String username = mUsernameView.getText().toString();
String password = mPasswordView.getText().toString();
String hostname = mHostView.getText().toString();
final String username = mUsernameView.getText().toString();
final String password = mPasswordView.getText().toString();
final String hostname = mHostView.getText().toString();
String mqttPort = mMqttPortView.getText().toString();
boolean cancel = false;
View focusView = null;
@ -119,30 +124,57 @@ public class RegisterActivity extends Activity {
if (cancel) {
focusView.requestFocus();
} else {
SenseClient client = new SenseClient(getApplicationContext());
LocalRegistry.addServerURL(getBaseContext(), hostname);
String deviceId = SenseUtils.generateDeviceId(getBaseContext(), getContentResolver());
boolean registerStatus = client.register(username, password, deviceId);
if (registerStatus) {
LocalRegistry.addUsername(getApplicationContext(), username);
LocalRegistry.addDeviceId(getApplicationContext(), deviceId);
LocalRegistry.addMqttPort(getApplicationContext(), Integer.parseInt(mqttPort));
MQTTTransportHandler mqttTransportHandler = AndroidSenseMQTTHandler.getInstance(this);
if (!mqttTransportHandler.isConnected()) {
mqttTransportHandler.connect();
}
SenseScheduleReceiver senseScheduleReceiver = new SenseScheduleReceiver();
senseScheduleReceiver.clearAbortBroadcast();
senseScheduleReceiver.onReceive(this, null);
final int mqttPortNo= Integer.parseInt(mqttPort);
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
SenseClient client = new SenseClient(getApplicationContext());
LocalRegistry.addServerURL(getBaseContext(), hostname);
String deviceId = SenseUtils.generateDeviceId(getBaseContext(), getContentResolver());
final RegisterInfo registerStatus = client.register(username, password, deviceId, mUiHandler);
mUiHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), registerStatus.getMsg(), Toast.LENGTH_LONG).show();
}
});
if (registerStatus.isRegistered()) {
LocalRegistry.addUsername(getApplicationContext(), username);
LocalRegistry.addDeviceId(getApplicationContext(), deviceId);
LocalRegistry.addMqttPort(getApplicationContext(), mqttPortNo);
MQTTTransportHandler mqttTransportHandler = AndroidSenseMQTTHandler.getInstance(getApplicationContext());
if (!mqttTransportHandler.isConnected()) {
mqttTransportHandler.connect();
}
SenseScheduleReceiver senseScheduleReceiver = new SenseScheduleReceiver();
senseScheduleReceiver.clearAbortBroadcast();
senseScheduleReceiver.onReceive(getApplicationContext(), null);
DataPublisherReceiver dataUploaderReceiver = new DataPublisherReceiver();
dataUploaderReceiver.clearAbortBroadcast();
dataUploaderReceiver.onReceive(getApplicationContext(), null);
mUiHandler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(getApplicationContext(), ActivitySelectSensor.class);
startActivity(intent);
}
});
}
mUiHandler.post(new Runnable() {
@Override
public void run() {
showProgress(false);
}
});
DataPublisherReceiver dataUploaderReceiver = new DataPublisherReceiver();
dataUploaderReceiver.clearAbortBroadcast();
dataUploaderReceiver.onReceive(this, null);
}
});
myThread.start();
Intent intent = new Intent(getApplicationContext(), ActivitySelectSensor.class);
startActivity(intent);
}
showProgress(false);
}
}

@ -13,9 +13,12 @@
*/
package org.wso2.carbon.iot.android.sense.constants;
/**
* This hold constants related to android_sense.
*/
public class SenseConstants {
public final static String DEVICE_TYPE = "android_sense";
public final static String REGISTER_CONTEXT = "/android_sense_mgt";
public final static String REGISTER_CONTEXT = "/android_sense";
public final static String DCR_CONTEXT = "/dynamic-client-web";
public final static String TOKEN_ISSUER_CONTEXT = "/oauth2";
public final static String API_APPLICATION_REGISTRATION_CONTEXT = "/api-application-registration";

@ -43,7 +43,7 @@ import java.util.List;
* This is an android service which publishes the data to the server.
*/
public class DataPublisherService extends Service {
private static final String TAG = "Data Publisher";
private static final String TAG = DataPublisherService.class.getName();
private static String KEY_TAG = "key";
private static String TIME_TAG = "time";
private static String VALUE_TAG = "value";

@ -3,6 +3,9 @@ package org.wso2.carbon.iot.android.sense.data.publisher;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This hold the definition of the stream that android sense is publishing to.
*/
public class Event {
private String owner;

@ -18,6 +18,9 @@
package org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport;
/**
* This exception will be thrown when the mqtt transport fails.
*/
public class TransportHandlerException extends Exception {
private static final long serialVersionUID = 2736466230451105440L;

@ -30,7 +30,7 @@ public class LocationDataReader extends DataReader implements LocationListener {
protected LocationManager locationManager;
private Context mContext;
private boolean canGetLocation = false;
private static final String TAG = "Location Data";
private static final String TAG = LocationDataReader.class.getName();
Location location; // location
double latitude; // latitude

@ -43,6 +43,7 @@ public class SensorDataReader extends DataReader implements SensorEventListener
Context ctx;
private List<Sensor> sensorList = new ArrayList<>();
private SupportedSensors supportedSensors = SupportedSensors.getInstance();
private static final String TAG = SensorDataReader.class.getName();
public SensorDataReader(Context context) {
ctx = context;
@ -63,11 +64,11 @@ public class SensorDataReader extends DataReader implements SensorEventListener
if (senseDataStruct.containsKey(sensor.getName())) {
SensorData sensorInfo = senseDataStruct.get(sensor.getName());
sensorVector.add(sensorInfo);
Log.d(this.getClass().getName(), "Sensor Name " + sensor.getName() + ", Type " + sensor.getType() + " " +
Log.d(TAG, "Sensor Name " + sensor.getName() + ", Type " + sensor.getType() + " " +
", sensorValue :" + sensorInfo.getSensorValues());
}
} catch (Throwable e) {
Log.d(this.getClass().getName(), "error on sensors");
Log.d(TAG, "error on sensors");
}
}
@ -79,7 +80,7 @@ public class SensorDataReader extends DataReader implements SensorEventListener
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Log.e(SensorDataReader.class.getName(), e.getMessage());
Log.e(TAG, e.getMessage());
}
collectSensorData();
return sensorVector;
@ -96,7 +97,7 @@ public class SensorDataReader extends DataReader implements SensorEventListener
@Override
public void run() {
Log.d(this.getClass().getName(), "running -sensorDataMap");
Log.d(TAG, "running -sensorDataMap");
Vector<SensorData> sensorDatas = getSensorData();
for (SensorData data : sensorDatas) {
SenseDataHolder.getSensorDataHolder().add(data);

@ -30,8 +30,6 @@ import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
* Adaptor for populate the ListView.
* Takes list of Sensor readings
*/
//TODO : Add the location and battery data sections.
public class SensorViewAdaptor extends BaseAdapter {
private Context context;

@ -1,3 +1,16 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.iot.android.sense.speech.detector;
import android.content.Intent;
@ -21,6 +34,9 @@ import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
import agent.sense.android.iot.carbon.wso2.org.wso2_senseagent.R;
/**
* This is main activity for word recognition.
*/
public class WordRecognitionActivity extends ListeningActivity {
Button setThreasholdButton;
Button addWordButton;

@ -1,3 +1,16 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.iot.android.sense.speech.detector.util;
/**

@ -20,9 +20,11 @@ import android.util.Log;
import android.widget.Toast;
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
import org.wso2.carbon.iot.android.sense.util.dto.RegisterInfo;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.logging.Handler;
/**
* This Client is used for http communication with the server.
@ -44,40 +46,39 @@ public class SenseClient {
* @param deviceId
* @return
*/
public boolean register(String username, String password, String deviceId) {
public RegisterInfo register(String username, String password, String deviceId, android.os.Handler mUiHandler) {
Map<String, String> response = registerWithTimeWait(username, password, deviceId);
String responseStatus = response.get("status");
RegisterInfo registerInfo = new RegisterInfo();
if (responseStatus.trim().contains(SenseConstants.Request.REQUEST_SUCCESSFUL)) {
Toast.makeText(context, "Device Registered", Toast.LENGTH_LONG).show();
return true;
registerInfo.setMsg("Device Registered");
registerInfo.setIsRegistered(true);
return registerInfo;
} else if (responseStatus.trim().contains(SenseConstants.Request.REQUEST_CONFLICT)) {
Toast.makeText(context, "Login Successful", Toast.LENGTH_LONG).show();
return true;
registerInfo.setMsg("Login Successful");
registerInfo.setIsRegistered(true);
return registerInfo;
} else {
Toast.makeText(context, "Authentication failed, please check your credentials and try again.", Toast
.LENGTH_LONG).show();
return false;
registerInfo.setMsg("Authentication failed, please check your credentials and try again.");
registerInfo.setIsRegistered(false);
return registerInfo;
}
}
public Map<String, String> registerWithTimeWait(String username, String password, String deviceId) {
for (int i = 1; i <= SenseConstants.Request.MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
SenseClientAsyncExecutor senseClientAsyncExecutor = new SenseClientAsyncExecutor(context);
String endpoint = LocalRegistry.getServerURL(context);
senseClientAsyncExecutor.execute(username, password, deviceId, endpoint);
Map<String, String> response = senseClientAsyncExecutor.get();
if (response != null) {
return response;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Log.e("Send Sensor Data", "Thread Interruption for endpoint " + LocalRegistry.getServerURL(context));
} catch (ExecutionException e) {
Log.e("Send Sensor Data", "Failed to push data to the endpoint " + LocalRegistry.getServerURL(context));
try {
SenseClientAsyncExecutor senseClientAsyncExecutor = new SenseClientAsyncExecutor(context);
String endpoint = LocalRegistry.getServerURL(context);
senseClientAsyncExecutor.execute(username, password, deviceId, endpoint);
Map<String, String> response = senseClientAsyncExecutor.get();
if (response != null) {
return response;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Log.e("Send Sensor Data", "Thread Interruption for endpoint " + LocalRegistry.getServerURL(context));
} catch (ExecutionException e) {
Log.e("Send Sensor Data", "Failed to push data to the endpoint " + LocalRegistry.getServerURL(context));
}
return null;
}

@ -136,7 +136,7 @@ public class SenseClientAsyncExecutor extends AsyncTask<String, Void, Map<String
AndroidSenseManagerService androidSenseManagerService = Feign.builder().client(disableHostnameVerification)
.requestInterceptor(new OAuthRequestInterceptor(accessTokenInfo.getAccess_token()))
.contract(new JAXRSContract()).encoder(new JacksonEncoder()).decoder(new JacksonDecoder())
.target(AndroidSenseManagerService.class, "https://192.168.56.1:8243" + SenseConstants.REGISTER_CONTEXT);
.target(AndroidSenseManagerService.class, endpoint + SenseConstants.REGISTER_CONTEXT);
boolean registered = androidSenseManagerService.register(deviceId, DEVICE_NAME);
if (registered) {
LocalRegistry.addAccessToken(context, accessTokenInfo.getAccess_token());

@ -1,5 +1,22 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.iot.android.sense.util.dto;
/**
* This hold access token info that returned from the api call
*/
public class AccessTokenInfo {
public String token_type;
public String expires_in;

@ -1,3 +1,17 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.iot.android.sense.util.dto;
import javax.ws.rs.POST;
@ -5,9 +19,12 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
/**
* This holds the android manager service definition that is used with netflix feign.
*/
public interface AndroidSenseManagerService {
@Path("devices/{device_id}")
@Path("/enrollment/devices/{device_id}")
@POST
boolean register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName);
}

@ -1,3 +1,17 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.iot.android.sense.util.dto;

@ -1,3 +1,17 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.iot.android.sense.util.dto;
/**

@ -1,3 +1,17 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.iot.android.sense.util.dto;
@ -6,6 +20,9 @@ import feign.RequestTemplate;
import static feign.Util.checkNotNull;
/**
* This is a request interceptor to add oauth token header.
*/
public class OAuthRequestInterceptor implements RequestInterceptor {
private final String headerValue;

@ -0,0 +1,40 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.iot.android.sense.util.dto;
/**
* This holds the data related to registration.
*/
public class RegisterInfo {
private boolean isRegistered;
private String msg;
public boolean isRegistered() {
return isRegistered;
}
public void setIsRegistered(boolean isRegistered) {
this.isRegistered = isRegistered;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

@ -1,3 +1,17 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.iot.android.sense.util.dto;
import javax.ws.rs.POST;
@ -6,6 +20,9 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* This hold the api defintion that is used as a contract with netflix feign.
*/
@Path("/token")
public interface TokenIssuerService {

@ -26,6 +26,7 @@ import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.transport.AndroidSenseMQTTConnector;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.DeviceData;
@ -38,6 +39,15 @@ import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
@ -50,8 +60,9 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
private static Log log = LogFactory.getLog(AndroidSenseControllerServiceImpl.class);
private static AndroidSenseMQTTConnector androidSenseMQTTConnector;
public Response sendKeyWords(String deviceId, String keywords) {
@Path("device/{deviceId}/words")
@POST
public Response sendKeyWords(@PathParam("deviceId") String deviceId, @FormParam("keywords") String keywords) {
try {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
androidSenseMQTTConnector.publishDeviceData(username, deviceId, "add", keywords);
@ -61,7 +72,9 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
}
}
public Response sendThreshold(String deviceId, String threshold) {
@Path("device/{deviceId}/words/threshold")
@POST
public Response sendThreshold(@PathParam("deviceId") String deviceId, @FormParam("threshold") String threshold) {
try {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
androidSenseMQTTConnector.publishDeviceData(username, deviceId, "threshold", threshold);
@ -71,7 +84,9 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
}
}
public Response removeKeyWords(String deviceId, String words) {
@Path("device/{deviceId}/words")
@DELETE
public Response removeKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("words") String words) {
try {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
androidSenseMQTTConnector.publishDeviceData(username, deviceId, "remove", words);
@ -81,7 +96,12 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
}
}
public Response getAndroidSenseDeviceStats(String deviceId, String sensor, long from, long to) {
@Path("stats/{deviceId}/sensors/{sensorName}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getAndroidSenseDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor,
@QueryParam("from") long from, @QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String user = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();

@ -30,30 +30,30 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Path("enrollment")
@DeviceType(value = "android_sense")
@API(name = "android_sense_mgt", version = "1.0.0", context = "/android_sense_mgt", tags = {"android_sense"})
public interface AndroidSenseManagerService {
@Path("devices/{device_id}")
@Path("/devices/{device_id}")
@POST
Response register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName);
@Path("devices/{device_id}")
@Path("/devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@Path("/devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@Path("/devices/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices/download")
@Path("/devices/download")
@GET
@Produces("application/octet-stream")
Response downloadSketch();

@ -28,19 +28,25 @@ import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.utils.CarbonUtils;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.io.File;
import java.util.Date;
@Path("enrollment")
public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerService {
private static Log log = LogFactory.getLog(AndroidSenseManagerServiceImpl.class);
@Path("devices/{device_id}")
@Path("/devices/{device_id}")
@POST
public Response register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
@ -60,9 +66,11 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
device.setName(deviceName);
device.setType(AndroidSenseConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser());
return Response.ok(true).build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).entity(false).build();
@ -72,7 +80,9 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
}
}
public Response removeDevice(String deviceId) {
@Path("/devices/{device_id}")
@DELETE
public Response removeDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
@ -88,7 +98,9 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
}
}
public Response updateDevice(String deviceId, String name) {
@Path("/devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
@ -109,7 +121,11 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
}
}
public Response getDevice(String deviceId) {
@Path("/devices/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
@ -121,6 +137,9 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
}
}
@Path("/devices/download")
@GET
@Produces("application/octet-stream")
public Response downloadSketch() {
try {
String sep = File.separator;

@ -15,6 +15,9 @@ import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import java.util.ArrayList;
import java.util.HashMap;
@ -27,6 +30,7 @@ import java.util.Map;
public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class);
private static Object lock = new Object();
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
@ -153,4 +157,38 @@ public class APIUtil {
}
return jwtClientManagerService;
}
public static void registerApiAccessRoles(String user) {
UserStoreManager userStoreManager = null;
try {
userStoreManager = getUserStoreManager();
if (userStoreManager != null) {
synchronized (lock) {
String[] userList = new String[]{user};
if (!userStoreManager.isExistingRole(Constants.DEFAULT_ROLE_NAME)) {
userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, Constants.DEFAULT_PERMISSION);
}
}
}
} catch (UserStoreException e) {
log.error("error on wso2 user component");
}
}
private static UserStoreManager getUserStoreManager() throws UserStoreException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
return getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
}
public static RealmService getRealmService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService =
(RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "JWT Client manager service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return realmService;
}
}

@ -0,0 +1,33 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.iot.androidsense.service.impl.util;
import org.wso2.carbon.user.core.Permission;
import org.wso2.carbon.user.core.authorization.TreeNode;
/**
* This hold the constants related to android sense.
*/
public class Constants {
private static final String DEFAULT_PERMISSION_RESOURCE = "/_system/governance/permission/admin/device-mgt/android_sense/user";
public static final String DEFAULT_ROLE_NAME = "android_sense_user";
public static final Permission DEFAULT_PERMISSION[] = new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE,
TreeNode.Permission.UI_EXECUTE.toString())};
}

@ -1,3 +1,21 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.iot.androidsense.service.impl.util;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@ -1,3 +1,21 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.iot.androidsense.service.impl.util;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@ -1,3 +1,21 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.iot.androidsense.service.impl.util;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@ -30,64 +30,64 @@
<!-- Device related APIs -->
<Permission>
<name>Set words</name>
<path>/device-mgt/android_sense/word/add</path>
<path>/device-mgt/android_sense/user</path>
<url>/device/*/words</url>
<method>POST</method>
<scope>android_sense_user</scope>
</Permission>
<Permission>
<name>set word threshold information</name>
<path>/device-mgt/android_sense/threshold</path>
<path>/device-mgt/android_sense/user</path>
<url>/device/*/words/threshold</url>
<method>POST</method>
<scope>android_sense_user</scope>
</Permission>
<Permission>
<name>delete words</name>
<path>/device-mgt/android_sense/word/delete</path>
<path>/device-mgt/android_sense/user</path>
<url>/device/*/words</url>
<method>DELETE</method>
<scope>android_sense_user</scope>
</Permission>
<Permission>
<name>get device stats</name>
<path>/device-mgt/android_sense/device/stats</path>
<path>/device-mgt/android_sense/user</path>
<url>/stats/*/sensors/*</url>
<method>GET</method>
<scope>android_sense_device</scope>
</Permission>
<Permission>
<name>Get device</name>
<path>/device-mgt/android_sense/user/devices/list</path>
<url>/devices/*</url>
<path>/device-mgt/android_sense/user</path>
<url>/enrollment/devices/*</url>
<method>GET</method>
<scope>android_sense_user</scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/android_sense/user/devices/add</path>
<url>/devices/*</url>
<path>/login</path>
<url>/enrollment/devices/*</url>
<method>POST</method>
<scope>android_sense_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/android_sense/user/devices/remove</path>
<url>/devices/*</url>
<path>/device-mgt/android_sense/user</path>
<url>/enrollment/devices/*</url>
<method>DELETE</method>
<scope>android_sense_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/android_sense/user/devices/add</path>
<url>/devices/download</url>
<path>/device-mgt/android_sense/user</path>
<url>/enrollment/devices/download</url>
<method>GET</method>
<scope>android_sense_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/android_sense/user/devices/update</path>
<url>/devices/*</url>
<path>/device-mgt/android_sense/user</path>
<url>/enrollment/devices/*</url>
<method>PUT</method>
<scope>android_sense_user</scope>
</Permission>

@ -36,6 +36,16 @@
</jaxrs:providers>
</jaxrs:server>
<!--<jaxrs:server id="AndroidSense_Mgt" address="/enrollment/">-->
<!--<jaxrs:serviceBeans>-->
<!--<bean id="AndroidSenseManagerService"-->
<!--class="org.wso2.carbon.device.mgt.iot.androidsense.service.impl.AndroidSenseManagerServiceImpl"/>-->
<!--</jaxrs:serviceBeans>-->
<!--<jaxrs:providers>-->
<!--<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />-->
<!--</jaxrs:providers>-->
<!--</jaxrs:server>-->
<bean id="mqttConnectorBean"
class="org.wso2.carbon.device.mgt.iot.androidsense.service.impl.transport.AndroidSenseMQTTConnector">
</bean>

@ -42,8 +42,4 @@
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-endpoint-context</param-name>
<param-value>/android_sense</param-value>
</context-param>
</web-app>

@ -45,8 +45,6 @@ import java.util.Date;
import java.util.List;
import java.util.UUID;
@API(name = "arduino_mgt", version = "1.0.0", context = "/arduino_mgt", tags = {"arduino"})
@DeviceType(value = "arduino")
public class ArduinoManagerServiceImpl implements ArduinoManagerService {
private static final String KEY_TYPE = "PRODUCTION";

@ -51,6 +51,9 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This will act as the event reciver.
*/
public class HTTPMessageServlet extends HttpServlet {
private static final String AUTHORIZATION_HEADER = "Authorization";

@ -1,5 +1,22 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.event.input.adapter.extensions.http.util;
/**
* This will be return after authentication and this will consist of the authenticated user info.
*/
public class AuthenticationInfo {
/**

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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
@ -14,7 +14,9 @@
*/
package org.wso2.carbon.event.input.adapter.extensions.http.util;
/**
* This holds the constants related to HTTP event adapter.
*/
public final class HTTPEventAdapterConstants {
private HTTPEventAdapterConstants() {

@ -17,6 +17,9 @@
*/
package org.wso2.carbon.event.input.adapter.extensions.mqtt.exception;
/**
* This exception will thrown when content validator is failed to intialiaze.
*/
public class MQTTContentValidatorInitializationException extends RuntimeException {
private String errMessage;

@ -21,6 +21,9 @@ import org.wso2.carbon.event.input.adapter.extensions.mqtt.Constants;
import java.util.Map;
/**
* This holds the configurations related to MQTT Broker.
*/
public class MQTTBrokerConnectionConfiguration {
private String brokerUsername = null;

@ -17,6 +17,10 @@
*/
package org.wso2.carbon.event.input.adapter.extensions.mqtt.util;
/**
* This holds the constants related to mqtt event adapter.
*/
public class MQTTEventAdapterConstants {
public static final String ADAPTER_TYPE_MQTT = "oauth-mqtt";

@ -1,3 +1,17 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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 oauth;
import org.apache.axis2.context.ServiceContext;
@ -22,6 +36,9 @@ import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.Properties;
/**
* This acts as a contract point for OAuth token validation.
*/
public class OAuthTokenValdiator {
private static String cookie;

@ -1,5 +1,22 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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 util;
/**
* This is returned after authentication.
*/
public class AuthenticationInfo {
/**

@ -1,3 +1,17 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.event.output.adapter.extensions.ui.internal.ds;
import org.wso2.carbon.event.stream.core.EventStreamService;

@ -1,6 +1,6 @@
/*
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except

Loading…
Cancel
Save