This commit is contained in:
ayyoob 2016-06-14 15:25:23 +05:30
commit 86018fddf1
107 changed files with 1890 additions and 4077 deletions

View File

@ -5,3 +5,5 @@ WSO2 MOBILE DEVICE MANAGER
WSO2 Mobile Device Manager (WSO2 MDM) is a comprehensive platform that helps solve mobile computing challenges enterprises face today when dealing with both corporate owned, personally enabled (COPE) devices and employee owned devices as part of a bring your own device (BYOD) program. WSO2 Mobile Device Manager (WSO2 MDM) is a comprehensive platform that helps solve mobile computing challenges enterprises face today when dealing with both corporate owned, personally enabled (COPE) devices and employee owned devices as part of a bring your own device (BYOD) program.
Whether it is device provisioning, device configuration management, policy enforcement, mobile application management, device data security, or compliance monitoring, WSO2 MDM offers a single enterprise-grade platform. Whether it is device provisioning, device configuration management, policy enforcement, mobile application management, device data security, or compliance monitoring, WSO2 MDM offers a single enterprise-grade platform.

View File

@ -60,6 +60,7 @@
<activity <activity
android:name="org.wso2.carbon.iot.android.sense.realtimeviewer.ActivitySelectSensor" android:name="org.wso2.carbon.iot.android.sense.realtimeviewer.ActivitySelectSensor"
android:label="My Sensors" android:label="My Sensors"
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="@style/AppTheme.NoActionBar" > android:theme="@style/AppTheme.NoActionBar" >
</activity> </activity>
<activity <activity

View File

@ -30,7 +30,7 @@ import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.Transport
import org.wso2.carbon.iot.android.sense.constants.SenseConstants; import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationData; import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationData;
import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationDataReader; import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationDataReader;
import org.wso2.carbon.iot.android.sense.event.streams.Speed.SpeedData;
import org.wso2.carbon.iot.android.sense.event.streams.Sensor.SensorData; import org.wso2.carbon.iot.android.sense.event.streams.Sensor.SensorData;
import org.wso2.carbon.iot.android.sense.event.streams.battery.BatteryData; import org.wso2.carbon.iot.android.sense.event.streams.battery.BatteryData;
import org.wso2.carbon.iot.android.sense.speech.detector.util.ProcessWords; import org.wso2.carbon.iot.android.sense.speech.detector.util.ProcessWords;
@ -134,6 +134,19 @@ public class DataPublisherService extends Service {
} }
SenseDataHolder.resetLocationDataHolder(); SenseDataHolder.resetLocationDataHolder();
//retrieve speed data.
List<SpeedData> speedDataMap = SenseDataHolder.getSpeedDataHolder();
if (!speedDataMap.isEmpty()) {
for (SpeedData speedData : speedDataMap) {
Event event = new Event();
event.setTimestamp(speedData.getTimeStamp());
event.setSpeed(speedData.getSpeed());
event.setTurns(speedData.getTurns());
events.add(event);
}
}
SenseDataHolder.resetSpeedDataHolder();
//retrieve words //retrieve words
ProcessWords.cleanAndPushToWordMap(); ProcessWords.cleanAndPushToWordMap();
List<WordData> wordDatMap = SenseDataHolder.getWordDataHolder(); List<WordData> wordDatMap = SenseDataHolder.getWordDataHolder();

View File

@ -25,6 +25,9 @@ public class Event {
private String word; private String word;
private String wordStatus; private String wordStatus;
private long timestamp; private long timestamp;
private static float speed;
private String turn;
public static final float SPEED_LIMIT = 60;
private int getBattery() { private int getBattery() {
return battery; return battery;
@ -165,6 +168,32 @@ public class Event {
this.wordStatus = wordStatus; this.wordStatus = wordStatus;
} }
public void setSpeed(float speed) {
this.type = "speed";
this.speed = speed;
}
public float getSpeed() {
this.type = "speed";
return speed;
}
public void setTurns(String turn) {
this.type = "turn";
this.turn = turn;
}
public String getTurns() {
if (turn == null || turn.isEmpty() || turn.equals("null")){
turn = "No Turns";
}
return turn;
}
public JSONObject getEvent() throws JSONException { public JSONObject getEvent() throws JSONException {
JSONObject jsonEvent = new JSONObject(); JSONObject jsonEvent = new JSONObject();
JSONObject jsonMetaData = new JSONObject(); JSONObject jsonMetaData = new JSONObject();
@ -185,6 +214,15 @@ public class Event {
jsonPayloadData.put("accelerometer_x", events[0]); jsonPayloadData.put("accelerometer_x", events[0]);
jsonPayloadData.put("accelerometer_y", events[1]); jsonPayloadData.put("accelerometer_y", events[1]);
jsonPayloadData.put("accelerometer_z", events[2]); jsonPayloadData.put("accelerometer_z", events[2]);
//speed
//if (getSpeed()>SPEED_LIMIT) {
jsonPayloadData.put("speed_limit", getSpeed());
//}
//turn
jsonPayloadData.put("turn_way", getTurns());
//magnetic //magnetic
events = getMagnetic(); events = getMagnetic();
jsonPayloadData.put("magnetic_x", events[0]); jsonPayloadData.put("magnetic_x", events[0]);

View File

@ -49,6 +49,8 @@ public class SenseService extends Service {
SenseDataCollector Sensor = new SenseDataCollector(this, SenseDataCollector.DataType.SENSOR); SenseDataCollector Sensor = new SenseDataCollector(this, SenseDataCollector.DataType.SENSOR);
SenseDataCollector Location = new SenseDataCollector(this, SenseDataCollector.DataType.LOCATION); SenseDataCollector Location = new SenseDataCollector(this, SenseDataCollector.DataType.LOCATION);
registerReceiver(new BatteryDataReceiver(), new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); registerReceiver(new BatteryDataReceiver(), new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
SenseDataCollector speed = new SenseDataCollector(this, SenseDataCollector.DataType.SPEED);
//service will not be stopped until we manually stop the service //service will not be stopped until we manually stop the service
return Service.START_NOT_STICKY; return Service.START_NOT_STICKY;

View File

@ -14,13 +14,19 @@
package org.wso2.carbon.iot.android.sense.event.streams.Location; package org.wso2.carbon.iot.android.sense.event.streams.Location;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import android.location.Location; import android.location.Location;
import android.location.LocationListener; import android.location.LocationListener;
import android.location.LocationManager; import android.location.LocationManager;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log; import android.util.Log;
import android.widget.Toast;
import org.wso2.carbon.iot.android.sense.event.streams.DataReader; import org.wso2.carbon.iot.android.sense.event.streams.DataReader;
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder; import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
import java.util.Calendar;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
@ -32,6 +38,9 @@ public class LocationDataReader extends DataReader implements LocationListener {
LocationData gps; LocationData gps;
static final Double EARTH_RADIUS = 6371.00;
// flag for GPS status // flag for GPS status
private boolean isGPSEnabled = false; private boolean isGPSEnabled = false;
@ -47,6 +56,12 @@ public class LocationDataReader extends DataReader implements LocationListener {
double latitude; // latitude double latitude; // latitude
double longitude; // longitude double longitude; // longitude
double lat_old=0.0;
double lon_old=0.0;
double time;
float speed = 0.0f;
private long lastUpdate;
// The minimum distance to change Updates in meters // The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
@ -150,6 +165,39 @@ public class LocationDataReader extends DataReader implements LocationListener {
@Override @Override
public void onLocationChanged(Location arg0) { public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
Log.v("Debug", "in onLocation changed..");
if(location!=null){
long curTime = System.currentTimeMillis();
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
Calendar c=Calendar.getInstance();
c.setTimeInMillis(diffTime);
time=c.get(Calendar.HOUR);
locationManager.removeUpdates(LocationDataReader.this);
//String Speed = "Device Speed: " +location.getSpeed();
latitude=location.getLongitude();
longitude =location.getLatitude();
double distance =CalculationByDistance(latitude, longitude, lat_old, lon_old)/1000;
speed = (float)distance/(float)time;
Toast.makeText(mContext, longitude+"\n"+latitude+"\nDistance is: "
+distance+"\nSpeed is: "+speed , Toast.LENGTH_SHORT).show();
Intent intent = new Intent("speedUpdate");
intent.putExtra("speed", speed);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
lat_old=latitude;
lon_old=longitude;
}
} }
@ -192,4 +240,17 @@ public class LocationDataReader extends DataReader implements LocationListener {
} }
} }
public double CalculationByDistance(double lat1, double lon1, double lat2, double lon2) {
double Radius = EARTH_RADIUS;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return Radius * c;
}
} }

View File

@ -17,13 +17,14 @@ package org.wso2.carbon.iot.android.sense.event.streams;
import android.content.Context; import android.content.Context;
import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationDataReader; import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationDataReader;
import org.wso2.carbon.iot.android.sense.event.streams.Sensor.SensorDataReader; import org.wso2.carbon.iot.android.sense.event.streams.Sensor.SensorDataReader;
import org.wso2.carbon.iot.android.sense.event.streams.Speed.SpeedDataReader;
/** /**
* This class triggered by service to collect the sensor data. * This class triggered by service to collect the sensor data.
*/ */
public class SenseDataCollector { public class SenseDataCollector {
public enum DataType { public enum DataType {
SENSOR, LOCATION SENSOR, LOCATION,SPEED
} }
public SenseDataCollector(Context ctx, DataType dt) { public SenseDataCollector(Context ctx, DataType dt) {
@ -35,6 +36,9 @@ public class SenseDataCollector {
case LOCATION: case LOCATION:
dr = new LocationDataReader(ctx); dr = new LocationDataReader(ctx);
break; break;
case SPEED:
dr = new SpeedDataReader(ctx);
break;
} }
if (dr != null) { if (dr != null) {
Thread DataCollector = new Thread(dr); Thread DataCollector = new Thread(dr);

View File

@ -0,0 +1,56 @@
/*
* 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.event.streams.Speed;
import java.util.Date;
public class SpeedData {
private float speed; // speed
private String turnAxis; // turns
private long timestamp;
SpeedData(float speed, String turnAxis) {
this.speed = speed;
this.turnAxis = turnAxis;
timestamp = new Date().getTime();
}
public float getSpeed() {
return speed;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public String getTurns() {
return turnAxis;
}
public void setTurns(String turnAxis) {
this.turnAxis = turnAxis;
}
public long getTimeStamp() {
return timestamp;
}
public void setTimeStamp(long timeStamp) {
timestamp = timeStamp;
}
}

View File

@ -0,0 +1,183 @@
/*
* 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.event.streams.Speed;
import org.wso2.carbon.iot.android.sense.event.streams.DataReader;
import org.wso2.carbon.iot.android.sense.event.streams.Sensor.SensorData;
import org.wso2.carbon.iot.android.sense.realtimeviewer.sensorlisting.SupportedSensors;
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.app.Activity;
import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationDataReader;
public class SpeedDataReader extends DataReader implements SensorEventListener {
SpeedData data;
private SensorManager mSensorManager;
private Map<String, SensorData> senseDataStruct = new HashMap<>();
private Vector<SensorData> sensorVector = new Vector<>();
private static final String TAG = SpeedDataReader.class.getName();
private float last_x, last_y, last_z;
private long lastUpdate;
private String xTurnAxis;
float speed;
private float x,y,z;
Context ctx;
private List<Sensor> sensorList = new ArrayList<>();
private SupportedSensors supportedSensors = SupportedSensors.getInstance();
@Override
public void onSensorChanged(SensorEvent event) {
Sensor devSensor = event.sensor;
if (devSensor.getType() == Sensor.TYPE_ACCELEROMETER) {
x = event.values[0];
y = event.values[1];
z = event.values[2];
}
}
public SpeedDataReader(Context context) {
ctx = context;
SharedPreferences sharedPreferences = ctx.getSharedPreferences(SupportedSensors.SELECTED_SENSORS, Context
.MODE_MULTI_PROCESS);
Set<String> selectedSet = sharedPreferences.getStringSet(SupportedSensors.SELECTED_SENSORS_BY_USER, null);
mSensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
selectedSensorList(selectedSet);
for (Sensor sensor : sensorList) {
mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
LocalBroadcastManager.getInstance(ctx).registerReceiver(mMessageReceiver,
new IntentFilter("speedUpdate"));
}
private void collectSensorData() {
for (Sensor sensor : sensorList) {
try {
if (senseDataStruct.containsKey(sensor.getName())) {
SensorData sensorInfo = senseDataStruct.get(sensor.getName());
sensorVector.add(sensorInfo);
Log.d(TAG, "Sensor Name " + sensor.getName() + ", Type " + sensor.getType() + " " +
", sensorValue :" + sensorInfo.getSensorValues());
}
} catch (Throwable e) {
Log.d(TAG, "error on sensors");
}
}
mSensorManager.unregisterListener(this);
}
public String getTurns() {
if(Round(x,4)>10.0000){
Log.d("sensor", "X Right axis: " + x);
xTurnAxis = "Right";
return xTurnAxis;
}else if(Round(x,4)<-10.0000){
Log.d("sensor", "X Left axis: " + x);
xTurnAxis = "Left";
return xTurnAxis;
}else {
xTurnAxis = "No Turns";
}
return xTurnAxis;
}
public float getSpeed(){
return speed;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// can be safely ignored for this demo
}
public static float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
Log.d("round", "round: " + tmp/p);
return tmp/p;
}
@Override
public void run() {
Log.d(TAG, "running - Device Speed");
try {
TimeUnit.MILLISECONDS.sleep(10000);
// String trn = getTurns();
// double spd = getSpeed();
//if (trn != 0 && spd != 0) {
data = new SpeedData(getSpeed(), getTurns());
SenseDataHolder.getSpeedDataHolder().add(data);
collectSensorData();
//}
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
Log.e(TAG, " Speed Data Retrieval Failed");
}
}
public void selectedSensorList(Set<String> set) {
if (set != null) {
String[] sensorsSet = set.toArray(new String[set.size()]);
for (String s : sensorsSet) {
sensorList.add(mSensorManager.getDefaultSensor(supportedSensors.getType(s.toLowerCase())));
}
}
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
speed = intent.getFloatExtra("speed",speed);
Log.d("receiver", "Got message: " + speed);
}
};
}

View File

@ -69,7 +69,7 @@ public class ActivitySelectSensor extends AppCompatActivity
private ListView listView; private ListView listView;
private SensorManager sensorManager; private SensorManager sensorManager;
private ArrayList<Sensor> sensors = new ArrayList<>(); private ArrayList<Sensor> sensors = new ArrayList<>();
private EditText sessionIdText;
private RealTimeSensorReader sensorReader = null; private RealTimeSensorReader sensorReader = null;
private RealTimeSensorChangeReceiver realTimeSensorChangeReceiver = new RealTimeSensorChangeReceiver(); private RealTimeSensorChangeReceiver realTimeSensorChangeReceiver = new RealTimeSensorChangeReceiver();
private SupportedSensors supportedSensors = SupportedSensors.getInstance(); private SupportedSensors supportedSensors = SupportedSensors.getInstance();
@ -81,11 +81,21 @@ public class ActivitySelectSensor extends AppCompatActivity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sessionIdText = (EditText) findViewById(R.id.sessionId);
sessionIdText.setCursorVisible(false);
listView = (ListView) findViewById(R.id.senseListContainer); listView = (ListView) findViewById(R.id.senseListContainer);
registerReceiver(realTimeSensorChangeReceiver, new IntentFilter("sensorDataMap")); registerReceiver(realTimeSensorChangeReceiver, new IntentFilter("sensorDataMap"));
sessionIdText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sessionIdText.setCursorVisible(true);
}
});
//Publish data //Publish data
FloatingActionButton fbtnPublishData = (FloatingActionButton) findViewById(R.id.publish); FloatingActionButton fbtnPublishData = (FloatingActionButton) findViewById(R.id.publish);
@ -113,7 +123,6 @@ public class ActivitySelectSensor extends AppCompatActivity
fbtnSpeechRecongnizer.setOnClickListener(new View.OnClickListener() { fbtnSpeechRecongnizer.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
EditText sessionIdText = (EditText) findViewById(R.id.sessionId);
String sessionId = sessionIdText.getText().toString(); String sessionId = sessionIdText.getText().toString();
if (!sessionId.isEmpty()) { if (!sessionId.isEmpty()) {
Intent intent = new Intent(getApplicationContext(), WordRecognitionActivity.class); Intent intent = new Intent(getApplicationContext(), WordRecognitionActivity.class);
@ -214,6 +223,8 @@ public class ActivitySelectSensor extends AppCompatActivity
return true; return true;
} }
@Override @Override
public void onDialogPositiveClick(SelectSensorDialog dialog) { public void onDialogPositiveClick(SelectSensorDialog dialog) {
@ -275,6 +286,7 @@ public class ActivitySelectSensor extends AppCompatActivity
} }
} }
/** /**
* This method unregisters the real-time broadcast receiver. * This method unregisters the real-time broadcast receiver.
*/ */

View File

@ -15,6 +15,7 @@ package org.wso2.carbon.iot.android.sense.util;
import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationData; import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationData;
import org.wso2.carbon.iot.android.sense.event.streams.Sensor.SensorData; import org.wso2.carbon.iot.android.sense.event.streams.Sensor.SensorData;
import org.wso2.carbon.iot.android.sense.event.streams.Speed.SpeedData;
import org.wso2.carbon.iot.android.sense.event.streams.battery.BatteryData; import org.wso2.carbon.iot.android.sense.event.streams.battery.BatteryData;
import org.wso2.carbon.iot.android.sense.speech.detector.util.WordData; import org.wso2.carbon.iot.android.sense.speech.detector.util.WordData;
import java.util.List; import java.util.List;
@ -31,6 +32,8 @@ public class SenseDataHolder {
private static List<BatteryData> batteryDataHolder; private static List<BatteryData> batteryDataHolder;
private static List<LocationData> locationDataHolder; private static List<LocationData> locationDataHolder;
private static List<WordData> wordDataHolder; private static List<WordData> wordDataHolder;
private static List<SpeedData> speedDataHolder;
//LocationData gps; //LocationData gps;
@ -70,6 +73,13 @@ public class SenseDataHolder {
return wordDataHolder; return wordDataHolder;
} }
public static List<SpeedData> getSpeedDataHolder(){
if(speedDataHolder == null){
speedDataHolder = new CopyOnWriteArrayList<>();
}
return speedDataHolder;
}
public static void resetSensorDataHolder(){ public static void resetSensorDataHolder(){
sensorDataHolder = null; sensorDataHolder = null;
} }
@ -86,4 +96,9 @@ public class SenseDataHolder {
wordDataHolder = null; wordDataHolder = null;
} }
public static void resetSpeedDataHolder() {
speedDataHolder = null;
}
} }

View File

@ -39,8 +39,22 @@ define stream battery (meta_owner string, meta_deviceType string, meta_deviceId
@Export('org.wso2.iot.devices.accelerometer:1.0.0') @Export('org.wso2.iot.devices.accelerometer:1.0.0')
define stream accelerometer (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, x float, y float, z float); define stream accelerometer (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, x float, y float, z float);
@Export("org.wso2.iot.devices.speed:1.0.0")
define stream speed (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, limit float);
@Export("org.wso2.iot.devices.turn:1.0.0")
define stream turn (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, turn string);
@Import('org.wso2.iot.android.sense:1.0.0') @Import('org.wso2.iot.android.sense:1.0.0')
define stream androidsense (meta_owner string, meta_deviceId string, meta_type string, meta_timestamp long, battery int, gps_lat double, gps_long double, accelerometer_x float, accelerometer_y float, accelerometer_z float, magnetic_x float, magnetic_y float, magnetic_z float, gyroscope_x float, gyroscope_y float, gyroscope_z float, light float, pressure float, proximity float, gravity_x float, gravity_y float, gravity_z float, rotation_x float, rotation_y float, rotation_z float, word string, word_sessionId string, word_status string); define stream androidsense (meta_owner string, meta_deviceId string, meta_type string, meta_timestamp long, battery int, gps_lat double, gps_long double, accelerometer_x float, accelerometer_y float, accelerometer_z float,speed_limit float,turn_way string, magnetic_x float, magnetic_y float, magnetic_z float, gyroscope_x float, gyroscope_y float, gyroscope_z float, light float, pressure float, proximity float, gravity_x float, gravity_y float, gravity_z float, rotation_x float, rotation_y float, rotation_z float, word string, word_sessionId string, word_status string);
from androidsense[meta_type == 'speed' and speed_limit > 25]
select meta_owner, 'android_sense' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, speed_limit as limit
insert into speed;
from androidsense[meta_type == 'turn']
select meta_owner, 'android_sense' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, turn_way as turn
insert into turn;
from androidsense[meta_type == 'accelerometer'] from androidsense[meta_type == 'accelerometer']
select meta_owner, 'android_sense' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, accelerometer_x as x, accelerometer_y as y, accelerometer_z as z select meta_owner, 'android_sense' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, accelerometer_x as x, accelerometer_y as y, accelerometer_z as z
@ -84,4 +98,4 @@ insert into rotation;
from androidsense[meta_type == 'word'] from androidsense[meta_type == 'word']
select meta_owner, 'android_sense' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, word_sessionId as sessionId, word as word, word_status as status select meta_owner, 'android_sense' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, word_sessionId as sessionId, word as word, word_status as status
insert into words; insert into words;

View File

@ -16,6 +16,8 @@
{"name": "accelerometer_x", "type": "FLOAT"}, {"name": "accelerometer_x", "type": "FLOAT"},
{"name": "accelerometer_y", "type": "FLOAT"}, {"name": "accelerometer_y", "type": "FLOAT"},
{"name": "accelerometer_z", "type": "FLOAT"}, {"name": "accelerometer_z", "type": "FLOAT"},
{"name": "speed_limit", "type": "FLOAT"},
{"name": "turn_way", "type": "STRING"},
{"name": "magnetic_x", "type": "FLOAT"}, {"name": "magnetic_x", "type": "FLOAT"},
{"name": "magnetic_y", "type": "FLOAT"}, {"name": "magnetic_y", "type": "FLOAT"},
{"name": "magnetic_z", "type": "FLOAT"}, {"name": "magnetic_z", "type": "FLOAT"},
@ -35,4 +37,4 @@
{"name": "word_sessionId", "type": "STRING"}, {"name": "word_sessionId", "type": "STRING"},
{"name": "word_status", "type": "STRING"} {"name": "word_status", "type": "STRING"}
] ]
} }

View File

@ -25,7 +25,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.exception.AndroidSenseDeviceMgtPluginException; import org.wso2.carbon.device.mgt.iot.androidsense.plugin.exception.AndroidSenseDeviceMgtPluginException;
@ -49,14 +49,14 @@ public class AndroidSenseManager implements DeviceManager {
} }
@Override @Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration) public boolean saveConfiguration(PlatformConfiguration PlatformConfiguration)
throws DeviceManagementException { throws DeviceManagementException {
//TODO implement this //TODO implement this
return false; return false;
} }
@Override @Override
public TenantConfiguration getConfiguration() throws DeviceManagementException { public PlatformConfiguration getConfiguration() throws DeviceManagementException {
//TODO implement this //TODO implement this
return null; return null;
} }

View File

@ -19,6 +19,6 @@
function onRequest(context){ function onRequest(context){
var viewModel = {}; var viewModel = {};
var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
viewModel.hostName = devicemgtProps["httpsURL"]; viewModel.hostName = devicemgtProps["httpsWebURL"];
return viewModel; return viewModel;
} }

View File

@ -27,7 +27,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.exception.ArduinoDeviceMgtPluginException; import org.wso2.carbon.device.mgt.iot.arduino.plugin.exception.ArduinoDeviceMgtPluginException;
@ -51,14 +51,14 @@ public class ArduinoManager implements DeviceManager {
} }
@Override @Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration) public boolean saveConfiguration(PlatformConfiguration PlatformConfiguration)
throws DeviceManagementException { throws DeviceManagementException {
//TODO implement this //TODO implement this
return false; return false;
} }
@Override @Override
public TenantConfiguration getConfiguration() throws DeviceManagementException { public PlatformConfiguration getConfiguration() throws DeviceManagementException {
//TODO implement this //TODO implement this
return null; return null;
} }

View File

@ -34,6 +34,8 @@
<property name="Pressure_dir" value="pressure_sensor"/> <property name="Pressure_dir" value="pressure_sensor"/>
<property name="Rotation_dir" value="rotation_sensor"/> <property name="Rotation_dir" value="rotation_sensor"/>
<property name="Temperature_dir" value="temperature_sensor"/> <property name="Temperature_dir" value="temperature_sensor"/>
<property name="Speed_dir" value="speed_sensor"/>
<property name="Turn_dir" value="turn_sensor"/>
<target name="clean"> <target name="clean">
<delete dir="${target-dir}" /> <delete dir="${target-dir}" />
@ -74,5 +76,12 @@
<zip destfile="${target-dir}/${Temperature_dir}.car"> <zip destfile="${target-dir}/${Temperature_dir}.car">
<zipfileset dir="${src-dir}/${Temperature_dir}"/> <zipfileset dir="${src-dir}/${Temperature_dir}"/>
</zip> </zip>
<zip destfile="${target-dir}/${Speed_dir}.car">
<zipfileset dir="${src-dir}/${Speed_dir}"/>
</zip>
<zip destfile="${target-dir}/${Turn_dir}.car">
<zipfileset dir="${src-dir}/${Turn_dir}"/>
</zip>
</target> </target>
</project> </project>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<artifacts>
<artifact name="speed" version="1.0.0" type="carbon/application">
<dependency artifact="speed_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="speed_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="speed_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="speed_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.EventExecution_ConnectedLap_1.EventPublisher_ConnectedLap_1.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventPublisher_ConnectedLap_1.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.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.
-->
<artifact name="speed_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
<file>speed_publisher.xml</file>
</artifact>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.EventExecution_ConnectedLap_1.EventPublisher_ConnectedLap_1.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventPublisher_ConnectedLap_1.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.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.
-->
<eventPublisher name="speed_publisher" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.devices.speed" version="1.0.0"/>
<mapping customMapping="disable" type="text"/>
<to eventAdapterType="email">
<property name="email.subject">Email Alerts Speed</property>
<property name="email.address"></property>
<property name="email.type">text/html</property>
</to>
</eventPublisher>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<artifact name="speed_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>speed_receiver.xml</file>
</artifact>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<eventReceiver name="speed_receiver" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="wso2event">
<property name="events.duplicated.in.cluster">false</property>
</from>
<mapping customMapping="disable" type="wso2event"/>
<to streamName="org.wso2.iot.devices.speed" version="1.0.0"/>
</eventReceiver>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<artifact name="speed_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_speed.xml</file>
</artifact>

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.speed:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>limit</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<artifact name="speed_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.speed_1.0.0.json</file>
</artifact>

View File

@ -0,0 +1,30 @@
{
"name": "org.wso2.iot.devices.speed",
"version": "1.0.0",
"nickName": "speed",
"description": "speed data received from the Device",
"metaData": [
{
"name": "owner",
"type": "STRING"
},
{
"name": "deviceType",
"type": "STRING"
},
{
"name": "deviceId",
"type": "STRING"
},
{
"name": "time",
"type": "LONG"
}
],
"payloadData": [
{
"name": "limit",
"type": "FLOAT"
}
]
}

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<artifacts>
<artifact name="turn" version="1.0.0" type="carbon/application">
<dependency artifact="turn_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="turn_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="turn_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="turn_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.EventExecution_ConnectedLap_1.EventPublisher_ConnectedLap_1.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventPublisher_ConnectedLap_1.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.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.
-->
<artifact name="turn_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
<file>turn_publisher.xml</file>
</artifact>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.EventExecution_ConnectedLap_1.EventPublisher_ConnectedLap_1.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventPublisher_ConnectedLap_1.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventReceiver_ConnectedLap_1.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_1.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_CpuUsage_1.EventStream_ConnectedLap_MemoryUsage_1.0.0.EventStream_ConnectedLap_MemoryUsage_1.0.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.
-->
<eventPublisher name="turn_publisher" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.devices.turn" version="1.0.0"/>
<mapping customMapping="disable" type="text"/>
<to eventAdapterType="email">
<property name="email.subject">Email Alerts Turn</property>
<property name="email.address"></property>
<property name="email.type">text/html</property>
</to>
</eventPublisher>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<artifact name="turn_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>turn_receiver.xml</file>
</artifact>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<eventReceiver name="turn_receiver" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="wso2event">
<property name="events.duplicated.in.cluster">false</property>
</from>
<mapping customMapping="disable" type="wso2event"/>
<to streamName="org.wso2.iot.devices.turn" version="1.0.0"/>
</eventReceiver>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<artifact name="turn_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_turn.xml</file>
</artifact>

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.turn:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>turn</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<artifact name="turn_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.turn_1.0.0.json</file>
</artifact>

View File

@ -0,0 +1,30 @@
{
"name": "org.wso2.iot.devices.turn",
"version": "1.0.0",
"nickName": "turn",
"description": "turn data received from the Device",
"metaData": [
{
"name": "owner",
"type": "STRING"
},
{
"name": "deviceType",
"type": "STRING"
},
{
"name": "deviceId",
"type": "STRING"
},
{
"name": "time",
"type": "LONG"
}
],
"payloadData": [
{
"name": "turn",
"type": "STRING"
}
]
}

View File

@ -26,7 +26,14 @@
} }
}, },
"sso": { "sso": {
"enabled": false "enabled": false,
"issuer" : "devicemgt",
"appName" : "devicemgt",
"identityProviderUrl" : "https://localhost:9443/samlsso",
"acs": "https://localhost:9443/devicemgt/uuf/sso/acs",
"identityAlias": "wso2carbon",
"responseSigningEnabled" : "true",
"useTenantKey": false
} }
}, },
"errorPages": { "errorPages": {

View File

@ -26,7 +26,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.exception.RaspberrypiDeviceMgtPluginException; import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.exception.RaspberrypiDeviceMgtPluginException;
@ -49,13 +49,13 @@ public class RaspberrypiManager implements DeviceManager {
} }
@Override @Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration) public boolean saveConfiguration(PlatformConfiguration tenantConfiguration)
throws DeviceManagementException { throws DeviceManagementException {
return false; return false;
} }
@Override @Override
public TenantConfiguration getConfiguration() throws DeviceManagementException { public PlatformConfiguration getConfiguration() throws DeviceManagementException {
return null; return null;
} }

View File

@ -173,6 +173,13 @@
<artifactId>json</artifactId> <artifactId>json</artifactId>
</dependency> </dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>
</dependencies> </dependencies>

View File

@ -23,12 +23,12 @@ import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.AbstractHandler;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.http.HTTPTransportHandler;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.exception.AgentCoreOperationException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.exception.AgentCoreOperationException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.http.HTTPTransportHandler;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -191,21 +191,19 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
private void executeDataPush(String pushDataPayload) { private void executeDataPush(String pushDataPayload) {
AgentManager agentManager = AgentManager.getInstance(); AgentManager agentManager = AgentManager.getInstance();
int responseCode = -1;
String pushDataEndPointURL = agentManager.getPushDataAPIEP(); String pushDataEndPointURL = agentManager.getPushDataAPIEP();
HttpURLConnection httpConnection = null; HttpURLConnection httpConnection;
int responseCode = -1;
try { try {
httpConnection = TransportUtils.getHttpConnection(agentManager.getPushDataAPIEP()); httpConnection = TransportUtils.getHttpConnection(agentManager.getPushDataAPIEP());
httpConnection.setRequestMethod(AgentConstants.HTTP_POST); httpConnection.setRequestMethod(AgentConstants.HTTP_POST);
httpConnection.setRequestProperty("Authorization", "Bearer " + httpConnection.setRequestProperty("Authorization",
agentManager.getAgentConfigs().getAuthToken()); "Bearer " + agentManager.getAgentConfigs().getAuthToken());
httpConnection.setRequestProperty("Content-Type", httpConnection.setRequestProperty("Content-Type", AgentConstants.APPLICATION_JSON);
AgentConstants.APPLICATION_JSON_TYPE);
httpConnection.setDoOutput(true); httpConnection.setDoOutput(true);
DataOutputStream dataOutPutWriter = new DataOutputStream( DataOutputStream dataOutPutWriter = new DataOutputStream(httpConnection.getOutputStream());
httpConnection.getOutputStream());
dataOutPutWriter.writeBytes(pushDataPayload); dataOutPutWriter.writeBytes(pushDataPayload);
dataOutPutWriter.flush(); dataOutPutWriter.flush();
dataOutPutWriter.close(); dataOutPutWriter.close();
@ -225,39 +223,34 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
} catch (IOException exception) { } catch (IOException exception) {
String errorMsg = String errorMsg =
"An IO error occurred whilst trying to get the response code from: " + "An IO error occurred whilst trying to get the response code from: " +
pushDataEndPointURL + " for a " + AgentConstants.HTTP_POST + pushDataEndPointURL + " for a " + AgentConstants.HTTP_POST + " method.";
" " + "method.";
log.error(AgentConstants.LOG_APPENDER + errorMsg); log.error(AgentConstants.LOG_APPENDER + errorMsg);
} catch (TransportHandlerException exception) { } catch (TransportHandlerException exception) {
log.error(AgentConstants.LOG_APPENDER + log.error(AgentConstants.LOG_APPENDER +
"Error encountered whilst trying to create HTTP-Connection " + "Error encountered whilst trying to create HTTP-Connection to IoT-Server EP at: " +
"to IoT-Server EP at: " +
pushDataEndPointURL); pushDataEndPointURL);
} }
if (responseCode == HttpStatus.CONFLICT_409 || if (responseCode == HttpStatus.CONFLICT_409 ||
responseCode == HttpStatus.PRECONDITION_FAILED_412) { responseCode == HttpStatus.PRECONDITION_FAILED_412) {
log.warn(AgentConstants.LOG_APPENDER + log.warn(AgentConstants.LOG_APPENDER +
"DeviceIP is being Re-Registered due to Push-Data failure " + "DeviceIP is being Re-Registered due to Push-Data failure with response code: " +
"with response code: " +
responseCode); responseCode);
registerThisDevice(); registerThisDevice();
} else if (responseCode != HttpStatus.NO_CONTENT_204) { } else if (responseCode != HttpStatus.NO_CONTENT_204) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.error(AgentConstants.LOG_APPENDER + "Status Code: " + responseCode + log.error(AgentConstants.LOG_APPENDER + "Status Code: " + responseCode +
" encountered whilst trying to Push-Device-Data to IoT " + " encountered whilst trying to Push-Device-Data to IoT Server at: " +
"Server at: " +
agentManager.getPushDataAPIEP()); agentManager.getPushDataAPIEP());
} }
agentManager.updateAgentStatus(AgentConstants.SERVER_NOT_RESPONDING); agentManager.updateAgentStatus(AgentConstants.SERVER_NOT_RESPONDING);
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug(AgentConstants.LOG_APPENDER + "Push-Data call with payload - " + log.debug(AgentConstants.LOG_APPENDER + "Push-Data call with payload - " + pushDataPayload +
pushDataPayload + ", to IoT Server returned status " + ", to IoT Server returned status " + responseCode);
responseCode);
} }
} }
@ -272,16 +265,14 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
closeConnection(); closeConnection();
} catch (Exception e) { } catch (Exception e) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.warn(AgentConstants.LOG_APPENDER + log.warn(AgentConstants.LOG_APPENDER + "Unable to 'STOP' HTTP server at port: " + port);
"Unable to 'STOP' HTTP server at port: " + port);
} }
try { try {
Thread.sleep(timeoutInterval); Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) { } catch (InterruptedException e1) {
log.error(AgentConstants.LOG_APPENDER + log.error(
"HTTP-Termination: Thread Sleep Interrupt " + AgentConstants.LOG_APPENDER + "HTTP-Termination: Thread Sleep Interrupt Exception");
"Exception");
} }
} }
} }
@ -398,8 +389,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
} catch (TransportHandlerException e) { } catch (TransportHandlerException e) {
String errorMsg = String errorMsg =
"Protocol specific error occurred when trying to fetch an HTTPConnection to:" + "Protocol specific error occurred when trying to fetch an HTTPConnection to:" +
" " + " " + registerEndpointURLString;
registerEndpointURLString;
log.error(AgentConstants.LOG_APPENDER + errorMsg); log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException(); throw new AgentCoreOperationException();
} }
@ -419,8 +409,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
} catch (IOException exception) { } catch (IOException exception) {
String errorMsg = "An IO error occurred whilst trying to get the response code from:" + String errorMsg = "An IO error occurred whilst trying to get the response code from:" +
" " + " " + registerEndpointURLString + " for a " + AgentConstants.HTTP_POST + " method.";
registerEndpointURLString + " for a " + AgentConstants.HTTP_POST + " method.";
log.error(AgentConstants.LOG_APPENDER + errorMsg); log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException(errorMsg, exception); throw new AgentCoreOperationException(errorMsg, exception);
} }
@ -436,7 +425,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
/*------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------*/
/* Utility methods relevant to creating and sending HTTP requests to the Iot-Server */ /* Utility methods relevant to creating and sending HTTP requests to the Iot-Server */
/*------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------*/
/** /**
* This method is used to get the IP of the device in which the agent is run on. * This method is used to get the IP of the device in which the agent is run on.

View File

@ -22,6 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentUtilOperations; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentUtilOperations;
@ -35,13 +36,14 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
//TODO:: Lincense heade, comments and SPECIFIC class name since its not generic //TODO:: Lincence header, comments and SPECIFIC class name since its not generic
public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
private static final Log log = LogFactory.getLog(FireAlarmMQTTCommunicator.class); private static final Log log = LogFactory.getLog(FireAlarmMQTTCommunicator.class);
private ScheduledExecutorService service = Executors.newScheduledThreadPool(2); private ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
private ScheduledFuture<?> dataPushServiceHandler; private ScheduledFuture<?> dataPushServiceHandler;
private static final String DEFAULT_PASSWORD = "";
public FireAlarmMQTTCommunicator(String deviceOwner, String deviceType, public FireAlarmMQTTCommunicator(String deviceOwner, String deviceType,
String mqttBrokerEndPoint, String subscribeTopic) { String mqttBrokerEndPoint, String subscribeTopic) {
@ -68,18 +70,23 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
public void run() { public void run() {
while (!isConnected()) { while (!isConnected()) {
try { try {
connectToQueue(); connectToQueue(agentManager.getAgentConfigs().getAuthToken(), DEFAULT_PASSWORD);
agentManager.updateAgentStatus("Connected to MQTT Queue"); agentManager.updateAgentStatus("Connected to MQTT Queue");
} catch (TransportHandlerException e) { } catch (TransportHandlerException e) {
log.warn(AgentConstants.LOG_APPENDER + "Connection to MQTT Broker at: " + mqttBrokerEndPoint + log.warn(AgentConstants.LOG_APPENDER + "Connection to MQTT Broker at: " + mqttBrokerEndPoint +
" failed.\n Will retry in " + timeoutInterval + " milli-seconds."); " failed.\n Will retry in " + timeoutInterval + " milli-seconds.");
if (e.getCause() != null && e.getCause() instanceof MqttSecurityException) {
refreshOAuthToken((MqttSecurityException) e.getCause());
}
} }
try{ try {
subscribeToQueue(); if (isConnected()) {
agentManager.updateAgentStatus("Subscribed to MQTT Queue"); subscribeToQueue();
publishDeviceData(); agentManager.updateAgentStatus("Subscribed to MQTT Queue");
publishDeviceData();
}
} catch (TransportHandlerException e) { } catch (TransportHandlerException e) {
log.warn(AgentConstants.LOG_APPENDER + "Subscription to MQTT Broker at: " + log.warn(AgentConstants.LOG_APPENDER + "Subscription to MQTT Broker at: " +
mqttBrokerEndPoint + " failed"); mqttBrokerEndPoint + " failed");
@ -100,6 +107,26 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
connectorThread.start(); connectorThread.start();
} }
private void refreshOAuthToken(final MqttSecurityException exception) {
Runnable tokenRefresher = new Runnable() {
public void run() {
String authenticationMethod = AgentUtilOperations.getAuthenticationMethod();
try {
if (exception.getReasonCode() == MqttSecurityException.REASON_CODE_FAILED_AUTHENTICATION &&
authenticationMethod.equals(AgentConstants.TOKEN_AUTHENTICATION_METHOD)) {
AgentUtilOperations.refreshOAuthToken();
}
} catch (AgentCoreOperationException e1) {
log.error(AgentConstants.LOG_APPENDER + "Token Refresh Attempt Failed. " + e1);
}
}
};
Thread connectorThread = new Thread(tokenRefresher);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Override @Override
public void processIncomingMessage(MqttMessage message, String... messageParams) { public void processIncomingMessage(MqttMessage message, String... messageParams) {

View File

@ -24,150 +24,159 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core;
* downloading the device agent from the IoT-Server. * downloading the device agent from the IoT-Server.
*/ */
public class AgentConfiguration { public class AgentConfiguration {
private String tenantDomain; private String tenantDomain;
private String deviceOwner; private String deviceOwner;
private String deviceId; private String deviceId;
private String deviceName; private String deviceName;
private String controllerContext; private String controllerContext;
private String scepContext; private String scepContext;
private String HTTPS_ServerEndpoint; private String HTTPS_ServerEndpoint;
private String HTTP_ServerEndpoint; private String HTTP_ServerEndpoint;
private String apimGatewayEndpoint; private String apimGatewayEndpoint;
private String mqttBrokerEndpoint; private String mqttBrokerEndpoint;
private String xmppServerEndpoint; private String xmppServerEndpoint;
private String authMethod; private String apiApplicationKey;
private String authToken; private String authMethod;
private String refreshToken; private String authToken;
private int dataPushInterval; private String refreshToken;
private String xmppServerName; private int dataPushInterval;
private String xmppServerName;
public String getTenantDomain() { public String getTenantDomain() {
return tenantDomain; return tenantDomain;
} }
public void setTenantDomain(String tenantDomain) { public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain; this.tenantDomain = tenantDomain;
} }
public String getDeviceOwner() { public String getDeviceOwner() {
return deviceOwner; return deviceOwner;
} }
public void setDeviceOwner(String deviceOwner) { public void setDeviceOwner(String deviceOwner) {
this.deviceOwner = deviceOwner; this.deviceOwner = deviceOwner;
} }
public String getDeviceId() { public String getDeviceId() {
return deviceId; return deviceId;
} }
public void setDeviceId(String deviceId) { public void setDeviceId(String deviceId) {
this.deviceId = deviceId; this.deviceId = deviceId;
} }
public String getDeviceName() { public String getDeviceName() {
return deviceName; return deviceName;
} }
public void setDeviceName(String deviceName) { public void setDeviceName(String deviceName) {
this.deviceName = deviceName; this.deviceName = deviceName;
} }
public String getControllerContext() { public String getControllerContext() {
return controllerContext; return controllerContext;
} }
public void setControllerContext(String controllerContext) { public void setControllerContext(String controllerContext) {
this.controllerContext = controllerContext; this.controllerContext = controllerContext;
} }
public String getHTTPS_ServerEndpoint() { public String getHTTPS_ServerEndpoint() {
return HTTPS_ServerEndpoint; return HTTPS_ServerEndpoint;
} }
public void setHTTPS_ServerEndpoint(String HTTPS_ServerEndpoint) { public void setHTTPS_ServerEndpoint(String HTTPS_ServerEndpoint) {
this.HTTPS_ServerEndpoint = HTTPS_ServerEndpoint; this.HTTPS_ServerEndpoint = HTTPS_ServerEndpoint;
} }
public String getHTTP_ServerEndpoint() { public String getHTTP_ServerEndpoint() {
return HTTP_ServerEndpoint; return HTTP_ServerEndpoint;
} }
public void setHTTP_ServerEndpoint(String HTTP_ServerEndpoint) { public void setHTTP_ServerEndpoint(String HTTP_ServerEndpoint) {
this.HTTP_ServerEndpoint = HTTP_ServerEndpoint; this.HTTP_ServerEndpoint = HTTP_ServerEndpoint;
} }
public String getApimGatewayEndpoint() { public String getApimGatewayEndpoint() {
return apimGatewayEndpoint; return apimGatewayEndpoint;
} }
public void setApimGatewayEndpoint(String apimGatewayEndpoint) { public void setApimGatewayEndpoint(String apimGatewayEndpoint) {
this.apimGatewayEndpoint = apimGatewayEndpoint; this.apimGatewayEndpoint = apimGatewayEndpoint;
} }
public String getMqttBrokerEndpoint() { public String getMqttBrokerEndpoint() {
return mqttBrokerEndpoint; return mqttBrokerEndpoint;
} }
public void setMqttBrokerEndpoint(String mqttBrokerEndpoint) { public void setMqttBrokerEndpoint(String mqttBrokerEndpoint) {
this.mqttBrokerEndpoint = mqttBrokerEndpoint; this.mqttBrokerEndpoint = mqttBrokerEndpoint;
} }
public String getXmppServerEndpoint() { public String getXmppServerEndpoint() {
return xmppServerEndpoint; return xmppServerEndpoint;
} }
public void setXmppServerEndpoint(String xmppServerEndpoint) { public void setXmppServerEndpoint(String xmppServerEndpoint) {
this.xmppServerEndpoint = xmppServerEndpoint; this.xmppServerEndpoint = xmppServerEndpoint;
} }
public String getAuthMethod() { public String getApiApplicationKey() {
return authMethod; return apiApplicationKey;
} }
public void setAuthMethod(String authMethod) { public void setApiApplicationKey(String apiApplicationKey) {
this.authMethod = authMethod; this.apiApplicationKey = apiApplicationKey;
} }
public String getAuthToken() { public String getAuthMethod() {
return authToken; return authMethod;
} }
public void setAuthToken(String authToken) { public void setAuthMethod(String authMethod) {
this.authToken = authToken; this.authMethod = authMethod;
} }
public String getRefreshToken() { public String getAuthToken() {
return refreshToken; return authToken;
} }
public void setRefreshToken(String refreshToken) { public void setAuthToken(String authToken) {
this.refreshToken = refreshToken; this.authToken = authToken;
} }
public int getDataPushInterval() { public String getRefreshToken() {
return dataPushInterval; return refreshToken;
} }
public void setDataPushInterval(int dataPushInterval) { public void setRefreshToken(String refreshToken) {
this.dataPushInterval = dataPushInterval; this.refreshToken = refreshToken;
} }
public String getScepContext() { public int getDataPushInterval() {
return scepContext; return dataPushInterval;
} }
public void setScepContext(String scepContext) { public void setDataPushInterval(int dataPushInterval) {
this.scepContext = scepContext; this.dataPushInterval = dataPushInterval;
} }
public String getXmppServerName() { public String getScepContext() {
return xmppServerName; return scepContext;
} }
public void setXmppServerName(String xmppServerName) { public void setScepContext(String scepContext) {
this.xmppServerName = xmppServerName; this.scepContext = scepContext;
} }
public String getXmppServerName() {
return xmppServerName;
}
public void setXmppServerName(String xmppServerName) {
this.xmppServerName = xmppServerName;
}
} }

View File

@ -19,94 +19,109 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core;
public class AgentConstants { public class AgentConstants {
public static final String DEVICE_TYPE = "virtual_firealarm"; public static final String DEVICE_TYPE = "virtual_firealarm";
public static final String LOG_APPENDER = "AGENT_LOG:: "; public static final String LOG_APPENDER = "AGENT_LOG:: ";
public static final String PROPERTIES_FILE_PATH = ""; public static final String PROPERTIES_FILE_PATH = "";
public static final int DEFAULT_RETRY_THREAD_INTERVAL = 5000; // time in millis public static final int DEFAULT_RETRY_THREAD_INTERVAL = 5000; // time in millis
/* --------------------------------------------------------------------------------------- public static final String TOKEN_AUTHENTICATION_METHOD = "token";
IoT-Server specific information /* ---------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------- */ IoT-Server specific information
public static final String DEVICE_CONTROLLER_API_EP = "/virtual_firealarm/controller"; --------------------------------------------------------------------------------------- */
public static final String DEVICE_ENROLLMENT_API_EP = "/scep"; public static final String DEVICE_ENROLLMENT_API_EP = "/scep";
public static final String DEVICE_REGISTER_API_EP = "/register"; public static final String DEVICE_REGISTER_API_EP = "/register";
public static final String DEVICE_PUSH_TEMPERATURE_API_EP = "/temperature"; public static final String DEVICE_PUSH_TEMPERATURE_API_EP = "/temperature";
public static final String PUSH_DATA_PAYLOAD = public static final String PUSH_DATA_PAYLOAD =
"{\"owner\":\"%s\",\"deviceId\":\"%s\",\"reply\":\"%s\",\"value\":\"%s\"}"; "{\"owner\":\"%s\",\"deviceId\":\"%s\",\"reply\":\"%s\",\"value\":\"%s\"}";
public static final String PUSH_SIMULATION_DATA_PAYLOAD = public static final String PUSH_SIMULATION_DATA_PAYLOAD =
"{\"owner\":\"%s\",\"deviceId\":\"%s\",\"reply\":\"%s\",\"value\":\"%s\",\"isSimulated\":\"%s\",\"duration\":\"%s\",\"frequency\":\"%s\"}"; "{\"owner\":\"%s\",\"deviceId\":\"%s\",\"reply\":\"%s\",\"value\":\"%s\",\"isSimulated\":\"%s\"," +
"\"duration\":\"%s\",\"frequency\":\"%s\"}";
public static final String AGENT_CONTROL_APP_EP = "/devicemgt/device/%s?id=%s"; public static final String DEVICE_DETAILS_PAGE_EP = "/devicemgt/device/%s?id=%s";
public static final String DEVICE_DETAILS_PAGE_EP = "/devicemgt/device/%s?id=%s"; public static final String DEVICE_ANALYTICS_PAGE_URL =
public static final String DEVICE_ANALYTICS_PAGE_URL = "/devicemgt/device/virtual_firealarm/analytics?deviceId=%s&deviceName=%s"; "/devicemgt/device/virtual_firealarm/analytics?deviceId=%s&deviceName=%s";
/* --------------------------------------------------------------------------------------- /* ---------------------------------------------------------------------------------------
HTTP Connection specific information for communicating with IoT-Server HTTP Connection specific information for communicating with IoT-Server
--------------------------------------------------------------------------------------- */ --------------------------------------------------------------------------------------- */
public static final String HTTP_POST = "POST"; public static final String HTTP_POST = "POST";
public static final String HTTP_GET = "GET"; public static final String HTTP_GET = "GET";
public static final String APPLICATION_JSON_TYPE = "application/json"; public static final String AUTHORIZATION_HEADER = "Authorization";
public static final String REGISTERED = "Registered"; public static final String CONTENT_TYPE_HEADER = "Content-Type";
public static final String NOT_REGISTERED = "Not-Registered"; public static final String APPLICATION_JSON = "application/json";
public static final String REGISTRATION_FAILED = "Registration Failed"; public static final String X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
public static final String RETRYING_TO_REGISTER = "Registration Failed. Re-trying.."; public static final String REGISTERED = "Registered";
public static final String SERVER_NOT_RESPONDING = "Server not responding.."; public static final String NOT_REGISTERED = "Not-Registered";
public static final String REGISTRATION_FAILED = "Registration Failed";
public static final String RETRYING_TO_REGISTER = "Registration Failed. Re-trying..";
public static final String SERVER_NOT_RESPONDING = "Server not responding..";
/* --------------------------------------------------------------------------------------- /* ---------------------------------------------------------------------------------------
MQTT Connection specific information MQTT Connection specific information
--------------------------------------------------------------------------------------- */ --------------------------------------------------------------------------------------- */
public static final int DEFAULT_MQTT_RECONNECTION_INTERVAL = 2; // time in seconds public static final int DEFAULT_MQTT_RECONNECTION_INTERVAL = 2; // time in seconds
public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0;
public static final String MQTT_SUBSCRIBE_TOPIC = "%s/" + DEVICE_TYPE + "/%s"; public static final String MQTT_SUBSCRIBE_TOPIC = "%s/" + DEVICE_TYPE + "/%s";
public static final String MQTT_PUBLISH_TOPIC = "%s/" + DEVICE_TYPE + "/%s/publisher"; public static final String MQTT_PUBLISH_TOPIC = "%s/" + DEVICE_TYPE + "/%s/publisher";
/* ---------------------------------------------------------------------------------------
XMPP Connection specific information /* ---------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------- */ Device/Agent specific properties to be read from the 'deviceConfig.properties' file
public static final String XMPP_ADMIN_ACCOUNT_UNAME = "admin"; --------------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------------- public static final String AGENT_PROPERTIES_FILE_NAME = "deviceConfig.properties";
Device/Agent specific properties to be read from the 'deviceConfig.properties' file public static final String TENANT_DOMAIN = "tenantDomain";
--------------------------------------------------------------------------------------- */ public static final String DEVICE_OWNER_PROPERTY = "owner";
public static final String AGENT_PROPERTIES_FILE_NAME = "deviceConfig.properties"; public static final String DEVICE_ID_PROPERTY = "deviceId";
public static final String TENANT_DOMAIN = "tenantDomain"; public static final String DEVICE_NAME_PROPERTY = "device-name";
public static final String DEVICE_OWNER_PROPERTY = "owner"; public static final String DEVICE_CONTROLLER_CONTEXT_PROPERTY = "controller-context";
public static final String DEVICE_ID_PROPERTY = "deviceId"; public static final String DEVICE_SCEP_CONTEXT_PROPERTY = "scep-context";
public static final String DEVICE_NAME_PROPERTY = "device-name"; public static final String SERVER_HTTPS_EP_PROPERTY = "https-ep";
public static final String DEVICE_CONTROLLER_CONTEXT_PROPERTY = "controller-context"; public static final String SERVER_HTTP_EP_PROPERTY = "http-ep";
public static final String DEVICE_SCEP_CONTEXT_PROPERTY = "scep-context"; public static final String APIM_GATEWAY_EP_PROPERTY = "apim-ep";
public static final String SERVER_HTTPS_EP_PROPERTY = "https-ep"; public static final String MQTT_BROKER_EP_PROPERTY = "mqtt-ep";
public static final String SERVER_HTTP_EP_PROPERTY = "http-ep"; public static final String XMPP_SERVER_EP_PROPERTY = "xmpp-ep";
public static final String APIM_GATEWAY_EP_PROPERTY = "apim-ep"; public static final String XMPP_SERVER_NAME_PROPERTY = "xmpp-server-name";
public static final String MQTT_BROKER_EP_PROPERTY = "mqtt-ep"; public static final String API_APPLICATION_KEY = "application-key";
public static final String XMPP_SERVER_EP_PROPERTY = "xmpp-ep"; public static final String AUTH_METHOD_PROPERTY = "auth-method";
public static final String XMPP_SERVER_NAME_PROPERTY = "xmpp-server-name"; public static final String AUTH_TOKEN_PROPERTY = "auth-token";
public static final String AUTH_METHOD_PROPERTY = "auth-method"; public static final String REFRESH_TOKEN_PROPERTY = "refresh-token";
public static final String AUTH_TOKEN_PROPERTY = "auth-token"; public static final String NETWORK_INTERFACE_PROPERTY = "network-interface";
public static final String REFRESH_TOKEN_PROPERTY = "refresh-token"; public static final String PUSH_INTERVAL_PROPERTY = "push-interval";
public static final String NETWORK_INTERFACE_PROPERTY = "network-interface"; /* ---------------------------------------------------------------------------------------
public static final String PUSH_INTERVAL_PROPERTY = "push-interval"; Default values for the Device/Agent specific configurations listed above
/* --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- */
Default values for the Device/Agent specific configurations listed above public static final String DEFAULT_NETWORK_INTERFACE = "en0";
--------------------------------------------------------------------------------------- */ public static final int DEFAULT_DATA_PUBLISH_INTERVAL = 15; // seconds
public static final String DEFAULT_NETWORK_INTERFACE = "en0"; public static final String DEFAULT_PROTOCOL = "MQTT";
public static final int DEFAULT_DATA_PUBLISH_INTERVAL = 15; // seconds /* ---------------------------------------------------------------------------------------
public static final String DEFAULT_PROTOCOL = "MQTT"; Control Signal specific constants to match the request context
/* --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- */
Control Signal specific constants to match the request context public static final String BULB_CONTROL = "BULB";
--------------------------------------------------------------------------------------- */ public static final String TEMPERATURE_CONTROL = "TEMPERATURE";
public static final String BULB_CONTROL = "BULB"; public static final String POLICY_SIGNAL = "POLICY";
public static final String TEMPERATURE_CONTROL = "TEMPERATURE"; public static final String HUMIDITY_CONTROL = "HUMIDITY";
public static final String POLICY_SIGNAL = "POLICY"; public static final String CONTROL_ON = "ON";
public static final String HUMIDITY_CONTROL = "HUMIDITY"; public static final String CONTROL_OFF = "OFF";
public static final String CONTROL_ON = "ON"; public static final String AUDIO_FILE_NAME = "fireAlarmSound.mid";
public static final String CONTROL_OFF = "OFF"; /* ---------------------------------------------------------------------------------------
public static final String AUDIO_FILE_NAME = "fireAlarmSound.mid"; Communication protocol specific Strings
/* --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- */
Communication protocol specific Strings public static final String TCP_PREFIX = "tcp://";
--------------------------------------------------------------------------------------- */ public static final String HTTP_PREFIX = "http://";
public static final String TCP_PREFIX = "tcp://"; public static final String HTTPS_PREFIX = "https://";
public static final String HTTP_PREFIX = "http://"; public static final String HTTP_PROTOCOL = "HTTP";
public static final String HTTPS_PREFIX = "https://"; public static final String MQTT_PROTOCOL = "MQTT";
public static final String HTTP_PROTOCOL = "HTTP"; public static final String XMPP_PROTOCOL = "XMPP";
public static final String MQTT_PROTOCOL = "MQTT"; public static final String PROTOCOL_PROPERTY = "Protocol";
public static final String XMPP_PROTOCOL = "XMPP"; public static final String HOST_PROPERTY = "Host";
public static final String PORT_PROPERTY = "Port";
/* ---------------------------------------------------------------------------------------
Keystore specific strings for the device trustStore
--------------------------------------------------------------------------------------- */
public static final String DEVICE_KEYSTORE_TYPE = "JKS";
public static final String DEVICE_KEYSTORE = "virtual_firealarm.jks";
public static final String DEVICE_KEYSTORE_PASSWORD = "wso2@virtual_firealarm";
public static final String DEVICE_PRIVATE_KEY_ALIAS = "virtual_firealarm_key";
public static final String DEVICE_CERT_ALIAS = "virtual_firealarm_cert";
public static final String SERVER_CA_CERT_ALIAS = "ca_iotServer";
} }

View File

@ -20,14 +20,14 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.communication.http.FireAlarmHTTPCommunicator;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.communication.mqtt.FireAlarmMQTTCommunicator;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.communication.xmpp.FireAlarmXMPPCommunicator;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.exception.AgentCoreOperationException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.exception.AgentCoreOperationException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandler; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandler;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportUtils; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.communication.http.FireAlarmHTTPCommunicator;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.communication.mqtt.FireAlarmMQTTCommunicator;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.communication.xmpp.FireAlarmXMPPCommunicator;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.virtual.VirtualHardwareManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.virtual.VirtualHardwareManager;
import java.util.ArrayList; import java.util.ArrayList;
@ -74,18 +74,19 @@ public class AgentManager {
public void init() { public void init() {
agentCommunicator = new HashMap<>(); agentCommunicator = new HashMap<>();
// Read IoT-Server specific configurations from the 'deviceConfig.properties' file // Read IoT-Server specific configurations from the 'deviceConfig.properties' file
try { try {
this.agentConfigs = AgentUtilOperations.readIoTServerConfigs(); this.agentConfigs = AgentUtilOperations.readIoTServerConfigs();
} catch (AgentCoreOperationException e) { } catch (AgentCoreOperationException e) {
log.error("Reading device configuration from configd file failed:\n"); log.error("Reading device configuration from configuration file failed:\n");
log.error(e); log.error(e);
System.exit(0); System.exit(0);
} }
// Initialise IoT-Server URL endpoints from the configuration read from file // Initialise IoT-Server URL endpoints from the configuration read from file
AgentUtilOperations.initializeServerEndPoints(); AgentUtilOperations.initializeServerEndPoints();
// Set the hostNameVerifier to the APIM-Server IPAddress to enable HTTPS handshake
AgentUtilOperations.setHTTPSConfigurations();
String analyticsPageContext = String.format(AgentConstants.DEVICE_ANALYTICS_PAGE_URL, String analyticsPageContext = String.format(AgentConstants.DEVICE_ANALYTICS_PAGE_URL,
agentConfigs.getDeviceId(), agentConfigs.getDeviceId(),
@ -153,7 +154,9 @@ public class AgentManager {
} }
try { try {
EnrollmentManager.getInstance().beginEnrollmentFlow(); if (!EnrollmentManager.getInstance().isEnrolled()) {
EnrollmentManager.getInstance().beginEnrollmentFlow();
}
} catch (AgentCoreOperationException e) { } catch (AgentCoreOperationException e) {
log.error("Device Enrollment Failed:\n"); log.error("Device Enrollment Failed:\n");
log.error(e); log.error(e);
@ -217,12 +220,16 @@ public class AgentManager {
/*------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------*/
/* Getter and Setter Methods for the private variables */ /* Getter and Setter Methods for the private variables */
/*------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------*/
public void setRootPath(String rootPath) { public void setRootPath(String rootPath) {
this.rootPath = rootPath; this.rootPath = rootPath;
} }
public String getRootPath() {
return rootPath;
}
public void setDeviceReady(boolean deviceReady) { public void setDeviceReady(boolean deviceReady) {
this.deviceReady = deviceReady; this.deviceReady = deviceReady;
} }
@ -324,6 +331,7 @@ public class AgentManager {
/** /**
* Get temperature reading from device * Get temperature reading from device
*
* @return Temperature * @return Temperature
*/ */
public int getTemperature() { public int getTemperature() {
@ -332,9 +340,10 @@ public class AgentManager {
/** /**
* Get humidity reading from device * Get humidity reading from device
*
* @return Humidity * @return Humidity
*/ */
public int getHumidity(){ public int getHumidity() {
return VirtualHardwareManager.getInstance().getHumidity(); return VirtualHardwareManager.getInstance().getHumidity();
} }

View File

@ -19,19 +19,30 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.http.HttpStatus;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.exception.AgentCoreOperationException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.exception.AgentCoreOperationException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.CommunicationUtils; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.CommunicationUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportUtils;
import java.io.File; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL; import java.net.URL;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -67,94 +78,104 @@ public class AgentUtilOperations {
Properties properties = new Properties(); Properties properties = new Properties();
InputStream propertiesInputStream = null; InputStream propertiesInputStream = null;
String propertiesFileName = AgentConstants.AGENT_PROPERTIES_FILE_NAME; String propertiesFileName = AgentConstants.AGENT_PROPERTIES_FILE_NAME;
String rootPath = "";
try { try {
ClassLoader loader = AgentUtilOperations.class.getClassLoader(); ClassLoader loader = AgentUtilOperations.class.getClassLoader();
URL path = loader.getResource(propertiesFileName); URL path = loader.getResource(propertiesFileName);
System.out.println(path);
String root = path.getPath().replace("wso2-firealarm-virtual-agent.jar!/deviceConfig.properties", "")
.replace("jar:", "").replace("file:", "");
root = URLDecoder.decode(root, StandardCharsets.UTF_8.toString()); if (path != null) {
agentManager.setRootPath(root); log.info(AgentConstants.LOG_APPENDER + path);
rootPath = path.getPath().replace("wso2-firealarm-virtual-agent.jar!/deviceConfig.properties", "")
.replace("jar:", "").replace("file:", "");
String deviceConfigFilePath = root + AgentConstants.AGENT_PROPERTIES_FILE_NAME; rootPath = URLDecoder.decode(rootPath, StandardCharsets.UTF_8.toString());
propertiesInputStream = new FileInputStream(deviceConfigFilePath); agentManager.setRootPath(rootPath);
//load a properties file from class path, inside static method String deviceConfigFilePath = rootPath + AgentConstants.AGENT_PROPERTIES_FILE_NAME;
properties.load(propertiesInputStream); propertiesInputStream = new FileInputStream(deviceConfigFilePath);
iotServerConfigs.setTenantDomain(properties.getProperty( //load a properties file from class path, inside static method
AgentConstants.TENANT_DOMAIN)); properties.load(propertiesInputStream);
iotServerConfigs.setDeviceOwner(properties.getProperty(
AgentConstants.DEVICE_OWNER_PROPERTY));
iotServerConfigs.setDeviceId(properties.getProperty(
AgentConstants.DEVICE_ID_PROPERTY));
iotServerConfigs.setDeviceName(properties.getProperty(
AgentConstants.DEVICE_NAME_PROPERTY));
iotServerConfigs.setControllerContext(properties.getProperty(
AgentConstants.DEVICE_CONTROLLER_CONTEXT_PROPERTY));
iotServerConfigs.setScepContext(properties.getProperty(
AgentConstants.DEVICE_SCEP_CONTEXT_PROPERTY));
iotServerConfigs.setHTTPS_ServerEndpoint(properties.getProperty(
AgentConstants.SERVER_HTTPS_EP_PROPERTY));
iotServerConfigs.setHTTP_ServerEndpoint(properties.getProperty(
AgentConstants.SERVER_HTTP_EP_PROPERTY));
iotServerConfigs.setApimGatewayEndpoint(properties.getProperty(
AgentConstants.APIM_GATEWAY_EP_PROPERTY));
iotServerConfigs.setMqttBrokerEndpoint(properties.getProperty(
AgentConstants.MQTT_BROKER_EP_PROPERTY));
iotServerConfigs.setXmppServerEndpoint(properties.getProperty(
AgentConstants.XMPP_SERVER_EP_PROPERTY));
iotServerConfigs.setXmppServerName(properties.getProperty(
AgentConstants.XMPP_SERVER_NAME_PROPERTY));
iotServerConfigs.setAuthMethod(properties.getProperty(
AgentConstants.AUTH_METHOD_PROPERTY));
iotServerConfigs.setAuthToken(properties.getProperty(
AgentConstants.AUTH_TOKEN_PROPERTY));
iotServerConfigs.setRefreshToken(properties.getProperty(
AgentConstants.REFRESH_TOKEN_PROPERTY));
iotServerConfigs.setDataPushInterval(Integer.parseInt(properties.getProperty(
AgentConstants.PUSH_INTERVAL_PROPERTY)));
log.info(AgentConstants.LOG_APPENDER + "Tenant Domain: " + iotServerConfigs.setTenantDomain(properties.getProperty(
iotServerConfigs.getTenantDomain()); AgentConstants.TENANT_DOMAIN));
log.info(AgentConstants.LOG_APPENDER + "Device Owner: " + iotServerConfigs.setDeviceOwner(properties.getProperty(
iotServerConfigs.getDeviceOwner()); AgentConstants.DEVICE_OWNER_PROPERTY));
log.info(AgentConstants.LOG_APPENDER + "Device ID: " + iotServerConfigs.getDeviceId()); iotServerConfigs.setDeviceId(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "Device Name: " + AgentConstants.DEVICE_ID_PROPERTY));
iotServerConfigs.getDeviceName()); iotServerConfigs.setDeviceName(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "Device Controller Context: " + AgentConstants.DEVICE_NAME_PROPERTY));
iotServerConfigs.getControllerContext()); iotServerConfigs.setControllerContext(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "IoT Server HTTPS EndPoint: " + AgentConstants.DEVICE_CONTROLLER_CONTEXT_PROPERTY));
iotServerConfigs.getHTTPS_ServerEndpoint()); iotServerConfigs.setScepContext(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "IoT Server HTTP EndPoint: " + AgentConstants.DEVICE_SCEP_CONTEXT_PROPERTY));
iotServerConfigs.getHTTP_ServerEndpoint()); iotServerConfigs.setHTTPS_ServerEndpoint(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "API-Manager Gateway EndPoint: " + AgentConstants.SERVER_HTTPS_EP_PROPERTY));
iotServerConfigs.getApimGatewayEndpoint()); iotServerConfigs.setHTTP_ServerEndpoint(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "MQTT Broker EndPoint: " + AgentConstants.SERVER_HTTP_EP_PROPERTY));
iotServerConfigs.getMqttBrokerEndpoint()); iotServerConfigs.setApimGatewayEndpoint(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "XMPP Server EndPoint: " + AgentConstants.APIM_GATEWAY_EP_PROPERTY));
iotServerConfigs.getXmppServerEndpoint()); iotServerConfigs.setMqttBrokerEndpoint(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "Authentication Method: " + AgentConstants.MQTT_BROKER_EP_PROPERTY));
iotServerConfigs.getAuthMethod()); iotServerConfigs.setXmppServerEndpoint(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "Authentication Token: " + AgentConstants.XMPP_SERVER_EP_PROPERTY));
iotServerConfigs.getAuthToken()); iotServerConfigs.setXmppServerName(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "Refresh Token: " + AgentConstants.XMPP_SERVER_NAME_PROPERTY));
iotServerConfigs.getRefreshToken()); iotServerConfigs.setApiApplicationKey(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "Data Push Interval: " + AgentConstants.API_APPLICATION_KEY));
iotServerConfigs.getDataPushInterval()); iotServerConfigs.setAuthMethod(properties.getProperty(
log.info(AgentConstants.LOG_APPENDER + "XMPP Server Name: " + AgentConstants.AUTH_METHOD_PROPERTY));
iotServerConfigs.getXmppServerName()); iotServerConfigs.setAuthToken(properties.getProperty(
AgentConstants.AUTH_TOKEN_PROPERTY));
iotServerConfigs.setRefreshToken(properties.getProperty(
AgentConstants.REFRESH_TOKEN_PROPERTY));
iotServerConfigs.setDataPushInterval(Integer.parseInt(properties.getProperty(
AgentConstants.PUSH_INTERVAL_PROPERTY)));
log.info(AgentConstants.LOG_APPENDER + "Tenant Domain: " +
iotServerConfigs.getTenantDomain());
log.info(AgentConstants.LOG_APPENDER + "Device Owner: " +
iotServerConfigs.getDeviceOwner());
log.info(AgentConstants.LOG_APPENDER + "Device ID: " + iotServerConfigs.getDeviceId());
log.info(AgentConstants.LOG_APPENDER + "Device Name: " +
iotServerConfigs.getDeviceName());
log.info(AgentConstants.LOG_APPENDER + "Device Controller Context: " +
iotServerConfigs.getControllerContext());
log.info(AgentConstants.LOG_APPENDER + "IoT Server HTTPS EndPoint: " +
iotServerConfigs.getHTTPS_ServerEndpoint());
log.info(AgentConstants.LOG_APPENDER + "IoT Server HTTP EndPoint: " +
iotServerConfigs.getHTTP_ServerEndpoint());
log.info(AgentConstants.LOG_APPENDER + "API-Manager Gateway EndPoint: " +
iotServerConfigs.getApimGatewayEndpoint());
log.info(AgentConstants.LOG_APPENDER + "MQTT Broker EndPoint: " +
iotServerConfigs.getMqttBrokerEndpoint());
log.info(AgentConstants.LOG_APPENDER + "XMPP Server EndPoint: " +
iotServerConfigs.getXmppServerEndpoint());
log.info(AgentConstants.LOG_APPENDER + "Authentication Method: " +
iotServerConfigs.getAuthMethod());
log.info(AgentConstants.LOG_APPENDER + "Base64Encoded API Application Key: " +
iotServerConfigs.getApiApplicationKey());
log.info(AgentConstants.LOG_APPENDER + "Authentication Token: " +
iotServerConfigs.getAuthToken());
log.info(AgentConstants.LOG_APPENDER + "Refresh Token: " +
iotServerConfigs.getRefreshToken());
log.info(AgentConstants.LOG_APPENDER + "Data Push Interval: " +
iotServerConfigs.getDataPushInterval());
log.info(AgentConstants.LOG_APPENDER + "XMPP Server Name: " +
iotServerConfigs.getXmppServerName());
} else {
throw new AgentCoreOperationException(
"Failed to load path of resource [" + propertiesFileName + "] from this classpath.");
}
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
String errorMsg = "[" + propertiesFileName + "] file not found at: " + AgentConstants.PROPERTIES_FILE_PATH; String errorMsg = "[" + propertiesFileName + "] file not found at: " + rootPath;
log.error(AgentConstants.LOG_APPENDER + errorMsg); log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException(errorMsg); throw new AgentCoreOperationException(errorMsg);
} catch (IOException ex) { } catch (IOException ex) {
String errorMsg = "Error occurred whilst trying to fetch [" + propertiesFileName + "] from: " + String errorMsg = "Error occurred whilst trying to fetch [" + propertiesFileName + "] from: " +
AgentConstants.PROPERTIES_FILE_PATH; AgentConstants.PROPERTIES_FILE_PATH;
log.error(AgentConstants.LOG_APPENDER + errorMsg); log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException(errorMsg); throw new AgentCoreOperationException(errorMsg);
} finally { } finally {
@ -174,10 +195,6 @@ public class AgentUtilOperations {
/** /**
* This method constructs the URLs for each of the API Endpoints called by the device agent * This method constructs the URLs for each of the API Endpoints called by the device agent
* Ex: Register API, Push-Data API * Ex: Register API, Push-Data API
*
* @throws AgentCoreOperationException if any error occurs at socket level whilst trying to
* retrieve the deviceIP of the network-interface read
* from the configs file
*/ */
public static void initializeServerEndPoints() { public static void initializeServerEndPoints() {
AgentManager agentManager = AgentManager.getInstance(); AgentManager agentManager = AgentManager.getInstance();
@ -209,6 +226,26 @@ public class AgentUtilOperations {
log.info(AgentConstants.LOG_APPENDER + "Push-Data API EndPoint: " + pushDataEndPointURL); log.info(AgentConstants.LOG_APPENDER + "Push-Data API EndPoint: " + pushDataEndPointURL);
} }
public static void setHTTPSConfigurations() {
String apimEndpoint = AgentManager.getInstance().getAgentConfigs().getApimGatewayEndpoint();
System.setProperty("javax.net.ssl.trustStore", AgentConstants.DEVICE_KEYSTORE);
System.setProperty("javax.net.ssl.trustStorePassword", AgentConstants.DEVICE_KEYSTORE_PASSWORD);
try {
final String apimHost = TransportUtils.getHostAndPort(apimEndpoint).get(AgentConstants.HOST_PROPERTY);
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return hostname.equals(apimHost);
}
});
} catch (TransportHandlerException e) {
log.error(AgentConstants.LOG_APPENDER +
"Failed to set HTTPS HostNameVerifier to the APIMServer-Host using the APIM-Endpoint " +
"string [" + apimEndpoint + "].");
log.error(AgentConstants.LOG_APPENDER + e);
}
}
public static String prepareSecurePayLoad(String message) throws AgentCoreOperationException { public static String prepareSecurePayLoad(String message) throws AgentCoreOperationException {
PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey(); PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey();
@ -227,7 +264,6 @@ public class AgentUtilOperations {
jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload); jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload);
//below statements are temporary fix. //below statements are temporary fix.
jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber()); jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber());
return jsonPayload.toString(); return jsonPayload.toString();
} }
@ -265,6 +301,138 @@ public class AgentUtilOperations {
return actualMessage; return actualMessage;
} }
public static String getAuthenticationMethod() {
String authMethod = AgentManager.getInstance().getAgentConfigs().getAuthMethod();
switch (authMethod) {
case AgentConstants.TOKEN_AUTHENTICATION_METHOD:
return AgentConstants.TOKEN_AUTHENTICATION_METHOD;
default:
return "";
}
}
public static void refreshOAuthToken() throws AgentCoreOperationException {
AgentManager agentManager = AgentManager.getInstance();
String tokenEndpoint = agentManager.getAgentConfigs().getApimGatewayEndpoint();
tokenEndpoint = tokenEndpoint + APIManagerTokenUtils.TOKEN_ENDPOINT;
HttpURLConnection httpConnection = null;
BufferedReader connectionBuffer = null;
String requestPayload;
String dataFromBuffer;
StringBuilder responseMessage = new StringBuilder();
try {
String refreshToken = agentManager.getAgentConfigs().getRefreshToken();
String applicationScope = "device_type_" + AgentConstants.DEVICE_TYPE +
" device_" + agentManager.getAgentConfigs().getDeviceId();
requestPayload = APIManagerTokenUtils.GRANT_TYPE + "=" + APIManagerTokenUtils.REFRESH_TOKEN + "&" +
APIManagerTokenUtils.REFRESH_TOKEN + "=" + refreshToken + "&" +
APIManagerTokenUtils.SCOPE + "=" + applicationScope;
httpConnection = TransportUtils.getHttpConnection(tokenEndpoint);
httpConnection.setRequestMethod(AgentConstants.HTTP_POST);
httpConnection.setRequestProperty(AgentConstants.AUTHORIZATION_HEADER,
"Basic " + agentManager.getAgentConfigs().getApiApplicationKey());
httpConnection.setRequestProperty(AgentConstants.CONTENT_TYPE_HEADER, AgentConstants.X_WWW_FORM_URLENCODED);
httpConnection.setDoOutput(true);
DataOutputStream dataOutPutWriter = new DataOutputStream(httpConnection.getOutputStream());
dataOutPutWriter.writeBytes(requestPayload);
dataOutPutWriter.flush();
dataOutPutWriter.close();
log.info(AgentConstants.LOG_APPENDER + "Request to refresh OAuth token was sent to [" +
httpConnection.getURL() + "] with payload [" + requestPayload + "].");
log.info(AgentConstants.LOG_APPENDER + "Response [" + httpConnection.getResponseCode() + ":" +
httpConnection.getResponseMessage() + "] was received for token refresh attempt.");
if (httpConnection.getResponseCode() == HttpStatus.OK_200) {
connectionBuffer = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
while ((dataFromBuffer = connectionBuffer.readLine()) != null) {
responseMessage.append(dataFromBuffer);
}
log.info(AgentConstants.LOG_APPENDER +
"Response " + responseMessage + " was received for the token refresh call.");
updateExistingTokens(responseMessage.toString());
} else if (httpConnection.getResponseCode() == HttpStatus.BAD_REQUEST_400) {
log.error(AgentConstants.LOG_APPENDER +
"Token refresh call returned with a [400 Bad Request].\nThe refresh-token has " +
"probably expired.\nPlease contact System-Admin to get a valid refresh-token.");
} else {
log.warn(AgentConstants.LOG_APPENDER + "There was an issue with refreshing the Access Token.");
}
} catch (TransportHandlerException e) {
throw new AgentCoreOperationException(e);
} catch (ProtocolException e) {
String errorMsg = "Protocol specific error occurred when trying to set method to " +
AgentConstants.HTTP_POST + " for endpoint at: " + tokenEndpoint;
log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "An IO error occurred whilst trying to get the response code from: " + tokenEndpoint +
" for a HTTP " + AgentConstants.HTTP_POST + " call.";
log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException(errorMsg, e);
} finally {
if (connectionBuffer != null) {
try {
connectionBuffer.close();
} catch (IOException e) {
log.error(AgentConstants.LOG_APPENDER +
"Error encounter whilst attempting to close buffer to connection at: " +
tokenEndpoint);
}
}
if (httpConnection != null) {
httpConnection.disconnect();
}
}
}
private static void updateExistingTokens(String responseFromTokenEP) throws AgentCoreOperationException {
JSONObject jsonTokenObject = new JSONObject(responseFromTokenEP);
String newAccessToken = jsonTokenObject.get(APIManagerTokenUtils.ACCESS_TOKEN).toString();
String newRefreshToken = jsonTokenObject.get(APIManagerTokenUtils.REFRESH_TOKEN).toString();
if (newAccessToken == null || newRefreshToken == null) {
String msg =
"Neither Access-Token nor Refresh-Token was found in the response [" + responseFromTokenEP + "].";
log.error(AgentConstants.LOG_APPENDER + msg);
throw new AgentCoreOperationException(msg);
}
AgentManager.getInstance().getAgentConfigs().setAuthToken(newAccessToken);
AgentManager.getInstance().getAgentConfigs().setRefreshToken(newRefreshToken);
String deviceConfigFilePath =
AgentManager.getInstance().getRootPath() + AgentConstants.AGENT_PROPERTIES_FILE_NAME;
try {
PropertiesConfiguration propertyFileConfiguration = new PropertiesConfiguration(deviceConfigFilePath);
propertyFileConfiguration.setProperty(AgentConstants.AUTH_TOKEN_PROPERTY, newAccessToken);
propertyFileConfiguration.setProperty(AgentConstants.REFRESH_TOKEN_PROPERTY, newRefreshToken);
propertyFileConfiguration.save();
} catch (ConfigurationException e) {
String msg = "Error occurred whilst trying to update the [" + AgentConstants.AGENT_PROPERTIES_FILE_NAME +
"] at: " + deviceConfigFilePath + " will the new tokens.";
log.error(AgentConstants.LOG_APPENDER + msg);
throw new AgentCoreOperationException(msg);
}
}
private class APIManagerTokenUtils {
public static final String TOKEN_ENDPOINT = "/oauth2/token";
public static final String GRANT_TYPE = "grant_type";
public static final String ACCESS_TOKEN = "access_token";
public static final String REFRESH_TOKEN = "refresh_token";
public static final String SCOPE = "scope";
}
} }

View File

@ -44,18 +44,24 @@ import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.exception.AgentCoreOperationException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.exception.AgentCoreOperationException;
import sun.security.x509.X509CertImpl; import sun.security.x509.X509CertImpl;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.security.Key;
import java.security.KeyPair; import java.security.KeyPair;
import java.security.KeyPairGenerator; import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException; import java.security.NoSuchProviderException;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.Security; import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertStore; import java.security.cert.CertStore;
import java.security.cert.CertStoreException; import java.security.cert.CertStoreException;
import java.security.cert.Certificate; import java.security.cert.Certificate;
@ -96,6 +102,7 @@ public class EnrollmentManager {
private PublicKey publicKey; private PublicKey publicKey;
private PublicKey serverPublicKey; private PublicKey serverPublicKey;
private X509Certificate SCEPCertificate; private X509Certificate SCEPCertificate;
private boolean isEnrolled = false;
/** /**
@ -104,6 +111,7 @@ public class EnrollmentManager {
*/ */
private EnrollmentManager() { private EnrollmentManager() {
this.SCEPUrl = AgentManager.getInstance().getEnrollmentEP(); this.SCEPUrl = AgentManager.getInstance().getEnrollmentEP();
setEnrollmentStatus();
} }
/** /**
@ -119,6 +127,63 @@ public class EnrollmentManager {
} }
public void setEnrollmentStatus() {
KeyStore keyStore;
try {
keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE);
keyStore.load(new FileInputStream(AgentConstants.DEVICE_KEYSTORE),
AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray());
this.isEnrolled = (keyStore.containsAlias(AgentConstants.DEVICE_CERT_ALIAS) &&
keyStore.containsAlias(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS) &&
keyStore.containsAlias(AgentConstants.SERVER_CA_CERT_ALIAS));
} catch (KeyStoreException e) {
log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '" +
AgentConstants.DEVICE_KEYSTORE + "' with keystore type [" +
AgentConstants.DEVICE_KEYSTORE_TYPE + "] to ensure enrollment status.");
log.error(AgentConstants.LOG_APPENDER + e);
log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled.");
return;
} catch (CertificateException | NoSuchAlgorithmException e) {
log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst trying to [load] the device KeyStore '" +
AgentConstants.DEVICE_KEYSTORE + "'.");
log.error(AgentConstants.LOG_APPENDER + e);
log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled.");
return;
} catch (IOException e) {
log.error(AgentConstants.LOG_APPENDER +
"An error occurred whilst trying to load input stream with the keystore file: " +
AgentConstants.DEVICE_KEYSTORE);
log.error(AgentConstants.LOG_APPENDER + e);
log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled.");
return;
}
try {
if (this.isEnrolled) {
this.SCEPCertificate = (X509Certificate) keyStore.getCertificate(AgentConstants.DEVICE_CERT_ALIAS);
this.privateKey = (PrivateKey) keyStore.getKey(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS,
AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray());
this.publicKey = SCEPCertificate.getPublicKey();
X509Certificate serverCACert = (X509Certificate) keyStore.getCertificate(
AgentConstants.SERVER_CA_CERT_ALIAS);
this.serverPublicKey = serverCACert.getPublicKey();
log.info(AgentConstants.LOG_APPENDER +
"Device has already been enrolled. Hence, loaded certificate information from device" +
" trust-store.");
}
} catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '" +
AgentConstants.DEVICE_KEYSTORE + "' to ensure enrollment status.");
log.error(AgentConstants.LOG_APPENDER + e);
log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled.");
this.isEnrolled = false;
}
}
/** /**
* Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key
* Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed
@ -181,13 +246,65 @@ public class EnrollmentManager {
this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest); this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest);
this.serverPublicKey = initPublicKeyOfServer(); this.serverPublicKey = initPublicKeyOfServer();
storeCertificateToStore(AgentConstants.DEVICE_CERT_ALIAS, SCEPCertificate);
storeKeyToKeyStore(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS, this.privateKey, SCEPCertificate);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.info(AgentConstants.LOG_APPENDER +
"SCEPCertificate, DevicePrivateKey, ServerPublicKey was saved to device keystore [" +
AgentConstants.DEVICE_KEYSTORE + "]");
log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey() + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey() + "\n]\n");
log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n");
} }
} }
private void storeCertificateToStore(String alias, Certificate certificate) {
KeyStore keyStore;
try {
keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE);
keyStore.load(new FileInputStream(AgentConstants.DEVICE_KEYSTORE),
AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray());
keyStore.setCertificateEntry(alias, certificate);
keyStore.store(new FileOutputStream(AgentConstants.DEVICE_KEYSTORE),
AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray());
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
log.error(AgentConstants.LOG_APPENDER +
"An error occurred whilst trying to store the Certificate received from the SCEP " +
"Enrollment.");
log.error(AgentConstants.LOG_APPENDER + e);
log.warn(AgentConstants.LOG_APPENDER +
"SCEP Certificate was not stored in the keystore; " +
"Hence the device will be re-enrolled during next restart.");
}
}
private void storeKeyToKeyStore(String alias, Key cryptoKey, Certificate certInCertChain) {
KeyStore keyStore;
try {
keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE);
keyStore.load(new FileInputStream(AgentConstants.DEVICE_KEYSTORE),
AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray());
Certificate[] certChain = new Certificate[1];
certChain[0] = certInCertChain;
keyStore.setKeyEntry(alias, cryptoKey, AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray(), certChain);
keyStore.store(new FileOutputStream(AgentConstants.DEVICE_KEYSTORE),
AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray());
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
log.error(AgentConstants.LOG_APPENDER +
"An error occurred whilst trying to store the key with alias " +
"[" + alias + "] in the device keystore.");
log.error(AgentConstants.LOG_APPENDER + e);
log.warn(AgentConstants.LOG_APPENDER +
"Key [" + alias + "] was not stored in the keystore; " +
"Hence the device will be re-enrolled during next restart.");
}
}
/** /**
* This method creates the Public-Private Key pair for the current client. * This method creates the Public-Private Key pair for the current client.
@ -382,6 +499,7 @@ public class EnrollmentManager {
// This is because the returned keystore may contain many certificates including RAs. // This is because the returned keystore may contain many certificates including RAs.
if (((Boolean) ((X509CertImpl) cert).getBasicConstraintsExtension().get(CERT_IS_CA_EXTENSION))) { if (((Boolean) ((X509CertImpl) cert).getBasicConstraintsExtension().get(CERT_IS_CA_EXTENSION))) {
serverCertPublicKey = cert.getPublicKey(); serverCertPublicKey = cert.getPublicKey();
storeCertificateToStore(AgentConstants.SERVER_CA_CERT_ALIAS, cert);
} }
} }
} }
@ -407,9 +525,9 @@ public class EnrollmentManager {
return serverCertPublicKey; return serverCertPublicKey;
} }
/** /**
* Gets the Public-Key of the client. * Gets the Public-Key of the client.
*
* @return the public key of the client. * @return the public key of the client.
*/ */
public PublicKey getPublicKey() { public PublicKey getPublicKey() {
@ -418,6 +536,7 @@ public class EnrollmentManager {
/** /**
* Gets the Private-Key of the client. * Gets the Private-Key of the client.
*
* @return the private key of the client. * @return the private key of the client.
*/ */
public PrivateKey getPrivateKey() { public PrivateKey getPrivateKey() {
@ -426,6 +545,7 @@ public class EnrollmentManager {
/** /**
* Gets the SCEP-Certificate of the client. * Gets the SCEP-Certificate of the client.
*
* @return the SCEP Certificate of the client. * @return the SCEP Certificate of the client.
*/ */
public X509Certificate getSCEPCertificate() { public X509Certificate getSCEPCertificate() {
@ -434,9 +554,19 @@ public class EnrollmentManager {
/** /**
* Gets the Public-Key of the Server. * Gets the Public-Key of the Server.
*
* @return the pubic key of the server. * @return the pubic key of the server.
*/ */
public PublicKey getServerPublicKey() { public PublicKey getServerPublicKey() {
return serverPublicKey; return serverPublicKey;
} }
/**
* Checks whether the device has already been enrolled with the SCEP Server.
*
* @return the enrollment status; 'TRUE' if already enrolled else 'FALSE'.
*/
public boolean isEnrolled() {
return isEnrolled;
}
} }

View File

@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportHandlerException;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -67,9 +68,9 @@ public class TransportUtils {
throw new TransportHandlerException(errorMsg); throw new TransportHandlerException(errorMsg);
} }
ipPortMap.put("Protocol", ipPortArray[0]); ipPortMap.put(AgentConstants.PROTOCOL_PROPERTY, ipPortArray[0]);
ipPortMap.put("Host", ipPortArray[1].replace("/", "")); ipPortMap.put(AgentConstants.HOST_PROPERTY, ipPortArray[1].replace("/", ""));
ipPortMap.put("Port", ipPortArray[2]); ipPortMap.put(AgentConstants.PORT_PROPERTY, ipPortArray[2]);
return ipPortMap; return ipPortMap;
} }
@ -99,8 +100,7 @@ public class TransportUtils {
return !ipAddress.endsWith("."); return !ipAddress.endsWith(".");
} catch (NumberFormatException nfe) { } catch (NumberFormatException nfe) {
log.warn("The IP Address: " + ipAddress + " could not " + log.warn("The IP Address: " + ipAddress + " could not be validated against IPv4-style");
"be validated against IPv4-style");
return false; return false;
} }
} }

View File

@ -52,7 +52,6 @@ import java.nio.charset.StandardCharsets;
public abstract class MQTTTransportHandler public abstract class MQTTTransportHandler
implements MqttCallback, TransportHandler<MqttMessage> { implements MqttCallback, TransportHandler<MqttMessage> {
private static final Log log = LogFactory.getLog(MQTTTransportHandler.class); private static final Log log = LogFactory.getLog(MQTTTransportHandler.class);
private static final String DEFAULT_PASSWORD = "";
public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0;
private MqttClient client; private MqttClient client;
@ -82,8 +81,6 @@ public abstract class MQTTTransportHandler
this.mqttBrokerEndPoint = mqttBrokerEndPoint; this.mqttBrokerEndPoint = mqttBrokerEndPoint;
this.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL; this.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL;
this.initSubscriber(); this.initSubscriber();
options.setUserName(AgentManager.getInstance().getAgentConfigs().getAuthToken());
options.setPassword(DEFAULT_PASSWORD.toCharArray());
} }
/** /**
@ -108,8 +105,6 @@ public abstract class MQTTTransportHandler
this.mqttBrokerEndPoint = mqttBrokerEndPoint; this.mqttBrokerEndPoint = mqttBrokerEndPoint;
this.timeoutInterval = intervalInMillis; this.timeoutInterval = intervalInMillis;
this.initSubscriber(); this.initSubscriber();
options.setUserName(AgentManager.getInstance().getAgentConfigs().getAuthToken());
options.setPassword(DEFAULT_PASSWORD.toCharArray());
} }
public void setTimeoutInterval(int timeoutInterval) { public void setTimeoutInterval(int timeoutInterval) {
@ -156,6 +151,12 @@ public abstract class MQTTTransportHandler
} }
protected void connectToQueue(String username, String password) throws TransportHandlerException {
options.setUserName(username);
options.setPassword(password.toCharArray());
connectToQueue();
}
/** /**
* Connects to the MQTT-Broker and if successfully established connection. * Connects to the MQTT-Broker and if successfully established connection.
* *
@ -248,8 +249,7 @@ public abstract class MQTTTransportHandler
try { try {
client.publish(topic, payLoad.getBytes(StandardCharsets.UTF_8), qos, retained); client.publish(topic, payLoad.getBytes(StandardCharsets.UTF_8), qos, retained);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Message: " + payLoad + " to MQTT topic [" + topic + log.debug("Message: " + payLoad + " to MQTT topic [" + topic + "] published successfully");
"] published successfully");
} }
} catch (MqttException ex) { } catch (MqttException ex) {
String errorMsg = String errorMsg =
@ -267,8 +267,7 @@ public abstract class MQTTTransportHandler
try { try {
client.publish(topic, message); client.publish(topic, message);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Message: " + message.toString() + " to MQTT topic [" + topic + log.debug("Message: " + message.toString() + " to MQTT topic [" + topic + "] published successfully");
"] published successfully");
} }
} catch (MqttException ex) { } catch (MqttException ex) {
//TODO:: Compulsory log of errors and remove formatted error //TODO:: Compulsory log of errors and remove formatted error
@ -291,8 +290,7 @@ public abstract class MQTTTransportHandler
@Override @Override
public void connectionLost(Throwable throwable) { public void connectionLost(Throwable throwable) {
log.warn("Lost Connection for client: " + this.clientId + log.warn("Lost Connection for client: " + this.clientId +
" to " + this.mqttBrokerEndPoint + ".\nThis was due to - " + " to " + this.mqttBrokerEndPoint + ".\nThis was due to - " + throwable.getMessage());
throwable.getMessage());
Thread reconnectThread = new Thread() { Thread reconnectThread = new Thread() {
public void run() { public void run() {
@ -340,8 +338,7 @@ public abstract class MQTTTransportHandler
} catch (MqttException e) { } catch (MqttException e) {
//TODO:: Throw errors //TODO:: Throw errors
log.error( log.error(
"Error occurred whilst trying to read the message from the MQTT delivery " + "Error occurred whilst trying to read the message from the MQTT delivery token.");
"token.");
} }
String topic = iMqttDeliveryToken.getTopics()[0]; String topic = iMqttDeliveryToken.getTopics()[0];
String client = iMqttDeliveryToken.getClient().getClientId(); String client = iMqttDeliveryToken.getClient().getClientId();

View File

@ -1,4 +1,4 @@
# ad#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. # Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -54,13 +54,27 @@ import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.*; import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
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 javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.util.*; import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
@ -136,7 +150,8 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>(); List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE)); deviceIdentifiers.add(new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(VirtualFireAlarmConstants.DEVICE_TYPE, commandOp, deviceIdentifiers); APIUtil.getDeviceManagementService().addOperation(VirtualFireAlarmConstants.DEVICE_TYPE, commandOp,
deviceIdentifiers);
break; break;
} }
return Response.ok().build(); return Response.ok().build();
@ -319,14 +334,16 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
scopes); scopes);
String accessToken = accessTokenInfo.getAccessToken(); String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken(); String refreshToken = accessTokenInfo.getRefreshToken();
//adding registering data
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(deviceId);
newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@" + APIUtil.getTenantDomainOftheUser());
boolean status; boolean status;
if (XmppConfig.getInstance().isEnabled()) { if (XmppConfig.getInstance().isEnabled()) {
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(deviceId);
newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@" + APIUtil.getTenantDomainOftheUser());
status = XmppServerClient.createAccount(newXmppAccount); status = XmppServerClient.createAccount(newXmppAccount);
if (!status) { if (!status) {
String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " + owner + String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " + owner +
@ -335,14 +352,16 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
} }
status = register(deviceId, deviceName); status = register(deviceId, deviceName);
if (!status) { if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner; String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
ZipUtil ziputil = new ZipUtil(); ZipUtil ziputil = new ZipUtil();
return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, deviceId, return ziputil.createZipFile(owner, sketchType, deviceId, deviceName, apiApplicationKey.toString(),
deviceName, accessToken, refreshToken); accessToken, refreshToken);
} }
private static String shortUUID() { private static String shortUUID() {
@ -350,5 +369,4 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX); return Long.toString(l, Character.MAX_RADIX);
} }
} }

View File

@ -0,0 +1,20 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig;
public class VirtualFireAlarmUtilConstants {
public static final String TENANT_DOMAIN = "TENANT_DOMAIN";
public static final String DEVICE_OWNER = "DEVICE_OWNER";
public static final String DEVICE_ID = "DEVICE_ID";
public static final String DEVICE_NAME = "DEVICE_NAME";
public static final String HTTPS_EP = "HTTPS_EP";
public static final String HTTP_EP = "HTTP_EP";
public static final String APIM_EP = "APIM_EP";
public static final String MQTT_EP = "MQTT_EP";
public static final String XMPP_EP = "XMPP_EP";
public static final String API_APPLICATION_KEY = "API_APPLICATION_KEY";
public static final String DEVICE_TOKEN = "DEVICE_TOKEN";
public static final String DEVICE_REFRESH_TOKEN = "DEVICE_REFRESH_TOKEN";
public static final String SERVER_NAME = "SERVER_NAME";
}

View File

@ -18,6 +18,11 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.util.Utils; import org.wso2.carbon.device.mgt.iot.util.Utils;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
@ -35,6 +40,7 @@ import java.util.Map;
*/ */
public class ZipUtil { public class ZipUtil {
private static final Log log = LogFactory.getLog(ZipUtil.class);
private static final String HTTPS_PORT_PROPERTY = "httpsPort"; private static final String HTTPS_PORT_PROPERTY = "httpsPort";
private static final String HTTP_PORT_PROPERTY = "httpPort"; private static final String HTTP_PORT_PROPERTY = "httpPort";
@ -42,12 +48,13 @@ public class ZipUtil {
private static final String HTTPS_PROTOCOL_APPENDER = "https://"; private static final String HTTPS_PROTOCOL_APPENDER = "https://";
private static final String HTTP_PROTOCOL_APPENDER = "http://"; private static final String HTTP_PROTOCOL_APPENDER = "http://";
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType, public ZipArchive createZipFile(String owner, String deviceType, String deviceId, String deviceName,
String deviceId, String deviceName, String token, String apiApplicationKey, String token, String refreshToken)
String refreshToken) throws DeviceManagementException { throws DeviceManagementException {
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches"; String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" + String archivesPath =
CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
File.separator + deviceId; File.separator + deviceId;
String templateSketchPath = sketchFolder + File.separator + deviceType; String templateSketchPath = sketchFolder + File.separator + deviceType;
String iotServerIP; String iotServerIP;
@ -63,24 +70,29 @@ public class ZipUtil {
if (mqttEndpoint.contains(LOCALHOST)) { if (mqttEndpoint.contains(LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP); mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
} }
String xmppEndpoint = XmppConfig.getInstance().getXmppServerIP() + ":" + String xmppEndpoint = XmppConfig.getInstance().getXmppServerIP() + ":" +
XmppConfig.getInstance().getXmppServerPort(); XmppConfig.getInstance().getXmppServerPort();
if (xmppEndpoint.contains(LOCALHOST)) { if (xmppEndpoint.contains(LOCALHOST)) {
xmppEndpoint = xmppEndpoint.replace(LOCALHOST, iotServerIP); xmppEndpoint = xmppEndpoint.replace(LOCALHOST, iotServerIP);
} }
String base64EncodedApplicationKey = getBase64EncodedAPIAppKey(apiApplicationKey).trim();
Map<String, String> contextParams = new HashMap<>(); Map<String, String> contextParams = new HashMap<>();
contextParams.put("TENANT_DOMAIN", APIUtil.getTenantDomainOftheUser()); contextParams.put(VirtualFireAlarmUtilConstants.TENANT_DOMAIN, APIUtil.getTenantDomainOftheUser());
contextParams.put("DEVICE_OWNER", owner); contextParams.put(VirtualFireAlarmUtilConstants.DEVICE_OWNER, owner);
contextParams.put("DEVICE_ID", deviceId); contextParams.put(VirtualFireAlarmUtilConstants.DEVICE_ID, deviceId);
contextParams.put("DEVICE_NAME", deviceName); contextParams.put(VirtualFireAlarmUtilConstants.DEVICE_NAME, deviceName);
contextParams.put("HTTPS_EP", httpsServerEP); contextParams.put(VirtualFireAlarmUtilConstants.HTTPS_EP, httpsServerEP);
contextParams.put("HTTP_EP", httpServerEP); contextParams.put(VirtualFireAlarmUtilConstants.HTTP_EP, httpServerEP);
contextParams.put("APIM_EP", apimEndpoint); contextParams.put(VirtualFireAlarmUtilConstants.APIM_EP, apimEndpoint);
contextParams.put("MQTT_EP", mqttEndpoint); contextParams.put(VirtualFireAlarmUtilConstants.MQTT_EP, mqttEndpoint);
contextParams.put("XMPP_EP", "XMPP:" + xmppEndpoint); contextParams.put(VirtualFireAlarmUtilConstants.XMPP_EP, "XMPP:" + xmppEndpoint);
contextParams.put("DEVICE_TOKEN", token); contextParams.put(VirtualFireAlarmUtilConstants.API_APPLICATION_KEY, base64EncodedApplicationKey);
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); contextParams.put(VirtualFireAlarmUtilConstants.DEVICE_TOKEN, token);
contextParams.put("SERVER_NAME", XmppConfig.getInstance().getXmppServerName()); contextParams.put(VirtualFireAlarmUtilConstants.DEVICE_REFRESH_TOKEN, refreshToken);
contextParams.put(VirtualFireAlarmUtilConstants.SERVER_NAME, XmppConfig.getInstance().getXmppServerName());
ZipArchive zipFile; ZipArchive zipFile;
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile; return zipFile;
@ -88,4 +100,13 @@ public class ZipUtil {
throw new DeviceManagementException("Zip File Creation Failed", e); throw new DeviceManagementException("Zip File Creation Failed", e);
} }
} }
private String getBase64EncodedAPIAppKey(String apiAppCredentialsAsJSONString) {
JSONObject jsonObject = new JSONObject(apiAppCredentialsAsJSONString);
String consumerKey = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_ID).toString();
String consumerSecret = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_SECRET).toString();
String stringToEncode = consumerKey + ":" + consumerSecret;
return Base64.encodeBase64String(stringToEncode.getBytes());
}
} }

View File

@ -26,7 +26,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
@ -50,13 +50,13 @@ public class VirtualFireAlarmManager implements DeviceManager {
} }
@Override @Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration) public boolean saveConfiguration(PlatformConfiguration PlatformConfiguration)
throws DeviceManagementException { throws DeviceManagementException {
return false; return false;
} }
@Override @Override
public TenantConfiguration getConfiguration() throws DeviceManagementException { public PlatformConfiguration getConfiguration() throws DeviceManagementException {
return null; return null;
} }

View File

@ -6,6 +6,7 @@ import org.wso2.carbon.device.mgt.iot.input.adapter.extension.ContentTransformer
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import java.math.BigInteger;
import java.security.PublicKey; import java.security.PublicKey;
import java.util.Map; import java.util.Map;
@ -22,7 +23,7 @@ public class VirtualFirealarmMqttContentTransformer implements ContentTransforme
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(tenantDomain, true); ctx.setTenantDomain(tenantDomain, true);
Long serialNo = (Long) jsonPayload.get(VirtualFireAlarmConstants.JSON_SERIAL_KEY); Integer serialNo = (Integer) jsonPayload.get(VirtualFireAlarmConstants.JSON_SERIAL_KEY);
// the hash-code of the deviceId is used as the alias for device certificates during SCEP enrollment. // the hash-code of the deviceId is used as the alias for device certificates during SCEP enrollment.
// hence, the same is used here to fetch the device-specific-certificate from the key store. // hence, the same is used here to fetch the device-specific-certificate from the key store.
PublicKey clientPublicKey = VirtualFireAlarmUtils.getDevicePublicKey("" + serialNo); PublicKey clientPublicKey = VirtualFireAlarmUtils.getDevicePublicKey("" + serialNo);

View File

@ -46,7 +46,7 @@
<version>2.2</version> <version>2.2</version>
<configuration> <configuration>
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes> <packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
<warName>${project.artifactId}</warName> <warName>mdm-android-agent</warName>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
@ -72,7 +72,7 @@
<tasks> <tasks>
<copy todir="${basedir}/../../../repository/deployment/server/webapps" overwrite="true"> <copy todir="${basedir}/../../../repository/deployment/server/webapps" overwrite="true">
<fileset dir="${basedir}/target"> <fileset dir="${basedir}/target">
<include name="${project.artifactId}.war" /> <include name="mdm-android-agent.war" />
</fileset> </fileset>
</copy> </copy>
</tasks> </tasks>

View File

@ -29,9 +29,12 @@ import java.io.Serializable;
@ApiModel(value = "UpgradeFirmware", @ApiModel(value = "UpgradeFirmware",
description = "This class carries all information related to UpgradeFirmware.") description = "This class carries all information related to UpgradeFirmware.")
public class UpgradeFirmware extends AndroidOperation implements Serializable { public class UpgradeFirmware extends AndroidOperation implements Serializable {
@ApiModelProperty(name = "schedule", value = "Schedule of the UpgradeFirmware.", required = true) @ApiModelProperty(name = "schedule", value = "Schedule of the UpgradeFirmware.")
private String schedule; private String schedule;
@ApiModelProperty(name = "server", value = "Firmware package server.")
private String server;
public String getSchedule() { public String getSchedule() {
return schedule; return schedule;
} }
@ -40,4 +43,12 @@ public class UpgradeFirmware extends AndroidOperation implements Serializable {
this.schedule = schedule; this.schedule = schedule;
} }
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
} }

View File

@ -19,7 +19,7 @@
package org.wso2.carbon.mdm.services.android.services.configuration; package org.wso2.carbon.mdm.services.android.services.configuration;
import io.swagger.annotations.*; import io.swagger.annotations.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.mdm.services.android.exception.AndroidAgentException; import org.wso2.carbon.mdm.services.android.exception.AndroidAgentException;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
@ -46,14 +46,14 @@ public interface ConfigurationMgtService {
@ApiResponse(code = 500, message = "Internal Server Error") @ApiResponse(code = 500, message = "Internal Server Error")
}) })
Response configureSettings(@ApiParam(name = "configuration", value = "AndroidPlatformConfiguration") Response configureSettings(@ApiParam(name = "configuration", value = "AndroidPlatformConfiguration")
TenantConfiguration configuration) throws AndroidAgentException; PlatformConfiguration configuration) throws AndroidAgentException;
@GET @GET
@ApiOperation( @ApiOperation(
httpMethod = "GET", httpMethod = "GET",
value = "Getting Android Platform Configurations", value = "Getting Android Platform Configurations",
notes = "Get the Android platform configuration details using this REST API", notes = "Get the Android platform configuration details using this REST API",
response = TenantConfiguration.class response = PlatformConfiguration.class
) )
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "Get Android Configurations"), @ApiResponse(code = 200, message = "Get Android Configurations"),
@ -75,5 +75,5 @@ public interface ConfigurationMgtService {
"Android platform") "Android platform")
}) })
Response updateConfiguration(@ApiParam(name = "configuration", value = "AndroidPlatformConfiguration") Response updateConfiguration(@ApiParam(name = "configuration", value = "AndroidPlatformConfiguration")
TenantConfiguration configuration) throws AndroidAgentException; PlatformConfiguration configuration) throws AndroidAgentException;
} }

View File

@ -23,7 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.mdm.services.android.exception.AndroidAgentException; import org.wso2.carbon.mdm.services.android.exception.AndroidAgentException;
import org.wso2.carbon.mdm.services.android.services.configuration.ConfigurationMgtService; import org.wso2.carbon.mdm.services.android.services.configuration.ConfigurationMgtService;
@ -45,7 +45,7 @@ public class ConfigurationMgtServiceImpl implements ConfigurationMgtService {
private static Log log = LogFactory.getLog(ConfigurationMgtServiceImpl.class); private static Log log = LogFactory.getLog(ConfigurationMgtServiceImpl.class);
@POST @POST
public Response configureSettings(TenantConfiguration configuration) public Response configureSettings(PlatformConfiguration configuration)
throws AndroidAgentException { throws AndroidAgentException {
Message responseMsg = new Message(); Message responseMsg = new Message();
@ -87,15 +87,15 @@ public class ConfigurationMgtServiceImpl implements ConfigurationMgtService {
@GET @GET
public Response getConfiguration() throws AndroidAgentException { public Response getConfiguration() throws AndroidAgentException {
String msg; String msg;
TenantConfiguration tenantConfiguration = null; PlatformConfiguration PlatformConfiguration = null;
List<ConfigurationEntry> configs; List<ConfigurationEntry> configs;
try { try {
tenantConfiguration = AndroidAPIUtils.getDeviceManagementService(). PlatformConfiguration = AndroidAPIUtils.getDeviceManagementService().
getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
if (tenantConfiguration != null) { if (PlatformConfiguration != null) {
configs = tenantConfiguration.getConfiguration(); configs = PlatformConfiguration.getConfiguration();
} else { } else {
tenantConfiguration = new TenantConfiguration(); PlatformConfiguration = new PlatformConfiguration();
configs = new ArrayList<>(); configs = new ArrayList<>();
} }
@ -109,18 +109,18 @@ public class ConfigurationMgtServiceImpl implements ConfigurationMgtService {
entry.setName(AndroidConstants.TenantConfigProperties.LICENSE_KEY); entry.setName(AndroidConstants.TenantConfigProperties.LICENSE_KEY);
entry.setValue(license.getText()); entry.setValue(license.getText());
configs.add(entry); configs.add(entry);
tenantConfiguration.setConfiguration(configs); PlatformConfiguration.setConfiguration(configs);
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
msg = "Error occurred while retrieving the Android tenant configuration"; msg = "Error occurred while retrieving the Android tenant configuration";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
return Response.status(Response.Status.OK).entity(tenantConfiguration).build(); return Response.status(Response.Status.OK).entity(PlatformConfiguration).build();
} }
@PUT @PUT
public Response updateConfiguration(TenantConfiguration configuration) throws AndroidAgentException { public Response updateConfiguration(PlatformConfiguration configuration) throws AndroidAgentException {
String msg; String msg;
Message responseMsg = new Message(); Message responseMsg = new Message();
ConfigurationEntry licenseEntry = null; ConfigurationEntry licenseEntry = null;
@ -145,7 +145,7 @@ public class ConfigurationMgtServiceImpl implements ConfigurationMgtService {
} }
configuration.setConfiguration(configs); configuration.setConfiguration(configs);
AndroidAPIUtils.getDeviceManagementService().saveConfiguration(configuration); AndroidAPIUtils.getDeviceManagementService().saveConfiguration(configuration);
AndroidAPIUtils.getGCMService().resetTenantConfigCache(); //AndroidAPIUtils.getGCMService().resetTenantConfigCache();
Response.status(Response.Status.ACCEPTED); Response.status(Response.Status.ACCEPTED);
responseMsg.setResponseMessage("Android platform configuration has updated successfully."); responseMsg.setResponseMessage("Android platform configuration has updated successfully.");
responseMsg.setResponseCode(Response.Status.ACCEPTED.toString()); responseMsg.setResponseCode(Response.Status.ACCEPTED.toString());

View File

@ -21,7 +21,6 @@ package org.wso2.carbon.mdm.services.android.services.event;
import io.swagger.annotations.*; import io.swagger.annotations.*;
import org.wso2.carbon.mdm.services.android.bean.DeviceState; import org.wso2.carbon.mdm.services.android.bean.DeviceState;
import org.wso2.carbon.mdm.services.android.bean.wrapper.EventBeanWrapper; import org.wso2.carbon.mdm.services.android.bean.wrapper.EventBeanWrapper;
import org.wso2.carbon.mdm.services.android.exception.AndroidAgentException;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
@ -49,7 +48,8 @@ public interface EventService {
@HeaderParam(ACCEPT) String acceptHeader, @HeaderParam(ACCEPT) String acceptHeader,
@ApiParam(name = "eventBeanWrapper", @ApiParam(name = "eventBeanWrapper",
value = "Information of the agent event to be published on DAS.") value = "Information of the agent event to be published on DAS.")
EventBeanWrapper eventBeanWrapper) throws AndroidAgentException; EventBeanWrapper eventBeanWrapper);
@GET @GET
@Path("{deviceId}") @Path("{deviceId}")
@Produces("application/json") @Produces("application/json")
@ -70,7 +70,7 @@ public interface EventService {
Response retrieveAlert(@ApiParam(name = "acceptHeader", value = "Accept Header.") Response retrieveAlert(@ApiParam(name = "acceptHeader", value = "Accept Header.")
@HeaderParam(ACCEPT) String acceptHeader, @HeaderParam(ACCEPT) String acceptHeader,
@ApiParam(name = "deviceId", value = "DeviceId which need to retrieve published events.") @ApiParam(name = "deviceId", value = "DeviceId which need to retrieve published events.")
@PathParam("deviceId") String deviceId) throws AndroidAgentException; @PathParam("deviceId") String deviceId);
@GET @GET
@Path("{deviceId}/date") @Path("{deviceId}/date")
@ -97,7 +97,7 @@ public interface EventService {
@ApiParam(name = "from", value = "From Date.") @ApiParam(name = "from", value = "From Date.")
@QueryParam("from") long from, @QueryParam("from") long from,
@ApiParam(name = "to", value = "To Date.") @ApiParam(name = "to", value = "To Date.")
@QueryParam("to") long to) throws AndroidAgentException; @QueryParam("to") long to);
@GET @GET
@Path("{deviceId}/type/{type}") @Path("{deviceId}/type/{type}")
@ -120,5 +120,5 @@ public interface EventService {
@ApiParam(name = "deviceId", value = "Device Identifier to be need to retrieve events.") @ApiParam(name = "deviceId", value = "Device Identifier to be need to retrieve events.")
@PathParam("deviceId") String deviceId, @PathParam("deviceId") String deviceId,
@ApiParam(name = "type", value = "Type of the Alert to be need to retrieve events.") @ApiParam(name = "type", value = "Type of the Alert to be need to retrieve events.")
@PathParam("type") String type) throws AndroidAgentException; @PathParam("type") String type);
} }

View File

@ -42,7 +42,7 @@ public class EventServiceImpl implements EventService {
@POST @POST
public Response publishEvents(@HeaderParam(ACCEPT) String acceptHeader, public Response publishEvents(@HeaderParam(ACCEPT) String acceptHeader,
EventBeanWrapper eventBeanWrapper) throws AndroidAgentException { EventBeanWrapper eventBeanWrapper) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Invoking Android device even logging."); log.debug("Invoking Android device even logging.");
@ -73,7 +73,7 @@ public class EventServiceImpl implements EventService {
@Produces("application/json") @Produces("application/json")
@GET @GET
public Response retrieveAlert(@HeaderParam(ACCEPT) String acceptHeader, public Response retrieveAlert(@HeaderParam(ACCEPT) String acceptHeader,
@PathParam("deviceId") String deviceId) throws AndroidAgentException { @PathParam("deviceId") String deviceId) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Retrieving events for given device Identifier."); log.debug("Retrieving events for given device Identifier.");
@ -104,7 +104,7 @@ public class EventServiceImpl implements EventService {
@GET @GET
public Response retrieveAlertFromDate(@HeaderParam(ACCEPT) String acceptHeader, public Response retrieveAlertFromDate(@HeaderParam(ACCEPT) String acceptHeader,
@PathParam("deviceId") String deviceId, @QueryParam("from") long from, @PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to) throws AndroidAgentException { @QueryParam("to") long to) {
String fromDate = String.valueOf(from); String fromDate = String.valueOf(from);
String toDate = String.valueOf(to); String toDate = String.valueOf(to);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -136,8 +136,7 @@ public class EventServiceImpl implements EventService {
@Path("{deviceId}/type/{type}") @Path("{deviceId}/type/{type}")
@GET @GET
public Response retrieveAlertType(@HeaderParam(ACCEPT) String acceptHeader, public Response retrieveAlertType(@HeaderParam(ACCEPT) String acceptHeader,
@PathParam("deviceId") String deviceId, @PathParam("type") String type) @PathParam("deviceId") String deviceId, @PathParam("type") String type) {
throws AndroidAgentException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Retrieving events for given device identifier and type."); log.debug("Retrieving events for given device identifier and type.");
@ -149,8 +148,8 @@ public class EventServiceImpl implements EventService {
try { try {
deviceStates = AndroidAPIUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); deviceStates = AndroidAPIUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query);
if (deviceStates == null) { if (deviceStates == null) {
message.setResponseCode("No any alerts are published for given Device: " + message.setResponseCode("No any alerts are published for given Device: "
"" + deviceId + " on specific date."); + deviceId + " on specific date.");
return Response.status(Response.Status.OK).entity(message).build(); return Response.status(Response.Status.OK).entity(message).build();
} else { } else {

View File

@ -46,7 +46,6 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtExcept
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils; import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.mobile.impl.android.gcm.GCMService;
import org.wso2.carbon.mdm.services.android.bean.DeviceState; import org.wso2.carbon.mdm.services.android.bean.DeviceState;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
@ -94,16 +93,16 @@ public class AndroidAPIUtils {
return deviceManagementProviderService; return deviceManagementProviderService;
} }
public static GCMService getGCMService() { // public static GCMService getGCMService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); // PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
GCMService gcmService = (GCMService) ctx.getOSGiService(GCMService.class, null); // GCMService gcmService = (GCMService) ctx.getOSGiService(GCMService.class, null);
if (gcmService == null) { // if (gcmService == null) {
String msg = "GCM service has not initialized."; // String msg = "GCM service has not initialized.";
log.error(msg); // log.error(msg);
throw new IllegalStateException(msg); // throw new IllegalStateException(msg);
} // }
return gcmService; // return gcmService;
} // }
public static MediaType getResponseMediaType(String acceptHeader) { public static MediaType getResponseMediaType(String acceptHeader) {
MediaType responseMediaType; MediaType responseMediaType;
@ -126,17 +125,17 @@ public class AndroidAPIUtils {
List<DeviceIdentifier> validDeviceIds = deviceIDHolder.getValidDeviceIDList(); List<DeviceIdentifier> validDeviceIds = deviceIDHolder.getValidDeviceIDList();
Activity activity = getDeviceManagementService().addOperation( Activity activity = getDeviceManagementService().addOperation(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, validDeviceIds); DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, validDeviceIds);
if (activity != null) { // if (activity != null) {
GCMService gcmService = getGCMService(); // GCMService gcmService = getGCMService();
if (gcmService.isGCMEnabled()) { // if (gcmService.isGCMEnabled()) {
List<DeviceIdentifier> deviceIDList = deviceIDHolder.getValidDeviceIDList(); // List<DeviceIdentifier> deviceIDList = deviceIDHolder.getValidDeviceIDList();
List<Device> devices = new ArrayList<Device>(deviceIDList.size()); // List<Device> devices = new ArrayList<Device>(deviceIDList.size());
for (DeviceIdentifier deviceIdentifier : deviceIDList) { // for (DeviceIdentifier deviceIdentifier : deviceIDList) {
devices.add(getDeviceManagementService().getDevice(deviceIdentifier)); // devices.add(getDeviceManagementService().getDevice(deviceIdentifier));
} // }
getGCMService().sendNotification(operation.getCode(), devices); // getGCMService().sendNotification(operation.getCode(), devices);
} // }
} // }
if (!deviceIDHolder.getErrorDeviceIdList().isEmpty()) { if (!deviceIDHolder.getErrorDeviceIdList().isEmpty()) {
return javax.ws.rs.core.Response.status(AndroidConstants.StatusCodes. return javax.ws.rs.core.Response.status(AndroidConstants.StatusCodes.
MULTI_STATUS_HTTP_CODE).type( MULTI_STATUS_HTTP_CODE).type(

View File

@ -27,7 +27,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
@ -85,7 +85,7 @@ public class AndroidDeviceManager implements DeviceManager {
} }
@Override @Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration) public boolean saveConfiguration(PlatformConfiguration tenantConfiguration)
throws DeviceManagementException { throws DeviceManagementException {
boolean status; boolean status;
try { try {
@ -96,7 +96,7 @@ public class AndroidDeviceManager implements DeviceManager {
DeviceManagementConstants. DeviceManagementConstants.
MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class); JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
Marshaller marshaller = context.createMarshaller(); Marshaller marshaller = context.createMarshaller();
marshaller.marshal(tenantConfiguration, writer); marshaller.marshal(tenantConfiguration, writer);
@ -119,7 +119,7 @@ public class AndroidDeviceManager implements DeviceManager {
} }
@Override @Override
public TenantConfiguration getConfiguration() throws DeviceManagementException { public PlatformConfiguration getConfiguration() throws DeviceManagementException {
Resource resource; Resource resource;
try { try {
String androidRegPath = String androidRegPath =
@ -127,9 +127,9 @@ public class AndroidDeviceManager implements DeviceManager {
MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
resource = MobileDeviceManagementUtil.getRegistryResource(androidRegPath); resource = MobileDeviceManagementUtil.getRegistryResource(androidRegPath);
if (resource != null) { if (resource != null) {
JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class); JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
Unmarshaller unmarshaller = context.createUnmarshaller(); Unmarshaller unmarshaller = context.createUnmarshaller();
return (TenantConfiguration) unmarshaller.unmarshal( return (PlatformConfiguration) unmarshaller.unmarshal(
new StringReader(new String((byte[]) resource.getContent(), Charset. new StringReader(new String((byte[]) resource.getContent(), Charset.
forName(MobilePluginConstants.CHARSET_UTF8)))); forName(MobilePluginConstants.CHARSET_UTF8))));
} }

View File

@ -234,11 +234,31 @@ public class AndroidFeatureManager implements FeatureManager {
feature.setName("Password Policy"); feature.setName("Password Policy");
feature.setDescription("Set passcode policy"); feature.setDescription("Set passcode policy");
supportedFeatures.add(feature); supportedFeatures.add(feature);
feature = new Feature(); feature = new Feature();
feature.setCode("NOTIFICATION"); feature.setCode("NOTIFICATION");
feature.setName("Message"); feature.setName("Message");
feature.setDescription("Send message"); feature.setDescription("Send message");
supportedFeatures.add(feature); supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DEVICE_REBOOT");
feature.setName("Reboot");
feature.setDescription("Reboot the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("UPGRADE_FIRMWARE");
feature.setName("Upgrade Firmware");
feature.setDescription("Upgrade Firmware");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("VPN");
feature.setName("Configure VPN");
feature.setDescription("Configure VPN settings");
supportedFeatures.add(feature);
feature = new Feature(); feature = new Feature();
feature.setCode("DISALLOW_ADJUST_VOLUME"); feature.setCode("DISALLOW_ADJUST_VOLUME");
feature.setName("Adjust Volume"); feature.setName("Adjust Volume");

View File

@ -27,7 +27,7 @@ import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.mobile.android.impl.util.AndroidPluginConstants; import org.wso2.carbon.device.mgt.mobile.android.impl.util.AndroidPluginConstants;
import org.wso2.carbon.device.mgt.mobile.android.internal.AndroidDeviceManagementDataHolder; import org.wso2.carbon.device.mgt.mobile.android.internal.AndroidDeviceManagementDataHolder;
@ -56,7 +56,7 @@ public class GCMUtil {
private static final int TIME_TO_LIVE = 60; private static final int TIME_TO_LIVE = 60;
private static final int HTTP_STATUS_CODE_OK = 200; private static final int HTTP_STATUS_CODE_OK = 200;
private static HashMap<Integer,TenantConfiguration> tenantConfigurationCache = new HashMap<>(); private static HashMap<Integer, PlatformConfiguration> tenantConfigurationCache = new HashMap<>();
public static GCMResult sendWakeUpCall(String message, List<Device> devices) { public static GCMResult sendWakeUpCall(String message, List<Device> devices) {
GCMResult result = new GCMResult(); GCMResult result = new GCMResult();
@ -163,7 +163,7 @@ public class GCMUtil {
getAndroidDeviceManagementService(); getAndroidDeviceManagementService();
try { try {
//Get the TenantConfiguration from cache if not we'll get it from DM service //Get the TenantConfiguration from cache if not we'll get it from DM service
TenantConfiguration tenantConfiguration = getTenantConfigurationFromCache(); PlatformConfiguration tenantConfiguration = getTenantConfigurationFromCache();
if (tenantConfiguration == null) { if (tenantConfiguration == null) {
tenantConfiguration = androidDMService.getDeviceManager().getConfiguration(); tenantConfiguration = androidDMService.getDeviceManager().getConfiguration();
if (tenantConfiguration != null) { if (tenantConfiguration != null) {
@ -190,11 +190,11 @@ public class GCMUtil {
tenantConfigurationCache.remove(getTenantId()); tenantConfigurationCache.remove(getTenantId());
} }
private static void addTenantConfigurationToCache(TenantConfiguration tenantConfiguration) { private static void addTenantConfigurationToCache(PlatformConfiguration tenantConfiguration) {
tenantConfigurationCache.put(getTenantId(), tenantConfiguration); tenantConfigurationCache.put(getTenantId(), tenantConfiguration);
} }
private static TenantConfiguration getTenantConfigurationFromCache() { private static PlatformConfiguration getTenantConfigurationFromCache() {
return tenantConfigurationCache.get(getTenantId()); return tenantConfigurationCache.get(getTenantId());
} }

View File

@ -1,70 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
/**
* This represents the Android implementation of DeviceManagerService.
*/
public class AndroidDeviceManagementService implements DeviceManagementService {
private DeviceManager deviceManager;
public static final String DEVICE_TYPE_ANDROID = "android";
private static final String SUPER_TENANT_DOMAIN = "carbon.super";
@Override
public String getType() {
return AndroidDeviceManagementService.DEVICE_TYPE_ANDROID;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new AndroidDeviceManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public ProvisioningConfig getProvisioningConfig() {
return new ProvisioningConfig(SUPER_TENANT_DOMAIN, true);
}
@Override
public PushNotificationConfig getPushNotificationConfig() {
return null;
}
}

View File

@ -1,342 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
import org.wso2.carbon.device.mgt.extensions.license.mgt.registry.RegistryBasedLicenseManager;
import org.wso2.carbon.device.mgt.mobile.common.MobileDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.common.MobilePluginConstants;
import org.wso2.carbon.device.mgt.mobile.dao.AbstractMobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dto.MobileDevice;
import org.wso2.carbon.device.mgt.mobile.impl.android.dao.AndroidDAOFactory;
import org.wso2.carbon.device.mgt.mobile.impl.android.util.AndroidPluginUtils;
import org.wso2.carbon.device.mgt.mobile.util.MobileDeviceManagementUtil;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class AndroidDeviceManager implements DeviceManager {
private AbstractMobileDeviceManagementDAOFactory daoFactory;
private static final Log log = LogFactory.getLog(AndroidDeviceManagementService.class);
private FeatureManager featureManager = new AndroidFeatureManager();
private LicenseManager licenseManager;
public AndroidDeviceManager() {
this.daoFactory = new AndroidDAOFactory();
this.licenseManager = new RegistryBasedLicenseManager();
License defaultLicense;
try {
if (licenseManager.getLicense(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID,
MobilePluginConstants.LANGUAGE_CODE_ENGLISH_US) == null) {
defaultLicense = AndroidPluginUtils.getDefaultLicense();
licenseManager.addLicense(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID, defaultLicense);
}
featureManager.addSupportedFeaturesToDB();
} catch (LicenseManagementException e) {
log.error("Error occurred while adding default license for Android devices", e);
} catch (DeviceManagementException e) {
throw new IllegalStateException("Error occurred while adding Android features to the DB.");
}
}
@Override
public FeatureManager getFeatureManager() {
return featureManager;
}
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Persisting android configurations in Registry");
}
String resourcePath = MobileDeviceManagementUtil.getPlatformConfigPath(
DeviceManagementConstants.
MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(tenantConfiguration, writer);
Resource resource = MobileDeviceManagementUtil.getConfigurationRegistry().newResource();
resource.setContent(writer.toString());
resource.setMediaType(MobilePluginConstants.MEDIA_TYPE_XML);
MobileDeviceManagementUtil.putRegistryResource(resourcePath, resource);
status = true;
} catch (MobileDeviceMgtPluginException e) {
throw new DeviceManagementException(
"Error occurred while retrieving the Registry instance", e);
} catch (RegistryException e) {
throw new DeviceManagementException(
"Error occurred while persisting the Registry resource of Android Configuration", e);
} catch (JAXBException e) {
throw new DeviceManagementException(
"Error occurred while parsing the Android configuration", e);
}
return status;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
Resource resource;
try {
String androidRegPath =
MobileDeviceManagementUtil.getPlatformConfigPath(DeviceManagementConstants.
MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
resource = MobileDeviceManagementUtil.getRegistryResource(androidRegPath);
if (resource != null) {
JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
return (TenantConfiguration) unmarshaller.unmarshal(
new StringReader(new String((byte[]) resource.getContent(), Charset.
forName(MobilePluginConstants.CHARSET_UTF8))));
}
return null;
} catch (MobileDeviceMgtPluginException e) {
throw new DeviceManagementException(
"Error occurred while retrieving the Registry instance", e);
} catch (JAXBException e) {
throw new DeviceManagementException(
"Error occurred while parsing the Android configuration", e);
} catch (RegistryException e) {
throw new DeviceManagementException(
"Error occurred while retrieving the Registry resource of Android Configuration", e);
}
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status = false;
boolean isEnrolled = this.isEnrolled(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Android device : " + device.getDeviceIdentifier());
}
if (isEnrolled) {
this.modifyEnrollment(device);
} else {
MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device);
AndroidDAOFactory.beginTransaction();
status = daoFactory.getMobileDeviceDAO().addMobileDevice(mobileDevice);
AndroidDAOFactory.commitTransaction();
}
} catch (MobileDeviceManagementDAOException e) {
try {
AndroidDAOFactory.rollbackTransaction();
} catch (MobileDeviceManagementDAOException mobileDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, mobileDAOEx);
}
String msg = "Error occurred while enrolling the Android device : " + device.getDeviceIdentifier();
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device);
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Android device enrollment data");
}
AndroidDAOFactory.beginTransaction();
status = daoFactory.getMobileDeviceDAO().updateMobileDevice(mobileDevice);
AndroidDAOFactory.commitTransaction();
} catch (MobileDeviceManagementDAOException e) {
try {
AndroidDAOFactory.rollbackTransaction();
} catch (MobileDeviceManagementDAOException mobileDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, mobileDAOEx);
}
String msg = "Error occurred while updating the enrollment of the Android device : " +
device.getDeviceIdentifier();
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
//Here we don't have anything specific to do. Hence returning.
return true;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Android device : " + deviceId.getId());
}
MobileDevice mobileDevice =
daoFactory.getMobileDeviceDAO().getMobileDevice(deviceId.getId());
if (mobileDevice != null) {
isEnrolled = true;
}
} catch (MobileDeviceManagementDAOException e) {
String msg = "Error occurred while checking the enrollment status of Android device : " + deviceId.getId();
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Android device : '" + deviceId.getId() + "'");
}
MobileDevice mobileDevice = daoFactory.getMobileDeviceDAO().
getMobileDevice(deviceId.getId());
device = MobileDeviceManagementUtil.convertToDevice(mobileDevice);
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException(
"Error occurred while fetching the Android device: '" + deviceId.getId() + "'", e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
@Override
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceIdentifier, String currentUser,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String languageCode) throws LicenseManagementException {
return licenseManager.
getLicense(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID, languageCode);
}
@Override
public void addLicense(License license) throws LicenseManagementException {
licenseManager.addLicense(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID, license);
}
@Override
public boolean requireDeviceAuthorization() {
return true;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device)
throws DeviceManagementException {
boolean status;
Device existingDevice = this.getDevice(deviceIdentifier);
// This object holds the current persisted device object
MobileDevice existingMobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(existingDevice);
// This object holds the newly received device object from response
MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device);
// Updating current object features using newer ones
existingMobileDevice.setLatitude(mobileDevice.getLatitude());
existingMobileDevice.setLongitude(mobileDevice.getLongitude());
existingMobileDevice.setDeviceProperties(mobileDevice.getDeviceProperties());
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Android device : " + device.getDeviceIdentifier());
}
AndroidDAOFactory.beginTransaction();
status = daoFactory.getMobileDeviceDAO().updateMobileDevice(existingMobileDevice);
AndroidDAOFactory.commitTransaction();
} catch (MobileDeviceManagementDAOException e) {
try {
AndroidDAOFactory.rollbackTransaction();
} catch (MobileDeviceManagementDAOException e1) {
log.warn("Error occurred while roll back the update device info transaction : '" +
device.toString() + "'", e1);
}
throw new DeviceManagementException(
"Error occurred while updating the Android device: '" + device.getDeviceIdentifier() + "'", e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Android devices");
}
List<MobileDevice> mobileDevices =
daoFactory.getMobileDeviceDAO().getAllMobileDevices();
if (mobileDevices != null) {
devices = new ArrayList<>(mobileDevices.size());
for (MobileDevice mobileDevice : mobileDevices) {
devices.add(MobileDeviceManagementUtil.convertToDevice(mobileDevice));
}
}
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while fetching all Android devices", e);
}
return devices;
}
}

View File

@ -1,296 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.mobile.dao.AbstractMobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileFeatureDAO;
import org.wso2.carbon.device.mgt.mobile.dto.MobileFeature;
import org.wso2.carbon.device.mgt.mobile.impl.android.dao.AndroidDAOFactory;
import org.wso2.carbon.device.mgt.mobile.util.MobileDeviceManagementUtil;
import java.util.ArrayList;
import java.util.List;
public class AndroidFeatureManager implements FeatureManager {
private MobileFeatureDAO featureDAO;
private static final Log log = LogFactory.getLog(AndroidFeatureManager.class);
public AndroidFeatureManager() {
MobileDeviceManagementDAOFactory daoFactory = new AndroidDAOFactory();
this.featureDAO = daoFactory.getMobileFeatureDAO();
}
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
try {
AndroidDAOFactory.beginTransaction();
MobileFeature mobileFeature = MobileDeviceManagementUtil.convertToMobileFeature(feature);
featureDAO.addFeature(mobileFeature);
AndroidDAOFactory.commitTransaction();
return true;
} catch (MobileDeviceManagementDAOException e) {
try {
AndroidDAOFactory.rollbackTransaction();
} catch (MobileDeviceManagementDAOException e1) {
log.warn("Error occurred while roll-backing the transaction", e);
}
throw new DeviceManagementException("Error occurred while adding the feature", e);
}
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
List<MobileFeature> mobileFeatures = new ArrayList<MobileFeature>(features.size());
for (Feature feature : features) {
mobileFeatures.add(MobileDeviceManagementUtil.convertToMobileFeature(feature));
}
try {
AndroidDAOFactory.beginTransaction();
featureDAO.addFeatures(mobileFeatures);
AndroidDAOFactory.commitTransaction();
return true;
} catch (MobileDeviceManagementDAOException e) {
try {
AndroidDAOFactory.rollbackTransaction();
} catch (MobileDeviceManagementDAOException e1) {
log.warn("Error occurred while roll-backing the transaction", e);
}
throw new DeviceManagementException("Error occurred while adding the features", e);
}
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
try {
MobileFeature mobileFeature = featureDAO.getFeatureByCode(name);
Feature feature = MobileDeviceManagementUtil.convertToFeature(mobileFeature);
return feature;
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the feature", e);
}
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
try {
List<MobileFeature> mobileFeatures = featureDAO.getAllFeatures();
List<Feature> featureList = new ArrayList<Feature>(mobileFeatures.size());
for (MobileFeature mobileFeature : mobileFeatures) {
featureList.add(MobileDeviceManagementUtil.convertToFeature(mobileFeature));
}
return featureList;
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the list of features registered for " +
"Android platform", e);
}
}
@Override
public boolean removeFeature(String code) throws DeviceManagementException {
boolean status;
try {
AndroidDAOFactory.beginTransaction();
featureDAO.deleteFeatureByCode(code);
AndroidDAOFactory.commitTransaction();
status = true;
} catch (MobileDeviceManagementDAOException e) {
try {
AndroidDAOFactory.rollbackTransaction();
} catch (MobileDeviceManagementDAOException e1) {
log.warn("Error occurred while roll-backing the transaction", e);
}
throw new DeviceManagementException("Error occurred while removing the feature", e);
}
return status;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
synchronized (this) {
List<Feature> supportedFeatures = getSupportedFeatures();
List<Feature> existingFeatures = this.getFeatures();
List<Feature> missingFeatures = MobileDeviceManagementUtil.
getMissingFeatures(supportedFeatures, existingFeatures);
if (missingFeatures.size() > 0) {
return this.addFeatures(missingFeatures);
}
return true;
}
}
//Get the supported feature list.
private static List<Feature> getSupportedFeatures() {
List<Feature> supportedFeatures = new ArrayList<Feature>();
Feature feature = new Feature();
feature.setCode("DEVICE_LOCK");
feature.setName("Device Lock");
feature.setDescription("Lock the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DEVICE_UNLOCK");
feature.setName("Device Unlock");
feature.setDescription("Unlock the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DEVICE_LOCATION");
feature.setName("Location");
feature.setDescription("Request coordinates of device location");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("WIFI");
feature.setName("wifi");
feature.setDescription("Setting up wifi configuration");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("CAMERA");
feature.setName("camera");
feature.setDescription("Enable or disable camera");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("EMAIL");
feature.setName("Email");
feature.setDescription("Configure email settings");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DEVICE_MUTE");
feature.setName("Mute");
feature.setDescription("Enable mute in the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DEVICE_INFO");
feature.setName("Device info");
feature.setDescription("Request device information");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("ENTERPRISE_WIPE");
feature.setName("Enterprise Wipe");
feature.setDescription("Remove enterprise applications");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("CLEAR_PASSWORD");
feature.setName("Clear Password");
feature.setDescription("Clear current password");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("WIPE_DATA");
feature.setName("Wipe Data");
feature.setDescription("Factory reset the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("APPLICATION_LIST");
feature.setName("Application List");
feature.setDescription("Request list of current installed applications");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("CHANGE_LOCK_CODE");
feature.setName("Change Lock-code");
feature.setDescription("Change current lock code");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("INSTALL_APPLICATION");
feature.setName("Install App");
feature.setDescription("Install Enterprise or Market application");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("UPDATE_APPLICATION");
feature.setName("Update App");
feature.setDescription("Update Enterprise or Market application");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("UNINSTALL_APPLICATION");
feature.setName("Uninstall App");
feature.setDescription("Uninstall application");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("BLACKLIST_APPLICATIONS");
feature.setName("Blacklist app");
feature.setDescription("Blacklist applications");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("ENCRYPT_STORAGE");
feature.setName("Encrypt storage");
feature.setDescription("Encrypt storage");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DEVICE_RING");
feature.setName("Ring");
feature.setDescription("Ring the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("PASSCODE_POLICY");
feature.setName("Password Policy");
feature.setDescription("Set passcode policy");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("NOTIFICATION");
feature.setName("Message");
feature.setDescription("Send message");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("DEVICE_REBOOT");
feature.setName("Reboot");
feature.setDescription("Reboot the device");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("UPGRADE_FIRMWARE");
feature.setName("Upgrade Firmware");
feature.setDescription("Upgrade Firmware");
supportedFeatures.add(feature);
feature = new Feature();
feature.setCode("VPN");
feature.setName("Configure VPN");
feature.setDescription("Configure VPN settings");
supportedFeatures.add(feature);
return supportedFeatures;
}
}

View File

@ -1,100 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.mobile.impl.android.gcm.GCMService;
import org.wso2.carbon.device.mgt.mobile.internal.MobileDeviceManagementDataHolder;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService;
import java.util.ArrayList;
import java.util.List;
public class AndroidPolicyMonitoringService implements PolicyMonitoringService {
private static Log log = LogFactory.getLog(AndroidPolicyMonitoringService.class);
@Override
public void notifyDevices(List<Device> list) throws PolicyComplianceException {
GCMService gcmService = MobileDeviceManagementDataHolder.getInstance().getGCMService();
if (gcmService.isGCMEnabled() && !list.isEmpty()) {
gcmService.sendNotification("POLICY_BUNDLE", list);
}
}
@Override
public ComplianceData checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy,
Object compliancePayload) throws PolicyComplianceException {
if (log.isDebugEnabled()) {
log.debug("Checking policy compliance status of device '" + deviceIdentifier.getId() + "'");
}
ComplianceData complianceData = new ComplianceData();
if (compliancePayload == null || policy == null) {
return complianceData;
}
String compliancePayloadString = new Gson().toJson(compliancePayload);
// Parsing json string to get compliance features.
JsonElement jsonElement;
if (compliancePayloadString instanceof String) {
jsonElement = new JsonParser().parse(compliancePayloadString);
} else {
throw new PolicyComplianceException("Invalid policy compliance payload");
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
Gson gson = new Gson();
ComplianceFeature complianceFeature;
List<ComplianceFeature> complianceFeatures = new ArrayList<ComplianceFeature>(jsonArray.size());
List<ComplianceFeature> nonComplianceFeatures = new ArrayList<>();
for (JsonElement element : jsonArray) {
complianceFeature = gson.fromJson(element, ComplianceFeature.class);
complianceFeatures.add(complianceFeature);
}
for (ComplianceFeature cf : complianceFeatures) {
if (!cf.isCompliant()) {
complianceData.setStatus(false);
nonComplianceFeatures.add(cf);
break;
}
}
complianceData.setComplianceFeatures(nonComplianceFeatures);
return complianceData;
}
@Override
public String getType() {
return DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID;
}
}

View File

@ -1,117 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.mobile.dao.*;
import org.wso2.carbon.device.mgt.mobile.impl.android.dao.impl.AndroidDeviceDAOImpl;
import org.wso2.carbon.device.mgt.mobile.impl.android.dao.impl.AndroidFeatureDAOImpl;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class AndroidDAOFactory extends AbstractMobileDeviceManagementDAOFactory {
private static final Log log = LogFactory.getLog(AndroidDAOFactory.class);
protected static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public AndroidDAOFactory() {
this.dataSource = getDataSourceMap().get(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
}
@Override
public MobileDeviceDAO getMobileDeviceDAO() {
return new AndroidDeviceDAOImpl();
}
public MobileFeatureDAO getMobileFeatureDAO() {
return new AndroidFeatureDAOImpl();
}
public static void beginTransaction() throws MobileDeviceManagementDAOException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws MobileDeviceManagementDAOException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while retrieving data source connection",
e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws MobileDeviceManagementDAOException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted");
}
}
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while committing the transaction", e);
}
}
public static void closeConnection() throws MobileDeviceManagementDAOException {
Connection conn = currentConnection.get();
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
currentConnection.remove();
}
public static void rollbackTransaction() throws MobileDeviceManagementDAOException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback " +
"has not been attempted");
}
}
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while rollback the transaction", e);
}
}
}

View File

@ -1,79 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.dao;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
public class AndroidFeatureManagementDAOException extends MobileDeviceManagementDAOException {
private String message;
private static final long serialVersionUID = 2021891706072918865L;
/**
* Constructs a new MobileDeviceManagementDAOException with the specified detail message and
* nested exception.
*
* @param message error message
* @param nestedException exception
*/
public AndroidFeatureManagementDAOException(String message, Exception nestedException) {
super(message, nestedException);
setErrorMessage(message);
}
/**
* Constructs a new MobileDeviceManagementDAOException with the specified detail message
* and cause.
*
* @param message the detail message.
* @param cause the cause of this exception.
*/
public AndroidFeatureManagementDAOException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
/**
* Constructs a new MobileDeviceManagementDAOException with the specified detail message.
*
* @param message the detail message.
*/
public AndroidFeatureManagementDAOException(String message) {
super(message);
setErrorMessage(message);
}
/**
* Constructs a new MobileDeviceManagementDAOException with the specified and cause.
*
* @param cause the cause of this exception.
*/
public AndroidFeatureManagementDAOException(Throwable cause) {
super(cause);
}
public String getMessage() {
return message;
}
public void setErrorMessage(String errorMessage) {
this.message = errorMessage;
}
}

View File

@ -1,265 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceDAO;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.util.MobileDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.mobile.dto.MobileDevice;
import org.wso2.carbon.device.mgt.mobile.impl.android.dao.AndroidDAOFactory;
import org.wso2.carbon.device.mgt.mobile.impl.android.util.AndroidPluginConstants;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements MobileDeviceDAO for Android Devices.
*/
public class AndroidDeviceDAOImpl implements MobileDeviceDAO{
private static final Log log = LogFactory.getLog(AndroidDeviceDAOImpl.class);
@Override
public MobileDevice getMobileDevice(String mblDeviceId) throws MobileDeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
MobileDevice mobileDevice = null;
ResultSet rs = null;
try {
conn = AndroidDAOFactory.getConnection();
String selectDBQuery =
"SELECT DEVICE_ID, GCM_TOKEN, DEVICE_INFO, DEVICE_MODEL, SERIAL, " +
"VENDOR, MAC_ADDRESS, DEVICE_NAME, LATITUDE, LONGITUDE, IMEI, IMSI, OS_VERSION" +
" FROM AD_DEVICE WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, mblDeviceId);
rs = stmt.executeQuery();
if (rs.next()) {
mobileDevice = new MobileDevice();
mobileDevice.setMobileDeviceId(rs.getString(AndroidPluginConstants.DEVICE_ID));
mobileDevice.setModel(rs.getString(AndroidPluginConstants.DEVICE_MODEL));
mobileDevice.setSerial(rs.getString(AndroidPluginConstants.SERIAL));
mobileDevice.setVendor(rs.getString(AndroidPluginConstants.VENDOR));
mobileDevice.setLatitude(rs.getString(AndroidPluginConstants.LATITUDE));
mobileDevice.setLongitude(rs.getString(AndroidPluginConstants.LONGITUDE));
mobileDevice.setImei(rs.getString(AndroidPluginConstants.IMEI));
mobileDevice.setImsi(rs.getString(AndroidPluginConstants.IMSI));
mobileDevice.setOsVersion(rs.getString(AndroidPluginConstants.OS_VERSION));
Map<String, String> propertyMap = new HashMap<String, String>();
propertyMap.put(AndroidPluginConstants.GCM_TOKEN, rs.getString(AndroidPluginConstants.GCM_TOKEN));
propertyMap.put(AndroidPluginConstants.DEVICE_INFO, rs.getString(AndroidPluginConstants.DEVICE_INFO));
propertyMap.put(AndroidPluginConstants.DEVICE_NAME, rs.getString(AndroidPluginConstants.DEVICE_NAME));
mobileDevice.setDeviceProperties(propertyMap);
if (log.isDebugEnabled()) {
log.debug("Android device " + mblDeviceId + " data has been fetched from " +
"Android database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Android device : '" + mblDeviceId + "'";
log.error(msg, e);
throw new MobileDeviceManagementDAOException(msg, e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
AndroidDAOFactory.closeConnection();
}
return mobileDevice;
}
@Override
public boolean addMobileDevice(MobileDevice mobileDevice) throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = AndroidDAOFactory.getConnection();
String createDBQuery =
"INSERT INTO AD_DEVICE(DEVICE_ID, GCM_TOKEN, DEVICE_INFO, SERIAL, " +
"VENDOR, MAC_ADDRESS, DEVICE_NAME, LATITUDE, LONGITUDE, IMEI, IMSI, " +
"OS_VERSION, DEVICE_MODEL) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, mobileDevice.getMobileDeviceId());
Map<String, String> properties = mobileDevice.getDeviceProperties();
stmt.setString(2, properties.get(AndroidPluginConstants.GCM_TOKEN));
stmt.setString(3, properties.get(AndroidPluginConstants.DEVICE_INFO));
stmt.setString(4, mobileDevice.getSerial());
stmt.setString(5, mobileDevice.getVendor());
stmt.setString(6, mobileDevice.getMobileDeviceId());
stmt.setString(7, properties.get(AndroidPluginConstants.DEVICE_NAME));
stmt.setString(8, mobileDevice.getLatitude());
stmt.setString(9, mobileDevice.getLongitude());
stmt.setString(10, mobileDevice.getImei());
stmt.setString(11, mobileDevice.getImsi());
stmt.setString(12, mobileDevice.getOsVersion());
stmt.setString(13, mobileDevice.getModel());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Android device " + mobileDevice.getMobileDeviceId() + " data has been" +
" added to the Android database.");
}
}
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while adding the Android device '" +
mobileDevice.getMobileDeviceId() + "' information to the Android plugin data store.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean updateMobileDevice(MobileDevice mobileDevice) throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = AndroidDAOFactory.getConnection();
String updateDBQuery =
"UPDATE AD_DEVICE SET GCM_TOKEN = ?, DEVICE_INFO = ?, SERIAL = ?, VENDOR = ?, " +
"MAC_ADDRESS = ?, DEVICE_NAME = ?, LATITUDE = ?, LONGITUDE = ?, IMEI = ?, " +
"IMSI = ?, OS_VERSION = ?, DEVICE_MODEL = ? WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
Map<String, String> properties = mobileDevice.getDeviceProperties();
stmt.setString(1, properties.get(AndroidPluginConstants.GCM_TOKEN));
stmt.setString(2, properties.get(AndroidPluginConstants.DEVICE_INFO));
stmt.setString(3, mobileDevice.getSerial());
stmt.setString(4, mobileDevice.getVendor());
stmt.setString(5, mobileDevice.getMobileDeviceId());
stmt.setString(6, properties.get(AndroidPluginConstants.DEVICE_NAME));
stmt.setString(7, mobileDevice.getLatitude());
stmt.setString(8, mobileDevice.getLongitude());
stmt.setString(9, mobileDevice.getImei());
stmt.setString(10, mobileDevice.getImsi());
stmt.setString(11, mobileDevice.getOsVersion());
stmt.setString(12, mobileDevice.getModel());
stmt.setString(13, mobileDevice.getMobileDeviceId());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Android device " + mobileDevice.getMobileDeviceId() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Android device '" +
mobileDevice.getMobileDeviceId() + "' data.";
log.error(msg, e);
throw new MobileDeviceManagementDAOException(msg, e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean deleteMobileDevice(String mblDeviceId)
throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = AndroidDAOFactory.getConnection();
String deleteDBQuery =
"DELETE FROM AD_DEVICE WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, mblDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Android device " + mblDeviceId + " data has deleted" +
" from the Android database.");
}
}
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while deleting android device '" +
mblDeviceId + "'", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public List<MobileDevice> getAllMobileDevices() throws MobileDeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
MobileDevice mobileDevice;
List<MobileDevice> mobileDevices = new ArrayList<MobileDevice>();
try {
conn = AndroidDAOFactory.getConnection();
String selectDBQuery =
"SELECT DEVICE_ID, GCM_TOKEN, DEVICE_INFO, DEVICE_MODEL, SERIAL, " +
"VENDOR, MAC_ADDRESS, DEVICE_NAME, LATITUDE, LONGITUDE, IMEI, IMSI, OS_VERSION " +
"FROM AD_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
rs = stmt.executeQuery();
while (rs.next()) {
mobileDevice = new MobileDevice();
mobileDevice.setMobileDeviceId(rs.getString(AndroidPluginConstants.DEVICE_ID));
mobileDevice.setModel(rs.getString(AndroidPluginConstants.DEVICE_MODEL));
mobileDevice.setSerial(rs.getString(AndroidPluginConstants.SERIAL));
mobileDevice.setVendor(rs.getString(AndroidPluginConstants.VENDOR));
mobileDevice.setLatitude(rs.getString(AndroidPluginConstants.LATITUDE));
mobileDevice.setLongitude(rs.getString(AndroidPluginConstants.LONGITUDE));
mobileDevice.setImei(rs.getString(AndroidPluginConstants.IMEI));
mobileDevice.setImsi(rs.getString(AndroidPluginConstants.IMSI));
mobileDevice.setOsVersion(rs.getString(AndroidPluginConstants.OS_VERSION));
Map<String, String> propertyMap = new HashMap<>();
propertyMap.put(AndroidPluginConstants.GCM_TOKEN, rs.getString(AndroidPluginConstants.GCM_TOKEN));
propertyMap.put(AndroidPluginConstants.DEVICE_INFO, rs.getString(AndroidPluginConstants.DEVICE_INFO));
propertyMap.put(AndroidPluginConstants.DEVICE_NAME, rs.getString(AndroidPluginConstants.DEVICE_NAME));
mobileDevice.setDeviceProperties(propertyMap);
mobileDevices.add(mobileDevice);
}
if (log.isDebugEnabled()) {
log.debug("All Android device details have fetched from Android database.");
}
return mobileDevices;
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while fetching all Android device data", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
AndroidDAOFactory.closeConnection();
}
}
}

View File

@ -1,285 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.MobileFeatureDAO;
import org.wso2.carbon.device.mgt.mobile.dao.util.MobileDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.mobile.dto.MobileFeature;
import org.wso2.carbon.device.mgt.mobile.impl.android.dao.AndroidDAOFactory;
import org.wso2.carbon.device.mgt.mobile.impl.android.dao.AndroidFeatureManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.impl.android.util.AndroidPluginConstants;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class AndroidFeatureDAOImpl implements MobileFeatureDAO {
private static final Log log = LogFactory.getLog(AndroidFeatureDAOImpl.class);
public AndroidFeatureDAOImpl() {
}
@Override
public boolean addFeature(MobileFeature mobileFeature) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
boolean status = false;
Connection conn;
try {
conn = AndroidDAOFactory.getConnection();
String sql = "INSERT INTO AD_FEATURE(CODE, NAME, DESCRIPTION) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, mobileFeature.getCode());
stmt.setString(2, mobileFeature.getName());
stmt.setString(3, mobileFeature.getDescription());
stmt.executeUpdate();
status = true;
} catch (SQLException e) {
throw new AndroidFeatureManagementDAOException(
"Error occurred while adding android feature '" +
mobileFeature.getName() + "' into the metadata repository", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean addFeatures(List<MobileFeature> mobileFeatures) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
MobileFeature mobileFeature;
boolean status = false;
Connection conn;
try {
conn = AndroidDAOFactory.getConnection();
stmt = conn.prepareStatement("INSERT INTO AD_FEATURE(CODE, NAME, DESCRIPTION) VALUES (?, ?, ?)");
for (int i = 0; i < mobileFeatures.size(); i++) {
mobileFeature = mobileFeatures.get(i);
stmt.setString(1, mobileFeature.getCode());
stmt.setString(2, mobileFeature.getName());
stmt.setString(3, mobileFeature.getDescription());
stmt.addBatch();
}
stmt.executeBatch();
status = true;
} catch (SQLException e) {
throw new AndroidFeatureManagementDAOException(
"Error occurred while adding android features into the metadata repository", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean updateFeature(MobileFeature mobileFeature) throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = AndroidDAOFactory.getConnection();
String updateDBQuery =
"UPDATE AD_FEATURE SET NAME = ?, DESCRIPTION = ?" +
"WHERE CODE = ?";
stmt = conn.prepareStatement(updateDBQuery);
stmt.setString(1, mobileFeature.getName());
stmt.setString(2, mobileFeature.getDescription());
stmt.setString(3, mobileFeature.getCode());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Android Feature " + mobileFeature.getCode() + " data has been " +
"modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while updating the Android Feature '" +
mobileFeature.getCode() + "' to the Android db.";
log.error(msg, e);
throw new AndroidFeatureManagementDAOException(msg, e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean deleteFeatureById(int mblFeatureId) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
boolean status = false;
Connection conn;
try {
conn = AndroidDAOFactory.getConnection();
String sql = "DELETE FROM AD_FEATURE WHERE ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, mblFeatureId);
stmt.execute();
status = true;
} catch (SQLException e) {
throw new AndroidFeatureManagementDAOException(
"Error occurred while deleting android feature '" +
mblFeatureId + "' from Android database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean deleteFeatureByCode(String mblFeatureCode) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
boolean status = false;
Connection conn;
try {
conn = AndroidDAOFactory.getConnection();
String sql = "DELETE FROM AD_FEATURE WHERE CODE = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, mblFeatureCode);
stmt.execute();
status = true;
} catch (SQLException e) {
throw new AndroidFeatureManagementDAOException(
"Error occurred while deleting android feature '" +
mblFeatureCode + "' from Android database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public MobileFeature getFeatureById(int mblFeatureId) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn;
try {
conn = AndroidDAOFactory.getConnection();
String sql = "SELECT ID, CODE, NAME, DESCRIPTION FROM AD_FEATURE WHERE ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, mblFeatureId);
rs = stmt.executeQuery();
MobileFeature mobileFeature = null;
if (rs.next()) {
mobileFeature = new MobileFeature();
mobileFeature.setId(rs.getInt(AndroidPluginConstants.ANDROID_FEATURE_ID));
mobileFeature.setCode(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_CODE));
mobileFeature.setName(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_NAME));
mobileFeature.setDescription(rs.getString(AndroidPluginConstants.
ANDROID_FEATURE_DESCRIPTION));
mobileFeature.setDeviceType(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
}
return mobileFeature;
} catch (SQLException e) {
throw new AndroidFeatureManagementDAOException(
"Error occurred while retrieving android feature '" +
mblFeatureId + "' from the Android database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
AndroidDAOFactory.closeConnection();
}
}
@Override
public MobileFeature getFeatureByCode(String mblFeatureCode) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn;
try {
conn = AndroidDAOFactory.getConnection();
String sql = "SELECT ID, CODE, NAME, DESCRIPTION FROM AD_FEATURE WHERE CODE = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, mblFeatureCode);
rs = stmt.executeQuery();
MobileFeature mobileFeature = null;
if (rs.next()) {
mobileFeature = new MobileFeature();
mobileFeature.setId(rs.getInt(AndroidPluginConstants.ANDROID_FEATURE_ID));
mobileFeature.setCode(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_CODE));
mobileFeature.setName(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_NAME));
mobileFeature.setDescription(rs.getString(AndroidPluginConstants.
ANDROID_FEATURE_DESCRIPTION));
mobileFeature.setDeviceType(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
}
return mobileFeature;
} catch (SQLException e) {
throw new AndroidFeatureManagementDAOException(
"Error occurred while retrieving android feature '" +
mblFeatureCode + "' from the Android database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
AndroidDAOFactory.closeConnection();
}
}
@Override
public List<MobileFeature> getFeatureByDeviceType(String deviceType)
throws MobileDeviceManagementDAOException {
return this.getAllFeatures();
}
@Override
public List<MobileFeature> getAllFeatures() throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn = null;
List<MobileFeature> features = new ArrayList<>();
try {
conn = AndroidDAOFactory.getConnection();
String sql = "SELECT ID, CODE, NAME, DESCRIPTION FROM AD_FEATURE";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
MobileFeature mobileFeature = null;
while (rs.next()) {
mobileFeature = new MobileFeature();
mobileFeature.setId(rs.getInt(AndroidPluginConstants.ANDROID_FEATURE_ID));
mobileFeature.setCode(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_CODE));
mobileFeature.setName(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_NAME));
mobileFeature.setDescription(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_DESCRIPTION));
mobileFeature.setDeviceType(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
features.add(mobileFeature);
}
return features;
} catch (SQLException e) {
throw new AndroidFeatureManagementDAOException("Error occurred while retrieving all " +
"android features from the android database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
AndroidDAOFactory.closeConnection();
}
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.gcm;
/**
* Represents model object for holding GCM response data.
*/
public class GCMResult {
private String errorMsg;
private String msg;
private int statusCode;
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
}

View File

@ -1,64 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.gcm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import java.util.ArrayList;
import java.util.List;
/**
* GCM notification service implementation for Android platform.
*/
public class GCMService {
private static final Log log = LogFactory.getLog(GCMService.class);
private static final String NOTIFIER_TYPE = "notifierType";
private static final String GCM_NOTIFIER_CODE = "2";
public boolean isGCMEnabled() {
String notifierType = GCMUtil.getConfigurationProperty(NOTIFIER_TYPE);
if (GCM_NOTIFIER_CODE.equals(notifierType)) {
return true;
}
return false;
}
public void sendNotification(String messageData, Device device) {
List<Device> devices = new ArrayList<>(1);
devices.add(device);
GCMResult result = GCMUtil.sendWakeUpCall(messageData, devices);
if (result.getStatusCode() != 200) {
log.error("Exception occurred while sending the GCM notification : " + result.getErrorMsg());
}
}
public void sendNotification(String messageData, List<Device> devices) {
GCMResult result = GCMUtil.sendWakeUpCall(messageData, devices);
if (result.getStatusCode() != 200) {
log.error("Exception occurred while sending the GCM notification : " + result.getErrorMsg());
}
}
public void resetTenantConfigCache() {
GCMUtil.resetTenantConfigCache();
}
}

View File

@ -1,199 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.gcm;
import com.google.gson.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.mobile.impl.android.AndroidDeviceManagementService;
import org.wso2.carbon.device.mgt.mobile.impl.android.util.AndroidPluginConstants;
import org.wso2.carbon.device.mgt.mobile.internal.MobileDeviceManagementDataHolder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Implements utility methods used by GCMService.
*/
public class GCMUtil {
private static final Log log = LogFactory.getLog(GCMService.class);
private final static String GCM_ENDPOINT = "https://gcm-http.googleapis.com/gcm/send";
private static final String GCM_API_KEY = "gcmAPIKey";
private static final int TIME_TO_LIVE = 60;
private static final int HTTP_STATUS_CODE_OK = 200;
private static HashMap<Integer,TenantConfiguration> tenantConfigurationCache = new HashMap<>();
public static GCMResult sendWakeUpCall(String message, List<Device> devices) {
GCMResult result = new GCMResult();
byte[] bytes = getGCMRequest(message, getGCMTokens(devices)).getBytes();
HttpURLConnection conn;
try {
conn = (HttpURLConnection) (new URL(GCM_ENDPOINT)).openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + getConfigurationProperty(GCM_API_KEY));
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
int status = conn.getResponseCode();
result.setStatusCode(status);
if (status != HTTP_STATUS_CODE_OK) {
result.setErrorMsg(getString(conn.getErrorStream()));
} else {
result.setMsg(getString(conn.getInputStream()));
}
} catch (ProtocolException e) {
log.error("Exception occurred while setting the HTTP protocol.", e);
} catch (IOException ex) {
log.error("Exception occurred while sending the GCM request.", ex);
}
return result;
}
private static String getString(InputStream stream) throws IOException {
if (stream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder content = new StringBuilder();
String newLine;
do {
newLine = reader.readLine();
if (newLine != null) {
content.append(newLine).append('\n');
}
} while (newLine != null);
if (content.length() > 0) {
content.setLength(content.length() - 1);
}
return content.toString();
}
return null;
}
private static String getGCMRequest(String message, List<String> registrationIds) {
JsonObject gcmRequest = new JsonObject();
gcmRequest.addProperty("delay_while_idle", false);
gcmRequest.addProperty("time_to_live", TIME_TO_LIVE);
//Add message to GCM request
JsonObject data = new JsonObject();
if (message != null && !message.isEmpty()) {
data.addProperty("data", message);
gcmRequest.add("data", data);
}
//Set device reg-ids
JsonArray regIds = new JsonArray();
for (String regId : registrationIds) {
if (regId == null || regId.isEmpty()) {
continue;
}
regIds.add(new JsonPrimitive(regId));
}
gcmRequest.add("registration_ids", regIds);
return gcmRequest.toString();
}
private static List<String> getGCMTokens(List<Device> devices) {
List<String> tokens = new ArrayList<>(devices.size());
for (Device device : devices) {
tokens.add(getGCMToken(device.getProperties()));
}
return tokens;
}
private static String getGCMToken(List<Device.Property> properties) {
String gcmToken = null;
for (Device.Property property : properties) {
if (AndroidPluginConstants.GCM_TOKEN.equals(property.getName())) {
gcmToken = property.getValue();
break;
}
}
return gcmToken;
}
public static String getConfigurationProperty(String property) {
DeviceManagementService androidDMService = new AndroidDeviceManagementService();
try {
//Get the TenantConfiguration from cache if not we'll get it from DM service
TenantConfiguration tenantConfiguration = getTenantConfigurationFromCache();
if (tenantConfiguration == null) {
androidDMService.init();
tenantConfiguration = androidDMService.getDeviceManager().getConfiguration();
if (tenantConfiguration != null) {
addTenantConfigurationToCache(tenantConfiguration);
}
}
if (tenantConfiguration != null) {
List<ConfigurationEntry> configs = tenantConfiguration.getConfiguration();
for (ConfigurationEntry entry : configs) {
if (property.equals(entry.getName())) {
return (String) entry.getValue();
}
}
}
return "";
} catch (DeviceManagementException e) {
log.error("Exception occurred while fetching the tenant-config.",e);
}
return null;
}
public static void resetTenantConfigCache() {
tenantConfigurationCache.remove(getTenantId());
}
private static void addTenantConfigurationToCache(TenantConfiguration tenantConfiguration) {
tenantConfigurationCache.put(getTenantId(), tenantConfiguration);
}
private static TenantConfiguration getTenantConfigurationFromCache() {
return tenantConfigurationCache.get(getTenantId());
}
private static int getTenantId() {
return CarbonContext.getThreadLocalCarbonContext().getTenantId();
}
}

View File

@ -1,47 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.util;
/**
* Defines constants used by android plugin.
*/
public class AndroidPluginConstants {
//Properties related to AD_DEVICE table
public static final String DEVICE_ID = "DEVICE_ID";
public static final String GCM_TOKEN = "GCM_TOKEN";
public static final String DEVICE_INFO = "DEVICE_INFO";
public static final String SERIAL = "SERIAL";
public static final String DEVICE_MODEL = "DEVICE_MODEL";
public static final String DEVICE_NAME = "DEVICE_NAME";
public static final String LATITUDE = "LATITUDE";
public static final String LONGITUDE = "LONGITUDE";
public static final String IMEI = "IMEI";
public static final String IMSI = "IMSI";
public static final String VENDOR = "VENDOR";
public static final String OS_VERSION = "OS_VERSION";
public static final String MAC_ADDRESS = "MAC_ADDRESS";
//Properties related to AD_FEATURE table
public static final String ANDROID_FEATURE_ID = "ID";
public static final String ANDROID_FEATURE_CODE = "CODE";
public static final String ANDROID_FEATURE_NAME = "NAME";
public static final String ANDROID_FEATURE_DESCRIPTION = "DESCRIPTION";
}

View File

@ -1,58 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.util;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.mobile.impl.android.AndroidDeviceManagementService;
/**
* Contains utility methods used by Android plugin.
*/
public class AndroidPluginUtils {
public static License getDefaultLicense() {
License license = new License();
license.setName(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID);
license.setLanguage("en_US");
license.setVersion("1.0.0");
license.setText("This End User License Agreement (\"Agreement\") is a legal agreement between you (\"You\") " +
"and WSO2, Inc., regarding the enrollment of Your personal mobile device (\"Device\") in SoR's " +
"mobile device management program, and the loading to and removal from Your Device and Your use " +
"of certain applications and any associated software and user documentation, whether provided in " +
"\"online\" or electronic format, used in connection with the operation of or provision of services " +
"to WSO2, Inc., BY SELECTING \"I ACCEPT\" DURING INSTALLATION, YOU ARE ENROLLING YOUR DEVICE, AND " +
"THEREBY AUTHORIZING SOR OR ITS AGENTS TO INSTALL, UPDATE AND REMOVE THE APPS FROM YOUR DEVICE AS " +
"DESCRIBED IN THIS AGREEMENT. YOU ARE ALSO EXPLICITLY ACKNOWLEDGING AND AGREEING THAT (1) THIS IS " +
"A BINDING CONTRACT AND (2) YOU HAVE READ AND AGREE TO THE TERMS OF THIS AGREEMENT.\n" +
"\n" +
"IF YOU DO NOT ACCEPT THESE TERMS, DO NOT ENROLL YOUR DEVICE AND DO NOT PROCEED ANY FURTHER.\n" +
"\n" +
"You agree that: (1) You understand and agree to be bound by the terms and conditions contained " +
"in this Agreement, and (2) You are at least 21 years old and have the legal capacity to enter " +
"into this Agreement as defined by the laws of Your jurisdiction. SoR shall have the right, " +
"without prior notice, to terminate or suspend (i) this Agreement, (ii) the enrollment of Your " +
"Device, or (iii) the functioning of the Apps in the event of a violation of this Agreement or " +
"the cessation of Your relationship with SoR (including termination of Your employment if You are " +
"an employee or expiration or termination of Your applicable franchise or supply agreement if You " +
"are a franchisee of or supplier to the WSO2 WSO2, Inc., system). SoR expressly reserves all " +
"rights not expressly granted herein.");
return license;
}
}

View File

@ -1,31 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.android.util;
import java.util.Map;
/**
* Contains utility methods used by Android plugin.
*/
public class AndroidUtils {
public static String getDeviceProperty(Map<String, String> deviceProperties, String property) {
return deviceProperties.get(property);
}
}

View File

@ -1,73 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
/**
* This represents the Windows implementation of DeviceManagerService.
*/
public class WindowsDeviceManagementService implements DeviceManagementService {
private DeviceManager deviceManager;
public static final String DEVICE_TYPE_WINDOWS = "windows";
private static final String SUPER_TENANT_DOMAIN = "carbon.super";
@Override
public String getType() {
return WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new WindowsDeviceManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public ProvisioningConfig getProvisioningConfig() {
return new ProvisioningConfig(SUPER_TENANT_DOMAIN, true);
}
@Override
public PushNotificationConfig getPushNotificationConfig() {
return null;
}
}

View File

@ -1,312 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
import org.wso2.carbon.device.mgt.extensions.license.mgt.registry.RegistryBasedLicenseManager;
import org.wso2.carbon.device.mgt.mobile.common.MobileDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.common.MobilePluginConstants;
import org.wso2.carbon.device.mgt.mobile.dao.AbstractMobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dto.MobileDevice;
import org.wso2.carbon.device.mgt.mobile.impl.windows.dao.WindowsDAOFactory;
import org.wso2.carbon.device.mgt.mobile.impl.windows.util.WindowsPluginUtils;
import org.wso2.carbon.device.mgt.mobile.util.MobileDeviceManagementUtil;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class WindowsDeviceManager implements DeviceManager {
private AbstractMobileDeviceManagementDAOFactory daoFactory;
private LicenseManager licenseManager;
private FeatureManager featureManager = new WindowsFeatureManager();
private static final Log log = LogFactory.getLog(WindowsDeviceManagementService.class);
public WindowsDeviceManager() {
this.daoFactory = new WindowsDAOFactory();
this.licenseManager = new RegistryBasedLicenseManager();
License defaultLicense = WindowsPluginUtils.getDefaultLicense();
try {
if (licenseManager.getLicense(WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS,
MobilePluginConstants.LANGUAGE_CODE_ENGLISH_US) == null) {
licenseManager.addLicense(WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS, defaultLicense);
}
featureManager.addSupportedFeaturesToDB();
} catch (LicenseManagementException e) {
log.error("Error occurred while adding default license for Windows devices", e);
} catch (DeviceManagementException e) {
throw new IllegalStateException("Error occurred while adding windows features to the DB.");
}
}
@Override
public FeatureManager getFeatureManager() {
return featureManager;
}
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration) throws DeviceManagementException {
boolean status;
Resource resource;
try {
if (log.isDebugEnabled()) {
log.debug("Persisting windows configurations in Registry");
}
String resourcePath = MobileDeviceManagementUtil.getPlatformConfigPath(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(tenantConfiguration, writer);
resource = MobileDeviceManagementUtil.getConfigurationRegistry().newResource();
resource.setContent(writer.toString());
resource.setMediaType(MobilePluginConstants.MEDIA_TYPE_XML);
MobileDeviceManagementUtil.putRegistryResource(resourcePath, resource);
status = true;
} catch (MobileDeviceMgtPluginException e) {
throw new DeviceManagementException(
"Error occurred while retrieving the Registry instance", e);
} catch (RegistryException e) {
throw new DeviceManagementException(
"Error occurred while persisting the Registry resource of Windows configuration", e);
} catch (JAXBException e) {
throw new DeviceManagementException(
"Error occurred while parsing the Windows configuration", e);
}
return status;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
Resource resource;
try {
String windowsTenantRegistryPath = MobileDeviceManagementUtil.
getPlatformConfigPath(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
resource = MobileDeviceManagementUtil.getRegistryResource(windowsTenantRegistryPath);
if (resource != null) {
JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
return (TenantConfiguration) unmarshaller.unmarshal(new StringReader(
new String((byte[]) resource.getContent(), Charset.
forName(MobilePluginConstants.CHARSET_UTF8))));
}
return null;
} catch (MobileDeviceMgtPluginException e) {
throw new DeviceManagementException(
"Error occurred while retrieving the Registry instance", e);
} catch (JAXBException e) {
throw new DeviceManagementException(
"Error occurred while parsing the Windows configuration", e);
} catch (RegistryException e) {
throw new DeviceManagementException(
"Error occurred while retrieving the Registry resource of Windows configuration", e);
}
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status = false;
MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device);
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Windows device enrollment data");
}
WindowsDAOFactory.beginTransaction();
if (daoFactory.getMobileDeviceDAO() != null) {
status = daoFactory.getMobileDeviceDAO().updateMobileDevice(mobileDevice);
}
WindowsDAOFactory.commitTransaction();
} catch (MobileDeviceManagementDAOException e) {
WindowsDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while updating the enrollment of the " +
"Windows device : " + device.getDeviceIdentifier(), e);
} finally {
WindowsDAOFactory.closeConnection();
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
//Here we don't have anything specific to do. Hence returning.
return true;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
MobileDevice mobileDevice;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Windows device : " + deviceId.getId());
}
if (daoFactory.getMobileDeviceDAO() != null) {
mobileDevice = daoFactory.getMobileDeviceDAO().getMobileDevice(deviceId.getId());
} else {
throw new DeviceManagementException("Error occurred while getting DAO object.");
}
} catch (MobileDeviceManagementDAOException e) {
String msg = "Error occurred while checking the enrollment status of Windows device : " + deviceId.getId();
throw new DeviceManagementException(msg, e);
}
return (mobileDevice != null);
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null;
List<MobileDevice> mobileDevices = null;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Windows devices");
}
WindowsDAOFactory.openConnection();
if (daoFactory.getMobileDeviceDAO() != null) {
mobileDevices = daoFactory.getMobileDeviceDAO().getAllMobileDevices();
}
if (mobileDevices != null) {
devices = new ArrayList<>(mobileDevices.size());
for (MobileDevice mobileDevice : mobileDevices) {
devices.add(MobileDeviceManagementUtil.convertToDevice(mobileDevice));
}
}
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while fetching all Windows devices", e);
} finally {
WindowsDAOFactory.closeConnection();
}
return devices;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device = null;
MobileDevice mobileDevice = null;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Windows device : '" + deviceId.getId() + "'");
}
WindowsDAOFactory.openConnection();
if (daoFactory.getMobileDeviceDAO() != null) {
mobileDevice = daoFactory.getMobileDeviceDAO().getMobileDevice(deviceId.getId());
}
device = MobileDeviceManagementUtil.convertToDevice(mobileDevice);
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException(
"Error occurred while fetching the Windows device: '" + deviceId.getId() + "'", e);
} finally {
WindowsDAOFactory.closeConnection();
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
@Override
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceIdentifier, String currentUser,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String languageCode) throws LicenseManagementException {
return licenseManager.getLicense(WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS, languageCode);
}
@Override
public void addLicense(License license) throws LicenseManagementException {
licenseManager.addLicense(WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS, license);
}
@Override
public boolean requireDeviceAuthorization() {
return false;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier,
Device device) throws DeviceManagementException {
return true;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status = false;
MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device);
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new windows device : " + device.getDeviceIdentifier());
}
boolean isEnrolled = this.isEnrolled(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
if (isEnrolled) {
this.modifyEnrollment(device);
} else {
WindowsDAOFactory.beginTransaction();
if (daoFactory.getMobileDeviceDAO() != null) {
status = daoFactory.getMobileDeviceDAO().addMobileDevice(mobileDevice);
}
WindowsDAOFactory.commitTransaction();
}
} catch (MobileDeviceManagementDAOException e) {
WindowsDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while enrolling the windows device : "
+ device.getDeviceIdentifier(), e);
}
return status;
}
}

View File

@ -1,198 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileFeatureDAO;
import org.wso2.carbon.device.mgt.mobile.dto.MobileFeature;
import org.wso2.carbon.device.mgt.mobile.impl.windows.dao.WindowsDAOFactory;
import org.wso2.carbon.device.mgt.mobile.impl.windows.util.WindowsUtils;
import org.wso2.carbon.device.mgt.mobile.util.MobileDeviceManagementUtil;
import java.util.ArrayList;
import java.util.List;
public class WindowsFeatureManager implements FeatureManager {
private MobileFeatureDAO featureDAO;
public WindowsFeatureManager() {
MobileDeviceManagementDAOFactory daoFactory = new WindowsDAOFactory();
this.featureDAO = daoFactory.getMobileFeatureDAO();
}
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
try {
WindowsDAOFactory.beginTransaction();
MobileFeature mobileFeature = MobileDeviceManagementUtil.convertToMobileFeature(feature);
featureDAO.addFeature(mobileFeature);
WindowsDAOFactory.commitTransaction();
return true;
} catch (MobileDeviceManagementDAOException e) {
WindowsDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while adding the feature", e);
} finally {
WindowsDAOFactory.closeConnection();
}
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
List<MobileFeature> mobileFeatures = new ArrayList<MobileFeature>(features.size());
for (Feature feature : features) {
mobileFeatures.add(MobileDeviceManagementUtil.convertToMobileFeature(feature));
}
try {
WindowsDAOFactory.beginTransaction();
featureDAO.addFeatures(mobileFeatures);
WindowsDAOFactory.commitTransaction();
return true;
} catch (MobileDeviceManagementDAOException e) {
WindowsDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while adding the features", e);
} finally {
WindowsDAOFactory.closeConnection();
}
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
try {
WindowsDAOFactory.openConnection();
MobileFeature mobileFeature = featureDAO.getFeatureByCode(name);
Feature feature = MobileDeviceManagementUtil.convertToFeature(mobileFeature);
return feature;
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the feature", e);
} finally {
WindowsDAOFactory.closeConnection();
}
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
try {
WindowsDAOFactory.openConnection();
List<MobileFeature> mobileFeatures = featureDAO.getAllFeatures();
List<Feature> featureList = new ArrayList<Feature>(mobileFeatures.size());
for (MobileFeature mobileFeature : mobileFeatures) {
featureList.add(MobileDeviceManagementUtil.convertToFeature(mobileFeature));
}
return featureList;
} catch (MobileDeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while retrieving the list of features registered for " +
"Windows platform", e);
} finally {
WindowsDAOFactory.closeConnection();
}
}
@Override
public boolean removeFeature(String code) throws DeviceManagementException {
boolean status;
try {
WindowsDAOFactory.beginTransaction();
featureDAO.deleteFeatureByCode(code);
WindowsDAOFactory.commitTransaction();
status = true;
return status;
} catch (MobileDeviceManagementDAOException e) {
WindowsDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while removing the feature", e);
} finally {
WindowsDAOFactory.closeConnection();
}
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
synchronized (this) {
List<Feature> supportedFeatures = getSupportedFeatures();
List<Feature> existingFeatures = this.getFeatures();
List<Feature> missingFeatures = MobileDeviceManagementUtil.
getMissingFeatures(supportedFeatures, existingFeatures);
if (missingFeatures.size() > 0) {
return this.addFeatures(missingFeatures);
}
return true;
}
}
/**
* Get supported Windows features.
*
* @return Supported features.
*/
public static List<Feature> getSupportedFeatures() {
List<Feature> supportedFeatures = new ArrayList<>();
Feature feature;
feature = WindowsUtils.getMobileFeature();
feature.setCode("DEVICE_LOCK");
feature.setName("Device Lock");
feature.setDescription("Lock the device");
supportedFeatures.add(feature);
feature = WindowsUtils.getMobileFeature();
feature.setCode("CAMERA");
feature.setName("camera");
feature.setDescription("Enable or disable camera");
supportedFeatures.add(feature);
feature = WindowsUtils.getMobileFeature();
feature.setCode("DEVICE_INFO");
feature.setName("Device info");
feature.setDescription("Request device information");
supportedFeatures.add(feature);
feature = WindowsUtils.getMobileFeature();
feature.setCode("WIPE_DATA");
feature.setName("Wipe Data");
feature.setDescription("Factory reset the device");
supportedFeatures.add(feature);
feature = WindowsUtils.getMobileFeature();
feature.setCode("ENCRYPT_STORAGE");
feature.setName("Encrypt storage");
feature.setDescription("Encrypt storage");
supportedFeatures.add(feature);
feature = WindowsUtils.getMobileFeature();
feature.setCode("DEVICE_RING");
feature.setName("Ring");
feature.setDescription("Ring the device");
supportedFeatures.add(feature);
feature = WindowsUtils.getMobileFeature();
feature.setCode("PASSCODE_POLICY");
feature.setName("Password Policy");
feature.setDescription("Set passcode policy");
supportedFeatures.add(feature);
feature = WindowsUtils.getMobileFeature();
feature.setCode("DISENROLL");
feature.setName("DisEnroll");
feature.setDescription("DisEnroll the device");
supportedFeatures.add(feature);
feature = WindowsUtils.getMobileFeature();
feature.setCode("LOCK_RESET");
feature.setName("LockReset");
feature.setDescription("Lock Reset device");
supportedFeatures.add(feature);
return supportedFeatures;
}
}

View File

@ -1,73 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService;
import java.util.ArrayList;
import java.util.List;
public class WindowsPolicyMonitoringService implements PolicyMonitoringService {
private static Log log = LogFactory.getLog(WindowsPolicyMonitoringService.class);
@Override
public void notifyDevices(List<Device> list) throws PolicyComplianceException {
}
@Override
public ComplianceData checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy, Object compliancePayload)
throws PolicyComplianceException {
if (log.isDebugEnabled()) {
log.debug("checking policy compliance status of device '" + deviceIdentifier.getId() + "'");
}
List<ComplianceFeature> complianceFeatures = (List<ComplianceFeature>) compliancePayload;
List<ComplianceFeature> nonComplianceFeatures = new ArrayList<>();
ComplianceData complianceData = new ComplianceData();
if (policy == null || compliancePayload == null) {
return complianceData;
}
for (ComplianceFeature complianceFeature : complianceFeatures) {
if (!complianceFeature.isCompliant()) {
complianceData.setStatus(false);
nonComplianceFeatures.add(complianceFeature);
break;
}
}
complianceData.setComplianceFeatures(nonComplianceFeatures);
return complianceData;
}
@Override
public String getType() {
return DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS;
}
}

View File

@ -1,132 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.mobile.dao.AbstractMobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceDAO;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.MobileFeatureDAO;
import org.wso2.carbon.device.mgt.mobile.impl.windows.dao.impl.WindowsDeviceDAOImpl;
import org.wso2.carbon.device.mgt.mobile.impl.windows.dao.impl.WindowsFeatureDAOImpl;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class WindowsDAOFactory extends AbstractMobileDeviceManagementDAOFactory {
private static final Log log = LogFactory.getLog(WindowsDAOFactory.class);
protected static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public WindowsDAOFactory() {
this.dataSource = getDataSourceMap().get(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
}
@Override
public MobileDeviceDAO getMobileDeviceDAO() {
return new WindowsDeviceDAOImpl();
}
@Override
public MobileFeatureDAO getMobileFeatureDAO() {
return new WindowsFeatureDAOImpl();
}
public static void beginTransaction() throws MobileDeviceManagementDAOException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while retrieving datasource connection", e);
}
}
public static void openConnection() throws MobileDeviceManagementDAOException {
if (currentConnection.get() == null) {
Connection conn;
try {
conn = dataSource.getConnection();
currentConnection.set(conn);
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException
("Error occurred while retrieving data source connection", e);
}
}
}
public static Connection getConnection() throws MobileDeviceManagementDAOException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException
("Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted");
}
}
} catch (SQLException e) {
log.error("Error occurred while committing the transaction", e);
}
}
public static void closeConnection() {
Connection con = currentConnection.get();
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
currentConnection.remove();
}
public static void rollbackTransaction() {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback " +
"has not been attempted");
}
}
} catch (SQLException e) {
log.warn("Error occurred while roll-backing the transaction", e);
}
}
}

View File

@ -1,80 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows.dao;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
/**
* This class responsible for wrapping exceptions related on Windows device features.
*/
public class WindowsFeatureManagementDAOException extends MobileDeviceManagementDAOException {
private String message;
private static final long serialVersionUID = 2021891706072918865L;
/**
* Constructs a new MobileDeviceManagementDAOException with the specified detail message and
* nested exception.
*
* @param message error message
* @param nestedException exception
*/
public WindowsFeatureManagementDAOException(String message, Exception nestedException) {
super(message, nestedException);
}
/**
* Constructs a new MobileDeviceManagementDAOException with the specified detail message
* and cause.
*
* @param message the detail message.
* @param cause the cause of this exception.
*/
public WindowsFeatureManagementDAOException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
/**
* Constructs a new MobileDeviceManagementDAOException with the specified detail message.
*
* @param message the detail message.
*/
public WindowsFeatureManagementDAOException(String message) {
super(message);
setErrorMessage(message);
}
/**
* Constructs a new MobileDeviceManagementDAOException with the specified and cause.
*
* @param cause the cause of this exception.
*/
public WindowsFeatureManagementDAOException(Throwable cause) {
super(cause);
}
public String getMessage() {
return message;
}
public void setErrorMessage(String errorMessage) {
this.message = errorMessage;
}
}

View File

@ -1,238 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceDAO;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.util.MobileDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.mobile.dto.MobileDevice;
import org.wso2.carbon.device.mgt.mobile.impl.windows.dao.WindowsDAOFactory;
import org.wso2.carbon.device.mgt.mobile.impl.windows.util.WindowsPluginConstants;
import org.wso2.carbon.device.mgt.mobile.impl.windows.util.WindowsUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements MobileDeviceDAO for Windows Devices.
*/
public class WindowsDeviceDAOImpl implements MobileDeviceDAO {
private static final Log log = LogFactory.getLog(WindowsDeviceDAOImpl.class);
@Override
public MobileDevice getMobileDevice(String mblDeviceId) throws MobileDeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
MobileDevice mobileDevice = null;
try {
conn = WindowsDAOFactory.getConnection();
String selectDBQuery =
"SELECT DEVICE_ID, CHANNEL_URI, DEVICE_INFO, IMEI, IMSI, " +
"OS_VERSION, DEVICE_MODEL, VENDOR, LATITUDE, LONGITUDE, SERIAL, MAC_ADDRESS," +
" OS_VERSION, DEVICE_NAME " +
"FROM WIN_DEVICE WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, mblDeviceId);
rs = stmt.executeQuery();
while (rs.next()) {
mobileDevice = WindowsUtils.loadMobileDevices(rs);
Map<String, String> propertyMap = new HashMap<>();
propertyMap.put(WindowsPluginConstants.CHANNEL_URI, rs.getString(WindowsPluginConstants.CHANNEL_URI));
propertyMap.put(WindowsPluginConstants.DEVICE_INFO, rs.getString(WindowsPluginConstants.DEVICE_INFO));
propertyMap.put(WindowsPluginConstants.MAC_ADDRESS, rs.getString(WindowsPluginConstants.MAC_ADDRESS));
propertyMap.put(WindowsPluginConstants.DEVICE_NAME, rs.getString(WindowsPluginConstants.DEVICE_NAME));
mobileDevice.setDeviceProperties(propertyMap);
}
if (log.isDebugEnabled()) {
log.debug("All Windows device details have fetched from Windows database.");
}
return mobileDevice;
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while fetching all Windows device data", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public boolean addMobileDevice(MobileDevice mobileDevice) throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = WindowsDAOFactory.getConnection();
String createDBQuery =
"INSERT INTO WIN_DEVICE(DEVICE_ID, CHANNEL_URI, DEVICE_INFO, IMEI, " +
"IMSI, OS_VERSION, DEVICE_MODEL, VENDOR, LATITUDE, LONGITUDE, SERIAL, " +
"MAC_ADDRESS, DEVICE_NAME) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, mobileDevice.getMobileDeviceId());
Map<String, String> properties = mobileDevice.getDeviceProperties();
stmt.setString(2, properties.get(WindowsPluginConstants.CHANNEL_URI));
stmt.setString(3, properties.get(WindowsPluginConstants.DEVICE_INFO));
stmt.setString(4, mobileDevice.getImei());
stmt.setString(5, mobileDevice.getImsi());
stmt.setString(6, mobileDevice.getOsVersion());
stmt.setString(7, mobileDevice.getModel());
stmt.setString(8, mobileDevice.getVendor());
stmt.setString(9, mobileDevice.getLatitude());
stmt.setString(10, mobileDevice.getLongitude());
stmt.setString(11, mobileDevice.getSerial());
stmt.setString(12, properties.get(WindowsPluginConstants.MAC_ADDRESS));
stmt.setString(13, properties.get(WindowsPluginConstants.DEVICE_NAME));
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Windows device " + mobileDevice.getMobileDeviceId() + " data has been" +
" added to the Windows database.");
}
}
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while adding the Windows device '" +
mobileDevice.getMobileDeviceId() + "' to the Windows db.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean updateMobileDevice(MobileDevice mobileDevice) throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = WindowsDAOFactory.getConnection();
String updateDBQuery =
"UPDATE WIN_DEVICE SET CHANNEL_URI = ?, DEVICE_INFO = ?, IMEI = ?, IMSI = ?, " +
"OS_VERSION = ?, DEVICE_MODEL = ?, VENDOR = ?, LATITUDE = ?, LONGITUDE = ?, " +
"SERIAL = ?, MAC_ADDRESS = ?, DEVICE_NAME = ? WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
Map<String, String> properties = mobileDevice.getDeviceProperties();
stmt.setString(1, properties.get(WindowsPluginConstants.CHANNEL_URI));
stmt.setString(2, properties.get(WindowsPluginConstants.DEVICE_INFO));
stmt.setString(3, mobileDevice.getImei());
stmt.setString(4, mobileDevice.getImsi());
stmt.setString(5, mobileDevice.getOsVersion());
stmt.setString(6, mobileDevice.getModel());
stmt.setString(7, mobileDevice.getVendor());
stmt.setString(8, mobileDevice.getLatitude());
stmt.setString(9, mobileDevice.getLongitude());
stmt.setString(10, mobileDevice.getSerial());
stmt.setString(11, properties.get(WindowsPluginConstants.MAC_ADDRESS));
stmt.setString(12, properties.get(WindowsPluginConstants.DEVICE_NAME));
stmt.setString(13, mobileDevice.getMobileDeviceId());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Windows device " + mobileDevice.getMobileDeviceId() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while modifying the Windows device '" +
mobileDevice.getMobileDeviceId() + "' data.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean deleteMobileDevice(String mblDeviceId) throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = WindowsDAOFactory.getConnection();
String deleteDBQuery = "DELETE FROM WIN_DEVICE WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, mblDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Windows device " + mblDeviceId + " data has deleted" +
" from the windows database.");
}
}
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while deleting windows device '" +
mblDeviceId + "'", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public List<MobileDevice> getAllMobileDevices() throws MobileDeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
MobileDevice mobileDevice;
List<MobileDevice> mobileDevices = new ArrayList<>();
try {
conn = WindowsDAOFactory.getConnection();
String selectDBQuery =
"SELECT DEVICE_ID, CHANNEL_URI, DEVICE_INFO, IMEI, IMSI, " +
"OS_VERSION, DEVICE_MODEL, VENDOR, LATITUDE, LONGITUDE, SERIAL, MAC_ADDRESS," +
" OS_VERSION, DEVICE_NAME " +
"FROM WIN_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
rs = stmt.executeQuery();
while (rs.next()) {
mobileDevice = WindowsUtils.loadMobileDevices(rs);
Map<String, String> propertyMap = new HashMap<>();
propertyMap.put(WindowsPluginConstants.CHANNEL_URI, rs.getString(WindowsPluginConstants.CHANNEL_URI));
propertyMap.put(WindowsPluginConstants.DEVICE_INFO, rs.getString(WindowsPluginConstants.DEVICE_INFO));
propertyMap.put(WindowsPluginConstants.DEVICE_NAME, rs.getString(WindowsPluginConstants.DEVICE_NAME));
mobileDevice.setDeviceProperties(propertyMap);
mobileDevices.add(mobileDevice);
}
if (log.isDebugEnabled()) {
log.debug("All Windows device details have fetched from Windows database.");
}
return mobileDevices;
} catch (SQLException e) {
throw new MobileDeviceManagementDAOException("Error occurred while fetching all Windows device data", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
}

View File

@ -1,267 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.MobileFeatureDAO;
import org.wso2.carbon.device.mgt.mobile.dao.util.MobileDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.mobile.dto.MobileFeature;
import org.wso2.carbon.device.mgt.mobile.impl.windows.dao.WindowsDAOFactory;
import org.wso2.carbon.device.mgt.mobile.impl.windows.dao.WindowsFeatureManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.impl.windows.util.WindowsPluginConstants;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Implement MobileFeatureDAO for Windows devices.
*/
public class WindowsFeatureDAOImpl implements MobileFeatureDAO {
private static final Log log = LogFactory.getLog(WindowsFeatureDAOImpl.class);
@Override
public boolean addFeature(MobileFeature mobileFeature) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
boolean status;
Connection conn;
try {
conn = WindowsDAOFactory.getConnection();
String sql = "INSERT INTO WIN_FEATURE(CODE, NAME, DESCRIPTION) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, mobileFeature.getCode());
stmt.setString(2, mobileFeature.getName());
stmt.setString(3, mobileFeature.getDescription());
stmt.executeUpdate();
status = true;
} catch (SQLException e) {
throw new WindowsFeatureManagementDAOException(
"Error occurred while adding windows feature '" +
mobileFeature.getName() + "' into the metadata repository", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean addFeatures(List<MobileFeature> mobileFeatures) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
boolean status = false;
Connection conn;
try {
conn = WindowsDAOFactory.getConnection();
stmt = conn.prepareStatement("INSERT INTO WIN_FEATURE(CODE, NAME, DESCRIPTION) VALUES (?, ?, ?)");
for (MobileFeature mobileFeature : mobileFeatures) {
stmt.setString(1, mobileFeature.getCode());
stmt.setString(2, mobileFeature.getName());
stmt.setString(3, mobileFeature.getDescription());
stmt.addBatch();
}
stmt.executeBatch();
status = true;
} catch (SQLException e) {
throw new WindowsFeatureManagementDAOException(
"Error occurred while adding windows features into the metadata repository", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean updateFeature(MobileFeature mobileFeature) throws MobileDeviceManagementDAOException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = WindowsDAOFactory.getConnection();
String updateDBQuery =
"UPDATE WIN_FEATURE SET NAME = ?, DESCRIPTION = ?" +
"WHERE CODE = ?";
stmt = conn.prepareStatement(updateDBQuery);
stmt.setString(1, mobileFeature.getName());
stmt.setString(2, mobileFeature.getDescription());
stmt.setString(3, mobileFeature.getCode());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Windows Feature " + mobileFeature.getCode() + " data has been " +
"modified.");
}
}
} catch (SQLException e) {
throw new WindowsFeatureManagementDAOException("Error occurred while updating the Windows Feature '" +
mobileFeature.getCode() + "' to the Windows db.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean deleteFeatureById(int mblFeatureId) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
boolean status = false;
Connection conn;
try {
conn = WindowsDAOFactory.getConnection();
String sql = "DELETE FROM WIN_FEATURE WHERE ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, mblFeatureId);
stmt.execute();
status = true;
} catch (SQLException e) {
throw new WindowsFeatureManagementDAOException(
"Error occurred while deleting windows feature '" +
mblFeatureId + "' from Windows database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean deleteFeatureByCode(String mblFeatureCode) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
boolean status = false;
Connection conn;
try {
conn = WindowsDAOFactory.getConnection();
String sql = "DELETE FROM WIN_FEATURE WHERE CODE = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, mblFeatureCode);
stmt.execute();
status = true;
} catch (SQLException e) {
throw new WindowsFeatureManagementDAOException(
"Error occurred while deleting windows feature '" +
mblFeatureCode + "' from Windows database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public MobileFeature getFeatureById(int mblFeatureId) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn;
try {
conn = WindowsDAOFactory.getConnection();
String sql = "SELECT ID, CODE, NAME, DESCRIPTION FROM WIN_FEATURE WHERE ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, mblFeatureId);
rs = stmt.executeQuery();
MobileFeature mobileFeature = null;
if (rs.next()) {
mobileFeature = new MobileFeature();
mobileFeature.setId(rs.getInt(WindowsPluginConstants.WINDOWS_FEATURE_ID));
mobileFeature.setCode(rs.getString(WindowsPluginConstants.WINDOWS_FEATURE_CODE));
mobileFeature.setName(rs.getString(WindowsPluginConstants.WINDOWS_FEATURE_NAME));
mobileFeature.setDescription(rs.getString(WindowsPluginConstants.WINDOWS_FEATURE_DESCRIPTION));
mobileFeature.setDeviceType(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
}
return mobileFeature;
} catch (SQLException e) {
throw new WindowsFeatureManagementDAOException(
"Error occurred while retrieving windows feature '" +
mblFeatureId + "' from the Windows database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public MobileFeature getFeatureByCode(String mblFeatureCode) throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn;
try {
conn = WindowsDAOFactory.getConnection();
String sql = "SELECT ID, CODE, NAME, DESCRIPTION FROM WIN_FEATURE WHERE CODE = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, mblFeatureCode);
rs = stmt.executeQuery();
MobileFeature mobileFeature = null;
if (rs.next()) {
mobileFeature = new MobileFeature();
mobileFeature.setId(rs.getInt(WindowsPluginConstants.WINDOWS_FEATURE_ID));
mobileFeature.setCode(rs.getString(WindowsPluginConstants.WINDOWS_FEATURE_CODE));
mobileFeature.setName(rs.getString(WindowsPluginConstants.WINDOWS_FEATURE_NAME));
mobileFeature.setDescription(rs.getString(WindowsPluginConstants.WINDOWS_FEATURE_DESCRIPTION));
mobileFeature.setDeviceType(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
}
return mobileFeature;
} catch (SQLException e) {
throw new WindowsFeatureManagementDAOException(
"Error occurred while retrieving windows feature '" +
mblFeatureCode + "' from the Windows database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public List<MobileFeature> getFeatureByDeviceType(String deviceType) throws MobileDeviceManagementDAOException {
return this.getAllFeatures();
}
@Override
public List<MobileFeature> getAllFeatures() throws MobileDeviceManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
Connection conn;
List<MobileFeature> features = new ArrayList<>();
try {
conn = WindowsDAOFactory.getConnection();
String sql = "SELECT ID, CODE, NAME, DESCRIPTION FROM WIN_FEATURE";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
MobileFeature mobileFeature;
while (rs.next()) {
mobileFeature = new MobileFeature();
mobileFeature.setId(rs.getInt(WindowsPluginConstants.WINDOWS_FEATURE_ID));
mobileFeature.setCode(rs.getString(WindowsPluginConstants.WINDOWS_FEATURE_CODE));
mobileFeature.setName(rs.getString(WindowsPluginConstants.WINDOWS_FEATURE_NAME));
mobileFeature.setDescription(rs.getString(WindowsPluginConstants.WINDOWS_FEATURE_DESCRIPTION));
mobileFeature.setDeviceType(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
features.add(mobileFeature);
}
return features;
} catch (SQLException e) {
throw new WindowsFeatureManagementDAOException("Error occurred while retrieving all " +
"windows features from the Windows database.", e);
} finally {
MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
}

View File

@ -1,48 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows.util;
/**
* Define constance used by Windows plugin.
*/
public class WindowsPluginConstants {
//properties related to database table WINDOWS_DEVICE
public static final String DEVICE_ID = "DEVICE_ID";
public static final String CHANNEL_URI = "CHANNEL_URI";
public static final String DEVICE_INFO = "DEVICE_INFO";
public static final String IMEI = "IMEI";
public static final String IMSI = "IMSI";
public static final String OS_VERSION = "OS_VERSION";
public static final String DEVICE_MODEL = "DEVICE_MODEL";
public static final String VENDOR = "VENDOR";
public static final String LATITUDE = "LATITUDE";
public static final String LONGITUDE = "LONGITUDE";
public static final String SERIAL = "SERIAL";
public static final String MAC_ADDRESS = "MAC_ADDRESS";
public static final String DEVICE_NAME = "DEVICE_NAME";
//Properties related to WIN_FEATURE table
public static final String WINDOWS_FEATURE_ID = "ID";
public static final String WINDOWS_FEATURE_CODE = "CODE";
public static final String WINDOWS_FEATURE_NAME = "NAME";
public static final String WINDOWS_FEATURE_DESCRIPTION = "DESCRIPTION";
}

View File

@ -1,58 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows.util;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.mobile.impl.windows.WindowsDeviceManagementService;
/**
* Contains utility method used by Windows plugin.
*/
public class WindowsPluginUtils {
public static License getDefaultLicense() {
License license = new License();
license.setName(WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS);
license.setLanguage("en_US");
license.setVersion("1.0.0");
license.setText("This End User License Agreement (\"Agreement\") is a legal agreement between you (\"You\") " +
"and WSO2, Inc., regarding the enrollment of Your personal mobile device (\"Device\") in SoR's " +
"mobile device management program, and the loading to and removal from Your Device and Your use " +
"of certain applications and any associated software and user documentation, whether provided in " +
"\"online\" or electronic format, used in connection with the operation of or provision of services " +
"to WSO2, Inc., BY SELECTING \"I ACCEPT\" DURING INSTALLATION, YOU ARE ENROLLING YOUR DEVICE, AND " +
"THEREBY AUTHORIZING SOR OR ITS AGENTS TO INSTALL, UPDATE AND REMOVE THE APPS FROM YOUR DEVICE AS " +
"DESCRIBED IN THIS AGREEMENT. YOU ARE ALSO EXPLICITLY ACKNOWLEDGING AND AGREEING THAT (1) THIS IS " +
"A BINDING CONTRACT AND (2) YOU HAVE READ AND AGREE TO THE TERMS OF THIS AGREEMENT.\n" +
"\n" +
"IF YOU DO NOT ACCEPT THESE TERMS, DO NOT ENROLL YOUR DEVICE AND DO NOT PROCEED ANY FURTHER.\n" +
"\n" +
"You agree that: (1) You understand and agree to be bound by the terms and conditions contained " +
"in this Agreement, and (2) You are at least 21 years old and have the legal capacity to enter " +
"into this Agreement as defined by the laws of Your jurisdiction. SoR shall have the right, " +
"without prior notice, to terminate or suspend (i) this Agreement, (ii) the enrollment of Your " +
"Device, or (iii) the functioning of the Apps in the event of a violation of this Agreement or " +
"the cessation of Your relationship with SoR (including termination of Your employment if You are " +
"an employee or expiration or termination of Your applicable franchise or supply agreement if You " +
"are a franchisee of or supplier to the WSO2 WSO2, Inc., system). SoR expressly reserves all " +
"rights not expressly granted herein.");
return license;
}
}

View File

@ -1,50 +0,0 @@
/*
* Copyright (c) 2015, 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.mobile.impl.windows.util;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.mobile.dto.MobileDevice;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Contains utility methods which are used by Windows plugin.
*/
public class WindowsUtils {
public static MobileDevice loadMobileDevices(ResultSet rs) throws SQLException {
MobileDevice mobileDevice = new MobileDevice();
mobileDevice.setMobileDeviceId(rs.getString(WindowsPluginConstants.DEVICE_ID));
mobileDevice.setImei(rs.getString(WindowsPluginConstants.IMEI));
mobileDevice.setImsi(rs.getString(WindowsPluginConstants.IMSI));
mobileDevice.setModel(rs.getString(WindowsPluginConstants.DEVICE_MODEL));
mobileDevice.setVendor(rs.getString(WindowsPluginConstants.VENDOR));
mobileDevice.setLatitude(rs.getString(WindowsPluginConstants.LATITUDE));
mobileDevice.setLongitude(rs.getString(WindowsPluginConstants.LONGITUDE));
mobileDevice.setSerial(rs.getString(WindowsPluginConstants.SERIAL));
mobileDevice.setOsVersion(rs.getString(WindowsPluginConstants.LATITUDE));
return mobileDevice;
}
public static Feature getMobileFeature() {
Feature feature = new Feature();
return feature;
}
}

View File

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.mobile.internal; package org.wso2.carbon.device.mgt.mobile.internal;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.mobile.impl.android.gcm.GCMService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
/** /**
@ -29,7 +28,6 @@ public class MobileDeviceManagementDataHolder {
private RegistryService registryService; private RegistryService registryService;
private DeviceManagementService androidDeviceManagementService; private DeviceManagementService androidDeviceManagementService;
private GCMService gcmService;
private static MobileDeviceManagementDataHolder thisInstance = new MobileDeviceManagementDataHolder(); private static MobileDeviceManagementDataHolder thisInstance = new MobileDeviceManagementDataHolder();
@ -57,11 +55,4 @@ public class MobileDeviceManagementDataHolder {
this.androidDeviceManagementService = androidDeviceManagementService; this.androidDeviceManagementService = androidDeviceManagementService;
} }
public GCMService getGCMService() {
return gcmService;
}
public void setGCMService(GCMService gcmService) {
this.gcmService = gcmService;
}
} }

View File

@ -23,20 +23,13 @@ import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration; import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.mobile.common.MobileDeviceMgtPluginException; import org.wso2.carbon.device.mgt.mobile.common.MobileDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.config.MobileDeviceConfigurationManager; import org.wso2.carbon.device.mgt.mobile.config.MobileDeviceConfigurationManager;
import org.wso2.carbon.device.mgt.mobile.config.MobileDeviceManagementConfig; import org.wso2.carbon.device.mgt.mobile.config.MobileDeviceManagementConfig;
import org.wso2.carbon.device.mgt.mobile.config.datasource.MobileDataSourceConfig; import org.wso2.carbon.device.mgt.mobile.config.datasource.MobileDataSourceConfig;
import org.wso2.carbon.device.mgt.mobile.dao.AbstractMobileDeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.mobile.dao.AbstractMobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.dao.util.MobileDeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.mobile.dao.util.MobileDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.mobile.impl.android.AndroidDeviceManagementService;
import org.wso2.carbon.device.mgt.mobile.impl.android.AndroidPolicyMonitoringService;
import org.wso2.carbon.device.mgt.mobile.impl.android.gcm.GCMService;
import org.wso2.carbon.device.mgt.mobile.impl.windows.WindowsDeviceManagementService;
import org.wso2.carbon.device.mgt.mobile.impl.windows.WindowsPolicyMonitoringService;
import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import java.util.Map; import java.util.Map;
@ -60,8 +53,6 @@ import java.util.Map;
*/ */
public class MobileDeviceManagementServiceComponent { public class MobileDeviceManagementServiceComponent {
private ServiceRegistration androidServiceRegRef;
private ServiceRegistration windowsServiceRegRef;
private ServiceRegistration gcmServiceRegRef; private ServiceRegistration gcmServiceRegRef;
private static final Log log = LogFactory.getLog(MobileDeviceManagementServiceComponent.class); private static final Log log = LogFactory.getLog(MobileDeviceManagementServiceComponent.class);
@ -100,30 +91,7 @@ public class MobileDeviceManagementServiceComponent {
log.error("Exception occurred while initializing mobile device management database schema", e); log.error("Exception occurred while initializing mobile device management database schema", e);
} }
} }
DeviceManagementService androidDeviceManagementService = new AndroidDeviceManagementService();
GCMService gcmService = new GCMService();
androidServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(),
androidDeviceManagementService, null);
windowsServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(),
new WindowsDeviceManagementService(), null);
gcmServiceRegRef =
bundleContext.registerService(GCMService.class.getName(), gcmService, null);
// Policy management service
bundleContext.registerService(PolicyMonitoringService.class,
new AndroidPolicyMonitoringService(), null);
bundleContext.registerService(PolicyMonitoringService.class,
new WindowsPolicyMonitoringService(), null);
MobileDeviceManagementDataHolder.getInstance().setAndroidDeviceManagementService(
androidDeviceManagementService);
MobileDeviceManagementDataHolder.getInstance().setGCMService(gcmService);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Mobile Device Management Service Component has been successfully activated"); log.debug("Mobile Device Management Service Component has been successfully activated");
} }
@ -137,12 +105,6 @@ public class MobileDeviceManagementServiceComponent {
log.debug("De-activating Mobile Device Management Service Component"); log.debug("De-activating Mobile Device Management Service Component");
} }
try { try {
if (androidServiceRegRef != null) {
androidServiceRegRef.unregister();
}
if (windowsServiceRegRef != null) {
windowsServiceRegRef.unregister();
}
if (gcmServiceRegRef != null) { if (gcmServiceRegRef != null) {
gcmServiceRegRef.unregister(); gcmServiceRegRef.unregister();
} }

View File

@ -3,7 +3,7 @@
~ ~
~ WSO2 Inc. licenses this file to you under the Apache License, ~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except ~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License. ~ in compliance with the License.a
~ You may obtain a copy of the License at ~ You may obtain a copy of the License at
~ ~
~ http://www.apache.org/licenses/LICENSE-2.0 ~ http://www.apache.org/licenses/LICENSE-2.0
@ -129,6 +129,12 @@
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-bindings-http</artifactId> <artifactId>cxf-rt-bindings-http</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.ws.security</groupId> <groupId>org.apache.ws.security</groupId>
@ -263,6 +269,12 @@
<groupId>org.wso2.carbon.identity</groupId> <groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth</artifactId> <artifactId>org.wso2.carbon.identity.oauth</artifactId>
<scope>provided</scope> <scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.cache</groupId> <groupId>javax.cache</groupId>
@ -306,7 +318,6 @@
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<scope>provided</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -27,7 +27,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
@ -165,7 +165,7 @@ public class WindowsAPIUtils {
getDeviceManagementService().updateOperation(deviceIdentifier, operation); getDeviceManagementService().updateOperation(deviceIdentifier, operation);
} }
public static TenantConfiguration getTenantConfiguration() throws DeviceManagementException { public static PlatformConfiguration getTenantConfiguration() throws DeviceManagementException {
return getDeviceManagementService().getConfiguration( return getDeviceManagementService().getConfiguration(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS); DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
} }

View File

@ -18,6 +18,7 @@
package org.wso2.carbon.mdm.mobileservices.windows.services.authbst; package org.wso2.carbon.mdm.mobileservices.windows.services.authbst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponses;
@ -33,6 +34,7 @@ import javax.ws.rs.core.Response;
/** /**
* Interface for handling authentication request comes via MDM login page. * Interface for handling authentication request comes via MDM login page.
*/ */
@Api(value = "BSTProvider", description = "Windows Device Management REST-API implementation.")
@Path("/bst") @Path("/bst")
public interface BSTProvider { public interface BSTProvider {

View File

@ -18,10 +18,11 @@
package org.wso2.carbon.mdm.mobileservices.windows.services.configurationmgtservice; package org.wso2.carbon.mdm.mobileservices.windows.services.configurationmgtservice;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponses;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WindowsConfigurationException; import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WindowsConfigurationException;
import org.wso2.carbon.mdm.mobileservices.windows.common.util.Message; import org.wso2.carbon.mdm.mobileservices.windows.common.util.Message;
@ -36,6 +37,7 @@ import javax.ws.rs.core.MediaType;
@WebService @WebService
@Produces({"application/json", "application/xml"}) @Produces({"application/json", "application/xml"})
@Consumes({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"})
@Api(value = "ConfigurationMgtService", description = "Windows Device Management REST-API implementation.")
public interface ConfigurationMgtService { public interface ConfigurationMgtService {
/** /**
@ -56,7 +58,7 @@ public interface ConfigurationMgtService {
@ApiResponse(code = 201, message = "Windows platform configuration saved successfully"), @ApiResponse(code = 201, message = "Windows platform configuration saved successfully"),
@ApiResponse(code = 500, message = "Internal Server Error") @ApiResponse(code = 500, message = "Internal Server Error")
}) })
Message ConfigureSettings(TenantConfiguration configuration) throws WindowsConfigurationException; Message ConfigureSettings(PlatformConfiguration configuration) throws WindowsConfigurationException;
/** /**
* Retrieve Tenant configurations according to the device type. * Retrieve Tenant configurations according to the device type.
@ -69,13 +71,13 @@ public interface ConfigurationMgtService {
httpMethod = "GET", httpMethod = "GET",
value = "Getting Windows Platform Configurations", value = "Getting Windows Platform Configurations",
notes = "Get the Windows platform configuration details using this REST API", notes = "Get the Windows platform configuration details using this REST API",
response = TenantConfiguration.class response = PlatformConfiguration.class
) )
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "Get Windows Configurations"), @ApiResponse(code = 200, message = "Get Windows Configurations"),
@ApiResponse(code = 500, message = "Server Error") @ApiResponse(code = 500, message = "Server Error")
}) })
TenantConfiguration getConfiguration() throws WindowsConfigurationException; PlatformConfiguration getConfiguration() throws WindowsConfigurationException;
/** /**
* Update Tenant Configurations for the specific Device type. * Update Tenant Configurations for the specific Device type.
@ -97,5 +99,5 @@ public interface ConfigurationMgtService {
@ApiResponse(code = 500, message = "Error occurred while modifying configuration settings of " + @ApiResponse(code = 500, message = "Error occurred while modifying configuration settings of " +
"windows platform") "windows platform")
}) })
Message updateConfiguration(TenantConfiguration configuration) throws WindowsConfigurationException; Message updateConfiguration(PlatformConfiguration configuration) throws WindowsConfigurationException;
} }

View File

@ -23,7 +23,8 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.mdm.mobileservices.windows.common.PluginConstants; import org.wso2.carbon.mdm.mobileservices.windows.common.PluginConstants;
import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WindowsConfigurationException; import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WindowsConfigurationException;
@ -54,7 +55,7 @@ public class ConfigurationMgtServiceImpl {
* @throws WindowsConfigurationException * @throws WindowsConfigurationException
*/ */
@POST @POST
public Message ConfigureSettings(TenantConfiguration configuration) throws WindowsConfigurationException { public Message ConfigureSettings(PlatformConfiguration configuration) throws WindowsConfigurationException {
Message responseMsg = new Message(); Message responseMsg = new Message();
ConfigurationEntry licenseEntry = null; ConfigurationEntry licenseEntry = null;
String message; String message;
@ -106,15 +107,15 @@ public class ConfigurationMgtServiceImpl {
* @throws WindowsConfigurationException * @throws WindowsConfigurationException
*/ */
@GET @GET
public TenantConfiguration getConfiguration() throws WindowsConfigurationException { public PlatformConfiguration getConfiguration() throws WindowsConfigurationException {
String msg; String msg;
TenantConfiguration tenantConfiguration = null; PlatformConfiguration PlatformConfiguration = null;
try { try {
if (WindowsAPIUtils.getDeviceManagementService(). if (WindowsAPIUtils.getDeviceManagementService().
getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS) != null) { getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS) != null) {
tenantConfiguration = WindowsAPIUtils.getDeviceManagementService(). PlatformConfiguration = WindowsAPIUtils.getDeviceManagementService().
getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS); getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
List<ConfigurationEntry> configs = tenantConfiguration.getConfiguration(); List<ConfigurationEntry> configs = PlatformConfiguration.getConfiguration();
ConfigurationEntry entry = new ConfigurationEntry(); ConfigurationEntry entry = new ConfigurationEntry();
License license = WindowsAPIUtils.getDeviceManagementService().getLicense( License license = WindowsAPIUtils.getDeviceManagementService().getLicense(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS, PluginConstants. DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS, PluginConstants.
@ -124,7 +125,7 @@ public class ConfigurationMgtServiceImpl {
entry.setName(PluginConstants.TenantConfigProperties.LICENSE_KEY); entry.setName(PluginConstants.TenantConfigProperties.LICENSE_KEY);
entry.setValue(license.getText()); entry.setValue(license.getText());
configs.add(entry); configs.add(entry);
tenantConfiguration.setConfiguration(configs); PlatformConfiguration.setConfiguration(configs);
} }
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
@ -132,7 +133,7 @@ public class ConfigurationMgtServiceImpl {
log.error(msg, e); log.error(msg, e);
throw new WindowsConfigurationException(msg, e); throw new WindowsConfigurationException(msg, e);
} }
return tenantConfiguration; return PlatformConfiguration;
} }
/** /**
@ -143,7 +144,7 @@ public class ConfigurationMgtServiceImpl {
* @throws WindowsConfigurationException * @throws WindowsConfigurationException
*/ */
@PUT @PUT
public Message updateConfiguration(TenantConfiguration configuration) throws WindowsConfigurationException { public Message updateConfiguration(PlatformConfiguration configuration) throws WindowsConfigurationException {
String message; String message;
Message responseMsg = new Message(); Message responseMsg = new Message();
ConfigurationEntry licenseEntry = null; ConfigurationEntry licenseEntry = null;

View File

@ -27,7 +27,6 @@ import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WindowsConfigurationException; import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WindowsConfigurationException;
import org.wso2.carbon.mdm.mobileservices.windows.common.util.Message; import org.wso2.carbon.mdm.mobileservices.windows.common.util.Message;
import javax.jws.WebService;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import java.util.List; import java.util.List;
@ -37,7 +36,6 @@ import java.util.List;
* All end points supports JSON, XMl with content negotiation. * All end points supports JSON, XMl with content negotiation.
*/ */
@Api(value = "DeviceManagementService", description = "Windows Device Management REST-API implementation.") @Api(value = "DeviceManagementService", description = "Windows Device Management REST-API implementation.")
@WebService
@Produces({"application/json", "application/xml"}) @Produces({"application/json", "application/xml"})
@Consumes({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"})
public interface DeviceManagementService { public interface DeviceManagementService {

View File

@ -18,6 +18,7 @@
package org.wso2.carbon.mdm.mobileservices.windows.services.discovery; package org.wso2.carbon.mdm.mobileservices.windows.services.discovery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponses;
@ -43,6 +44,7 @@ import javax.xml.ws.soap.SOAPBinding;
@WebService(targetNamespace = PluginConstants.DISCOVERY_SERVICE_TARGET_NAMESPACE, @WebService(targetNamespace = PluginConstants.DISCOVERY_SERVICE_TARGET_NAMESPACE,
name = "IDiscoveryService") name = "IDiscoveryService")
@BindingType(value = SOAPBinding.SOAP12HTTP_BINDING) @BindingType(value = SOAPBinding.SOAP12HTTP_BINDING)
@Api(value = "DiscoveryService", description = "Windows Device Management REST-API implementation.")
public interface DiscoveryService { public interface DiscoveryService {
@POST @POST

View File

@ -22,18 +22,15 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponses;
import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WindowsConfigurationException; import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WindowsConfigurationException;
import org.wso2.carbon.mdm.mobileservices.windows.common.util.Message; import org.wso2.carbon.mdm.mobileservices.windows.common.util.Message;
import javax.jws.WebService;
import javax.ws.rs.*; import javax.ws.rs.*;
/** /**
* Endpoint for Enforce Effective Policy. * Endpoint for Enforce Effective Policy.
*/ */
@Api(value = "PolicyMgtService", description = "Windows Device Management REST-API implementation.") @Api(value = "PolicyMgtService", description = "Windows Device Management REST-API implementation.")
@WebService
@Produces({"application/json", "application/xml"}) @Produces({"application/json", "application/xml"})
@Consumes({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"})
public interface PolicyMgtService { public interface PolicyMgtService {

View File

@ -32,7 +32,7 @@ import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.mdm.mobileservices.windows.common.PluginConstants; import org.wso2.carbon.mdm.mobileservices.windows.common.PluginConstants;
import org.wso2.carbon.mdm.mobileservices.windows.common.beans.CacheEntry; import org.wso2.carbon.mdm.mobileservices.windows.common.beans.CacheEntry;
import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.CertificateGenerationException; import org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.CertificateGenerationException;
@ -372,7 +372,7 @@ public class CertificateEnrollmentServiceImpl implements CertificateEnrollmentSe
*/ */
private List<ConfigurationEntry> getTenantConfigurationData() throws DeviceManagementException { private List<ConfigurationEntry> getTenantConfigurationData() throws DeviceManagementException {
if (WindowsAPIUtils.getTenantConfiguration() != null) { if (WindowsAPIUtils.getTenantConfiguration() != null) {
TenantConfiguration configuration = WindowsAPIUtils.getTenantConfiguration(); PlatformConfiguration configuration = WindowsAPIUtils.getTenantConfiguration();
return configuration.getConfiguration(); return configuration.getConfiguration();
} else { } else {
return null; return null;

Some files were not shown because too many files have changed in this diff Show More