Impproving the DAO layer, DeviceManagerService SPIs and implmenting initial bits of plugin management

revert-dabc3590
prabathabey 10 years ago
parent 33812ec50f
commit 19256e2638

@ -22,6 +22,8 @@ public class Device {
private int id; private int id;
private String type;
private String description; private String description;
private String name; private String name;
@ -130,4 +132,12 @@ public class Device {
this.features = features; this.features = features;
} }
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
} }

@ -80,10 +80,11 @@ public interface DeviceManagerService {
* Method to set the status indicating whether a particular device registered within CDM is enabled at a given * Method to set the status indicating whether a particular device registered within CDM is enabled at a given
* moment. * moment.
* *
* @param deviceId Fully qualified device identifier
* @param status Indicates whether the device is active * @param status Indicates whether the device is active
* @throws DeviceManagementException If some unusual behaviour is observed while enrolling a device * @throws DeviceManagementException If some unusual behaviour is observed while enrolling a device
*/ */
void setActive(boolean status) throws DeviceManagementException; void setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException;
/** /**
* Method to retrieve metadata of all devices registered within CDM corresponding to a particular device type. * Method to retrieve metadata of all devices registered within CDM corresponding to a particular device type.

@ -80,10 +80,6 @@
<groupId>org.eclipse.equinox</groupId> <groupId>org.eclipse.equinox</groupId>
<artifactId>org.eclipse.equinox.common</artifactId> <artifactId>org.eclipse.equinox.common</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId> <artifactId>org.wso2.carbon.device.mgt.common</artifactId>
@ -95,29 +91,26 @@
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId> <artifactId>org.wso2.carbon.utils</artifactId>
<version>${carbon.platform.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId> <artifactId>org.wso2.carbon.ndatasource.core</artifactId>
<version>${carbon.platform.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.rdbms</artifactId> <artifactId>org.wso2.carbon.ndatasource.rdbms</artifactId>
<version>${carbon.platform.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.transaction.manager</artifactId> <artifactId>org.wso2.carbon.transaction.manager</artifactId>
<version>${carbon.platform.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.jboss.spec.javax.transaction</groupId> <groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.1_spec</artifactId> <artifactId>jboss-transaction-api_1.1_spec</artifactId>
<version>${jboss-transaction-api.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.testng</groupId> <groupId>org.testng</groupId>

@ -15,8 +15,20 @@
*/ */
package org.wso2.carbon.device.mgt.core; package org.wso2.carbon.device.mgt.core;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagerService;
import java.util.Map;
public class DeviceManagementRepository { public class DeviceManagementRepository {
private Map<String, DeviceManagerService> providers;
public void addDeviceManagementProvider(DeviceManagerService provider) {
providers.put(provider.getProviderType(), provider);
}
public DeviceManagerService getDeviceManagementProvider(String type) {
return providers.get(type);
}
} }

@ -15,14 +15,11 @@
package org.wso2.carbon.device.mgt.core.config; package org.wso2.carbon.device.mgt.core.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
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.core.dao.exception.DeviceMgtDAOFactory; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.DeviceMgtDbCreator;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import javax.sql.DataSource; import javax.sql.DataSource;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
@ -34,16 +31,12 @@ import java.io.File;
*/ */
public class DeviceConfigurationManager { public class DeviceConfigurationManager {
private DeviceMgtConfig currentDeviceConfig; private DeviceManagementConfig currentDeviceConfig;
private static DeviceConfigurationManager deviceConfigManager; private static DeviceConfigurationManager deviceConfigManager;
private static final Log log = LogFactory.getLog(DeviceConfigurationManager.class);
private final String deviceMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + private final String deviceMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath() + File.separator +
DeviceManagementConstants.DataSourceProperties.DEVICE_CONFIG_XML_NAME; DeviceManagementConstants.DataSourceProperties.DEVICE_CONFIG_XML_NAME;
private final String cdmSetupSql = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator +
"conf" + File.separator + "dbscripts";
public static DeviceConfigurationManager getInstance() { public static DeviceConfigurationManager getInstance() {
if (deviceConfigManager == null) { if (deviceConfigManager == null) {
synchronized (DeviceConfigurationManager.class) { synchronized (DeviceConfigurationManager.class) {
@ -55,33 +48,26 @@ public class DeviceConfigurationManager {
return deviceConfigManager; return deviceConfigManager;
} }
public synchronized void initConfig() throws DeviceManagementException { public synchronized void initConfig() throws DeviceManagementException {
try { try {
File deviceMgtConfig = new File(deviceMgtConfigXMLPath); File deviceMgtConfig = new File(deviceMgtConfigXMLPath);
Document doc = DeviceManagerUtil.convertToDocument(deviceMgtConfig); Document doc = DeviceManagerUtil.convertToDocument(deviceMgtConfig);
/* Document doc = DeviceManagerUtil.convertToDocument(deviceMgtConfig);
//rss-config supports secure vault as it needs to be resolve when parsing
DeviceManagerUtil.secureResolveDocument(doc);*/
/* Un-marshaling RSS configuration */
JAXBContext rssContext = JAXBContext.newInstance(DeviceMgtConfig.class);
Unmarshaller unmarshaller = rssContext.createUnmarshaller();
this.currentDeviceConfig = (DeviceMgtConfig) unmarshaller.unmarshal(doc);
//set jndi data source name for future use
DeviceManagerUtil.setJndiDataSourceName(currentDeviceConfig.getDeviceMgtRepository().getDataSourceConfig().
getJndiLookupDefintion().getJndiName());
DataSource dataSource = DeviceMgtDAOFactory.resolveDataSource(this.currentDeviceConfig.getDeviceMgtRepository()
.getDataSourceConfig());
DeviceManagerUtil.setDataSource(dataSource);
/* Un-marshaling Device Management configuration */
JAXBContext rssContext = JAXBContext.newInstance(DeviceManagementConfig.class);
Unmarshaller unmarshaller = rssContext.createUnmarshaller();
this.currentDeviceConfig = (DeviceManagementConfig) unmarshaller.unmarshal(doc);
} catch (Exception e) { } catch (Exception e) {
throw new DeviceManagementException("Error occurred while initializing RSS config", e); throw new DeviceManagementException("Error occurred while initializing RSS config", e);
} }
} }
public DeviceManagementConfig getDeviceManagementConfig() {
public DeviceMgtConfig getCurrentDeviceConfig() {
return currentDeviceConfig; return currentDeviceConfig;
} }
public DataSourceConfig getDataSourceConfig() {
return currentDeviceConfig.getDeviceMgtRepository().getDataSourceConfig();
}
} }

@ -21,7 +21,7 @@ import javax.xml.bind.annotation.XmlRootElement;
* Represents Device Mgt configuration. * Represents Device Mgt configuration.
*/ */
@XmlRootElement(name = "DeviceMgtConfiguration") @XmlRootElement(name = "DeviceMgtConfiguration")
public final class DeviceMgtConfig { public final class DeviceManagementConfig {
private String deviceMgtProvider; private String deviceMgtProvider;

@ -37,4 +37,5 @@ public class DeviceManagementRepository {
public void setDataSourceConfig(DataSourceConfig dataSourceConfig) { public void setDataSourceConfig(DataSourceConfig dataSourceConfig) {
this.dataSourceConfig = dataSourceConfig; this.dataSourceConfig = dataSourceConfig;
} }
} }

@ -15,16 +15,21 @@
package org.wso2.carbon.device.mgt.core.dao; package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceDAOUtil; import org.wso2.carbon.device.mgt.core.dto.Device;
import org.wso2.carbon.device.mgt.core.dto.Status;
import javax.sql.DataSource; import java.util.List;
public class DeviceDAO { public interface DeviceDAO {
private DataSource dataSource; void addDevice(Device device) throws DeviceManagementDAOException;
public DeviceDAO(DataSource dataSource) { void updateDevice(Device device) throws DeviceManagementDAOException;
this.dataSource = dataSource;
} void updateDeviceStatus(Long deviceId, Status status) throws DeviceManagementDAOException;
void deleteDevice(Long deviceId) throws DeviceManagementDAOException;
List<Device> getDeviceByDeviceId(Long deviceId) throws DeviceManagementDAOException;
} }

@ -16,12 +16,12 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.core.dao.exception; package org.wso2.carbon.device.mgt.core.dao;
/** /**
* Custom exception class for data access related exceptions * Custom exception class for data access related exceptions
*/ */
public class DeviceDAOException extends Exception { public class DeviceManagementDAOException extends Exception {
private String message; private String message;
private static final long serialVersionUID = 2021891706072918864L; private static final long serialVersionUID = 2021891706072918864L;
@ -32,7 +32,7 @@ public class DeviceDAOException extends Exception {
* @param message error message * @param message error message
* @param nestedException exception * @param nestedException exception
*/ */
public DeviceDAOException(String message, Exception nestedException) { public DeviceManagementDAOException(String message, Exception nestedException) {
super(message, nestedException); super(message, nestedException);
setErrorMessage(message); setErrorMessage(message);
} }
@ -43,7 +43,7 @@ public class DeviceDAOException extends Exception {
* @param message the detail message. * @param message the detail message.
* @param cause the cause of this exception. * @param cause the cause of this exception.
*/ */
public DeviceDAOException(String message, Throwable cause) { public DeviceManagementDAOException(String message, Throwable cause) {
super(message, cause); super(message, cause);
setErrorMessage(message); setErrorMessage(message);
} }
@ -53,7 +53,7 @@ public class DeviceDAOException extends Exception {
* *
* @param message the detail message. * @param message the detail message.
*/ */
public DeviceDAOException(String message) { public DeviceManagementDAOException(String message) {
super(message); super(message);
setErrorMessage(message); setErrorMessage(message);
} }
@ -63,7 +63,7 @@ public class DeviceDAOException extends Exception {
* *
* @param cause the cause of this exception. * @param cause the cause of this exception.
*/ */
public DeviceDAOException(Throwable cause) { public DeviceManagementDAOException(Throwable cause) {
super(cause); super(cause);
} }

@ -0,0 +1,81 @@
/**
* Copyright (c) 2014, 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.device.mgt.core.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.device.mgt.core.dao.impl.DeviceDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.DeviceTypeDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import javax.sql.DataSource;
import java.util.Hashtable;
import java.util.List;
public class DeviceManagementDAOFactory {
private static DataSource dataSource;
private static final Log log = LogFactory.getLog(DeviceManagementDAOFactory.class);
public static DeviceDAO getDeviceDAO() {
return new DeviceDAOImpl(dataSource);
}
public static DeviceTypeDAO getDeviceTypeDAO() {
return new DeviceTypeDAOImpl(dataSource);
}
public static void init(DataSourceConfig config) {
dataSource = resolveDataSource(config);
}
/**
* Resolve data source from the data source definition
*
* @param config data source configuration
* @return data source resolved from the data source definition
*/
public static DataSource resolveDataSource(DataSourceConfig config) {
DataSource dataSource = null;
if (config == null) {
throw new RuntimeException("Device Management Repository data source configuration " +
"is null and thus, is not initialized");
}
JNDILookupDefinition jndiConfig = config.getJndiLookupDefintion();
if (jndiConfig != null) {
if (log.isDebugEnabled()) {
log.debug("Initializing Device Management Repository data source using the JNDI " +
"Lookup Definition");
}
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue());
}
dataSource =
DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties);
} else {
dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null);
}
}
return dataSource;
}
}

@ -1,41 +0,0 @@
/*
* Copyright (c) 2014, 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.core.dao;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dao.exception.DeviceDAOException;
import org.wso2.carbon.device.mgt.core.dao.exception.DeviceDatabaseConnectionException;
import org.wso2.carbon.device.mgt.core.dto.Device;
import org.wso2.carbon.device.mgt.core.dto.Status;
import java.util.List;
public interface DeviceMgtDAO {
void addDevice(Device device) throws DeviceDAOException, DeviceManagementException;
void updateDevice(Device device) throws DeviceDAOException, DeviceManagementException;
void updateDeviceStatus(Long deviceId, Status status) throws DeviceDAOException, DeviceManagementException;
void deleteDevice(Long deviceId) throws DeviceDAOException, DeviceManagementException;
List<Device> getDeviceByDeviceId(Long deviceId) throws DeviceDAOException, DeviceManagementException;
}

@ -18,17 +18,16 @@
package org.wso2.carbon.device.mgt.core.dao; package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.core.dao.exception.DeviceDAOException;
import org.wso2.carbon.device.mgt.core.dao.exception.DeviceDatabaseConnectionException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import java.util.List; import java.util.List;
public interface DeviceTypeMgtDAO { public interface DeviceTypeDAO {
void addDeviceType(DeviceType deviceType) throws DeviceDAOException, DeviceDatabaseConnectionException; void addDeviceType(DeviceType deviceType) throws DeviceManagementDAOException;
void updateDeviceType(DeviceType deviceType) throws DeviceDAOException, DeviceDatabaseConnectionException; void updateDeviceType(DeviceType deviceType) throws DeviceManagementDAOException;
List<DeviceType> getDeviceTypes() throws DeviceManagementDAOException;
List<DeviceType> getDeviceTypes() throws DeviceDAOException, DeviceDatabaseConnectionException;
} }

@ -1,72 +0,0 @@
/*
* Copyright (c) 2014, 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.core.dao.exception;
public class DeviceDatabaseConnectionException extends Exception {
private String message;
/**
* Constructs a new exception with the specified detail message and nested exception.
*
* @param message error message
* @param nestedException exception
*/
public DeviceDatabaseConnectionException(String message, Exception nestedException) {
super(message, nestedException);
setErrorMessage(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message the detail message.
* @param cause the cause of this exception.
*/
public DeviceDatabaseConnectionException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
/**
* Constructs a new exception with the specified detail message
*
* @param message the detail message.
*/
public DeviceDatabaseConnectionException(String message) {
super(message);
setErrorMessage(message);
}
/**
* Constructs a new exception with the specified and cause.
*
* @param cause the cause of this exception.
*/
public DeviceDatabaseConnectionException(Throwable cause) {
super(cause);
}
public String getMessage() {
return message;
}
public void setErrorMessage(String errorMessage) {
this.message = errorMessage;
}
}

@ -1,85 +0,0 @@
/*
* Copyright (c) 2014, 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.
* 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.core.dao.exception;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.device.mgt.core.config.datasource.RDBMSConfig;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import javax.sql.DataSource;
import java.util.Hashtable;
import java.util.List;
/**
* DAO factory class for creating RSS DAO objects.
*/
public class DeviceMgtDAOFactory {
private static final Log log = LogFactory.getLog(DeviceMgtDAOFactory.class);
/**
* Resolve data source from the data source definition
*
* @param dataSourceDef data source configuration
* @return data source resolved from the data source definition
*/
public static DataSource resolveDataSource(DataSourceConfig dataSourceDef) {
DataSource dataSource;
if (dataSourceDef == null) {
throw new RuntimeException("RSS Management Repository data source configuration " +
"is null and thus, is not initialized");
}
JNDILookupDefinition jndiConfig = dataSourceDef.getJndiLookupDefintion();
if (jndiConfig != null) {
if (log.isDebugEnabled()) {
log.debug("Initializing RSS Management Repository data source using the JNDI " +
"Lookup Definition");
}
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue());
}
dataSource =
DeviceManagerUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties);
} else {
dataSource = DeviceManagerUtil.lookupDataSource(jndiConfig.getJndiName(), null);
}
} else {
if (log.isDebugEnabled()) {
log.debug("No JNDI Lookup Definition found in the RSS Management Repository " +
"data source configuration. Thus, continuing with in-line data source " +
"configuration processing.");
}
RDBMSConfig rdbmsConfig = dataSourceDef.getRdbmsConfiguration();
if (rdbmsConfig == null) {
throw new RuntimeException(
"No JNDI/In-line data source configuration found. " +
"Thus, RSS Management Repository DAO is not initialized"
);
}
dataSource =
DeviceManagerUtil.createDataSource(DeviceManagerUtil.loadDataSourceProperties(
rdbmsConfig), rdbmsConfig.getDataSourceClassName());
}
return dataSource;
}
}

@ -0,0 +1,108 @@
/*
* Copyright (c) 2014, 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.core.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dto.Device;
import org.wso2.carbon.device.mgt.core.dto.Status;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
public class DeviceDAOImpl implements DeviceDAO {
private DataSource dataSource;
private static final Log log = LogFactory.getLog(DeviceDAOImpl.class);
public DeviceDAOImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void addDevice(Device device) throws DeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = this.getConnection();
String createDBQuery =
"INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNERSHIP," +
"STATUS, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, OWNER, TENANT_ID) VALUES " +
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, device.getDescription());
stmt.setString(2, device.getName());
stmt.setLong(3, new Date().getTime());
stmt.setLong(4, new Date().getTime());
stmt.setString(5, device.getOwnerShip());
stmt.setString(6, device.getStatus().toString());
stmt.setLong(7, device.getDeviceType().getId());
stmt.setLong(8, device.getDeviceIdentificationId());
stmt.setString(9, device.getOwnerId());
stmt.setInt(10, DeviceManagementDAOUtil.getTenantId());
stmt.executeUpdate();
} catch (SQLException e) {
String msg = "Failed to enroll device '" + device.getName() + "'";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
}
}
@Override
public void updateDevice(Device device) throws DeviceManagementDAOException {
}
@Override
public void updateDeviceStatus(Long deviceId, Status status) throws DeviceManagementDAOException {
}
@Override
public void deleteDevice(Long deviceId) throws DeviceManagementDAOException {
}
@Override
public List<Device> getDeviceByDeviceId(Long deviceId)
throws DeviceManagementDAOException {
return null;
}
private Connection getConnection() throws DeviceManagementDAOException {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while obtaining a connection from the device " +
"management metadata repository datasource", e);
}
}
}

@ -1,116 +0,0 @@
/*
* Copyright (c) 2014, 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.core.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.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceMgtDAO;
import org.wso2.carbon.device.mgt.core.dao.exception.DeviceDAOException;
import org.wso2.carbon.device.mgt.core.dao.exception.DeviceDatabaseConnectionException;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceDAOUtil;
import org.wso2.carbon.device.mgt.core.dao.util.ErrorHandler;
import org.wso2.carbon.device.mgt.core.dto.Device;
import org.wso2.carbon.device.mgt.core.dto.Status;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
public class DeviceMgtDAOImpl implements DeviceMgtDAO {
private static final Log log = LogFactory.getLog(DeviceMgtDAOImpl.class);
private DataSource dataSource;
public DeviceMgtDAOImpl() {
this.dataSource = DeviceManagerUtil.getDataSource();
}
@Override
public void addDevice(Device device) throws DeviceDAOException, DeviceManagementException {
Connection conn = null;
PreparedStatement addDeviceDBStatement = null;
try {
conn = getDataSourceConnection();
conn.setAutoCommit(false);
String createDBQuery =
"INSERT INTO DM_DEVICE(DESCRIPTION,NAME,DATE_OF_ENROLLMENT,DATE_OF_LAST_UPDATE,OWNERSHIP," +
"STATUS,DEVICE_TYPE_ID,DEVICE_IDENTIFICATION,OWNER) VALUES (?,?,?,?,?,?,?,?,?)";
addDeviceDBStatement = conn.prepareStatement(createDBQuery);
addDeviceDBStatement.setString(1, device.getDescription());
addDeviceDBStatement.setString(2, device.getName());
addDeviceDBStatement.setLong(3, new Date().getTime());
addDeviceDBStatement.setLong(4, new Date().getTime());
addDeviceDBStatement.setString(5, device.getOwnerShip());
addDeviceDBStatement.setString(6, device.getStatus().toString());
addDeviceDBStatement.setLong(7, device.getDeviceType().getId());
addDeviceDBStatement.setLong(8, device.getDeviceIdentificationId());
addDeviceDBStatement.setString(9, device.getOwnerId());
addDeviceDBStatement.executeUpdate();
conn.commit();
} catch (SQLException e) {
DeviceDAOUtil.rollback(conn, DeviceManagementConstants.ADD_DEVICE_ENTRY);
String msg = "Failed to enroll device " + device.getName() + " to CDM";
ErrorHandler errorHandler = new ErrorHandler(msg, log);
errorHandler.handleDAOException(msg, e);
} finally {
DeviceDAOUtil.cleanupResources(null, addDeviceDBStatement, conn, DeviceManagementConstants.ADD_DEVICE_ENTRY);
}
}
@Override
public void updateDevice(Device device) throws DeviceDAOException, DeviceManagementException {
}
@Override
public void updateDeviceStatus(Long deviceId, Status status)
throws DeviceDAOException, DeviceManagementException {
}
@Override
public void deleteDevice(Long deviceId) throws DeviceDAOException, DeviceManagementException {
}
@Override
public List<Device> getDeviceByDeviceId(Long deviceId)
throws DeviceDAOException, DeviceManagementException {
return null;
}
private Connection getDataSourceConnection() throws DeviceManagementException {
try {
return dataSource.getConnection();
} catch (SQLException e) {
String msg = "Error while acquiring the database connection";
throw new DeviceManagementException(msg, e);
}
}
}

@ -0,0 +1,72 @@
/**
* Copyright (c) 2014, 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.device.mgt.core.dao.impl;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
public class DeviceTypeDAOImpl implements DeviceTypeDAO {
private DataSource dataSource;
public DeviceTypeDAOImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void addDeviceType(DeviceType deviceType) throws DeviceManagementDAOException {
Connection conn = this.getConnection();
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_TYPE (NAME) VALUES (?)");
stmt.setString(1, deviceType.getName());
stmt.execute();
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while registering the device type '" +
deviceType.getName() + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
}
}
@Override
public void updateDeviceType(DeviceType deviceType) throws DeviceManagementDAOException {
}
@Override
public List<DeviceType> getDeviceTypes() throws DeviceManagementDAOException {
return null;
}
private Connection getConnection() throws DeviceManagementDAOException {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while obtaining a connection from the device " +
"management metadata repository datasource", e);
}
}
}

@ -1,121 +0,0 @@
/*
* Copyright (c) 2013, 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.core.dao.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagerDataHolder;
import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Util class for RSS DAO operations
*/
public class DeviceDAOUtil {
private static final Log log = LogFactory.getLog(DeviceDAOUtil.class);
/**
* Clean up database resources
* @param resultSet result set to be closed
* @param statement prepared statement to be closed
* @param conn connection to be closed
* @param task occurred when clean up the resources
*/
public static synchronized void cleanupResources(ResultSet resultSet, PreparedStatement statement,
Connection conn, String task) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
log.error("Error occurred while closing the result set " + task, e);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
log.error("Error occurred while closing the statement " + task, e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.error("Error occurred while closing the connection "+ task, e);
}
}
}
/**
* Roll back database updates on error
*
* @param connection database connection
* @param task task which was executing at the error.
*/
public static synchronized void rollback(Connection connection, String task) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException e) {
log.error("Rollback failed on " + task, e);
}
}
}
public synchronized static int getTenantId() throws DeviceManagementException {
CarbonContext ctx = CarbonContext.getThreadLocalCarbonContext();
int tenantId = ctx.getTenantId();
if (tenantId != MultitenantConstants.INVALID_TENANT_ID) {
return tenantId;
}
String tenantDomain = ctx.getTenantDomain();
if (null != tenantDomain) {
try {
TenantManager tenantManager = DeviceManagerDataHolder.getInstance().getTenantManager();
tenantId = tenantManager.getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new DeviceManagementException("Error while retrieving the tenant Id for " +
"tenant domain : " + tenantDomain, e);
}
}
return tenantId;
}
public static synchronized int getTenantId(String tenantDomain) throws DeviceManagementException {
int tenantId = MultitenantConstants.INVALID_TENANT_ID;
if (null != tenantDomain) {
try {
TenantManager tenantManager = DeviceManagerDataHolder.getInstance().getTenantManager();
tenantId = tenantManager.getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new DeviceManagementException("Error while retrieving the tenant Id for " +
"tenant domain : " + tenantDomain, e);
}
}
return tenantId;
}
}

@ -0,0 +1,102 @@
/**
* Copyright (c) 2012, 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.device.mgt.core.dao.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
public final class DeviceManagementDAOUtil {
private static final Log log = LogFactory.getLog(DeviceManagementDAOUtil.class);
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
/**
* Get id of the current tenant
* @return tenant id
* @throws DeviceManagementDAOException if an error is observed when getting tenant id
*/
public static int getTenantId() throws DeviceManagementDAOException {
CarbonContext context = CarbonContext.getThreadLocalCarbonContext();
int tenantId = context.getTenantId();
if (tenantId != MultitenantConstants.INVALID_TENANT_ID) {
return tenantId;
}
String tenantDomain = context.getTenantDomain();
if (tenantDomain == null) {
String msg = "Tenant domain is not properly set and thus, is null";
throw new DeviceManagementDAOException(msg);
}
TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager();
try {
tenantId = tenantManager.getTenantId(tenantDomain);
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving id from the domain of tenant " +
tenantDomain;
throw new DeviceManagementDAOException(msg);
}
return tenantId;
}
public static DataSource lookupDataSource(String dataSourceName, final Hashtable<Object, Object> jndiProperties) {
try {
if (jndiProperties == null || jndiProperties.isEmpty()) {
return (DataSource) InitialContext.doLookup(dataSourceName);
}
final InitialContext context = new InitialContext(jndiProperties);
return (DataSource) context.doLookup(dataSourceName);
} catch (Exception e) {
throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e);
}
}
}

@ -1,38 +0,0 @@
/*
* Copyright (c) 2014, 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.
* 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.core.dao.util;
import org.apache.commons.logging.Log;
import org.wso2.carbon.device.mgt.core.dao.exception.DeviceDAOException;
import java.sql.SQLException;
public class ErrorHandler {
private String errorMsg = "";
private Log log;
public ErrorHandler(String msg, Log log) {
errorMsg = msg;
this.log = log;
}
public void handleDAOException(String msg, SQLException e) throws DeviceDAOException {
log.error(msg, e);
throw new DeviceDAOException(msg, e);
}
}

@ -0,0 +1,67 @@
/*
* Copyright (c) 2014, 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.core.internal;
import org.wso2.carbon.device.mgt.core.DeviceManagementRepository;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;
public class DeviceManagementDataHolder {
private RealmService realmService;
private TenantManager tenantManager;
private DeviceManagementRepository repository;
private static DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder();
private DeviceManagementDataHolder() {}
public static DeviceManagementDataHolder getInstance() {
return thisInstance;
}
public RealmService getRealmService() {
return realmService;
}
public void setRealmService(RealmService realmService) {
this.realmService = realmService;
this.setTenantManager(realmService);
}
private void setTenantManager(RealmService realmService) {
if (realmService == null) {
throw new IllegalStateException("Realm service is not initialized properly");
}
this.tenantManager = realmService.getTenantManager();
}
public TenantManager getTenantManager() {
return tenantManager;
}
public DeviceManagementRepository getDeviceManagementRepository() {
return repository;
}
public void setDeviceManagementRepository(DeviceManagementRepository repository) {
this.repository = repository;
}
}

@ -0,0 +1,133 @@
/**
* Copyright (c) 2014, 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.device.mgt.core.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagerService;
import org.wso2.carbon.device.mgt.core.DeviceManagementRepository;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer;
import org.wso2.carbon.user.core.service.RealmService;
/**
* @scr.component name="org.wso2.carbon.device.manager" immediate="true"
* @scr.reference name="user.realmservice.default"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRealmService"
* unbind="unsetRealmService"
* @scr.reference name="device.manager.service"
* interface="org.wso2.carbon.device.mgt.common.spi.DeviceManagerService"
* cardinality="1..n"
* policy="dynamic"
* bind="setDeviceManagerService"
* unbind="unsetDeviceManagerService"
*/
public class DeviceManagementServiceComponent {
private static Log log = LogFactory.getLog(DeviceManagementServiceComponent.class);
protected void activate(ComponentContext componentContext) {
try {
/* Initializing Device Management Configuration */
DeviceConfigurationManager.getInstance().initConfig();
DataSourceConfig config = DeviceConfigurationManager.getInstance().getDataSourceConfig();
DeviceManagementDAOFactory.init(config);
DeviceManagementDataHolder.getInstance().setDeviceManagementRepository(new DeviceManagementRepository());
String setupOption = System.getProperty("setup");
/* If -Dsetup option specified then create device management database schema */
if (setupOption != null) {
setupDeviceManagementSchema(config);
}
BundleContext bundleContext = componentContext.getBundleContext();
bundleContext.registerService(DeviceManagementService.class.getName(),
new DeviceManagementService(), null);
} catch (Throwable e) {
String msg = "Error occurred while initializing device management core bundle";
log.error(msg, e);
}
}
private void setupDeviceManagementSchema(DataSourceConfig config) throws DeviceManagementException {
log.info("Setup option specified");
DeviceManagementSchemaInitializer initializer = new DeviceManagementSchemaInitializer(config);
log.info("Creating Meta Data tables");
try {
initializer.createRegistryDatabase();
} catch (Exception e) {
throw new DeviceManagementException("Error occurred while initializing Device Management " +
"database schema", e);
}
}
/**
* Sets Device Manager services
* @param deviceManager An instance of DeviceManagerService
*/
protected void setDeviceManagerService(DeviceManagerService deviceManager) {
if (log.isDebugEnabled()) {
log.debug("Setting Device Management Service");
}
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
addDeviceManagementProvider(deviceManager);
}
/**
* Unsets Device Management services
* @param deviceManager An instance of DeviceManagerService
*/
protected void unsetDeviceManagerService(DeviceManagerService deviceManager) {
if (log.isDebugEnabled()) {
log.debug("Unsetting Device Management Service");
}
}
/**
* Sets Realm Service
* @param realmService An instance of RealmService
*/
protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Setting Realm Service");
}
DeviceManagementDataHolder.getInstance().setRealmService(realmService);
}
/**
* Unsets Realm Service
* @param realmService An instance of RealmService
*/
protected void unsetRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.debug("Unsetting Realm Service");
}
DeviceManagementDataHolder.getInstance().setRealmService(null);
}
}

@ -1,126 +0,0 @@
/*
* Copyright (c) 2014, 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.core.internal;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.securevault.SecretCallbackHandlerService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.transaction.TransactionManager;
public class DeviceManagerDataHolder {
private DataSourceService dataSourceService;
private RealmService realmService;
private TransactionManager transactionManager;
private SecretCallbackHandlerService secretCallbackHandlerService;
private TenantManager tenantManager;
private static DeviceManagerDataHolder thisInstance = new DeviceManagerDataHolder();
private DeviceManagerDataHolder() {
}
public static DeviceManagerDataHolder getInstance() {
return thisInstance;
}
public DataSourceService getDataSourceService() {
return dataSourceService;
}
public void setDataSourceService(DataSourceService dataSourceService) {
this.dataSourceService = dataSourceService;
}
public RealmService getRealmService() {
return realmService;
}
public void setRealmService(RealmService realmService) {
this.realmService = realmService;
}
public TransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public SecretCallbackHandlerService getSecretCallbackHandlerService() {
return secretCallbackHandlerService;
}
public void setSecretCallbackHandlerService(
SecretCallbackHandlerService secretCallbackHandlerService) {
this.secretCallbackHandlerService = secretCallbackHandlerService;
}
public static void setThisInstance(DeviceManagerDataHolder thisInstance) {
DeviceManagerDataHolder.thisInstance = thisInstance;
}
public TenantManager getTenantManager() throws DeviceManagementException {
RealmService realmService = getRealmService();
if (realmService == null) {
throw new DeviceManagementException("Realm service is not initialized properly");
}
return realmService.getTenantManager();
}
/**
* Get tenant id of the current tenant
*
* @return tenant id
* @throws DeviceManagementException if error occurred when getting tenant id
*/
public int getTenantId() throws DeviceManagementException {
CarbonContext context = CarbonContext.getThreadLocalCarbonContext();
int tenantId = context.getTenantId();
if (tenantId != MultitenantConstants.INVALID_TENANT_ID) {
return tenantId;
}
String tenantDomain = context.getTenantDomain();
if (tenantDomain == null) {
String msg = "Tenant domain is not properly set and thus, is null";
throw new DeviceManagementException(msg);
}
TenantManager tenantManager = getTenantManager();
try {
tenantId = tenantManager.getTenantId(tenantDomain);
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving id from the domain of tenant " +
tenantDomain;
throw new DeviceManagementException(msg);
}
return tenantId;
}
}

@ -1,113 +0,0 @@
/**
* Copyright (c) 2014, 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.device.mgt.core.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagerService;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.DeviceMgtDbCreator;
import org.wso2.carbon.utils.CarbonUtils;
import javax.naming.InitialContext;
import javax.transaction.TransactionManager;
import java.io.File;
/**
* @scr.component name="org.wso2.carbon.device.manager" immediate="true"
* @scr.reference name="device.manager.service"
* interface="org.wso2.carbon.device.mgt.common.spi.DeviceManagerService" cardinality="1..n"
* policy="dynamic" bind="setDeviceManagerService" unbind="unsetDeviceManagerService"
*/
public class DeviceMgtServiceComponent {
private static Log log = LogFactory.getLog(DeviceMgtServiceComponent.class);
private final String deviceMgtSetupSql = CarbonUtils.getCarbonHome() + File.separator + "dbscripts" ;
protected void setDeviceManagerService(DeviceManagerService deviceManager) {
if (log.isDebugEnabled()) {
log.debug("Setting Device Management Service");
}
}
protected void unsetDeviceManagerService(DeviceManagerService deviceManager) {
if (log.isDebugEnabled()) {
log.debug("Unsetting Device Management Service");
}
}
protected void activate(ComponentContext componentContext) {
BundleContext bundleContext = componentContext.getBundleContext();
try {
/* Looks up for the JNDI registered transaction manager */
DeviceManagerDataHolder.getInstance().setTransactionManager(this.lookupTransactionManager());
/* Initializing RSS Configuration */
DeviceConfigurationManager.getInstance().initConfig();
String setupOption = System.getProperty("setup");
//if -Dsetup option specified then create rss manager tables
if (setupOption != null) {
log.info("Setup option specified");
DeviceMgtDbCreator dbCreator = new DeviceMgtDbCreator(DeviceManagerUtil.getDataSource());
dbCreator.setRssDBScriptDirectory(deviceMgtSetupSql);
log.info("Creating Meta Data tables");
dbCreator.createRegistryDatabase();
}
} catch (Throwable e) {
String msg = "Error occurred while initializing RSS Manager core bundle";
log.error(msg, e);
}
}
private TransactionManager lookupTransactionManager() {
TransactionManager transactionManager = null;
try {
Object txObj = InitialContext.doLookup(
DeviceManagementConstants.STANDARD_USER_TRANSACTION_JNDI_NAME);
if (txObj instanceof TransactionManager) {
transactionManager = (TransactionManager) txObj;
}
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Cannot find transaction manager at: "
+ DeviceManagementConstants.STANDARD_USER_TRANSACTION_JNDI_NAME, e);
}
/* ignore, move onto next step */
}
if (transactionManager == null) {
try {
transactionManager = InitialContext.doLookup(
DeviceManagementConstants.STANDARD_TRANSACTION_MANAGER_JNDI_NAME);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Cannot find transaction manager at: " +
DeviceManagementConstants.STANDARD_TRANSACTION_MANAGER_JNDI_NAME, e);
}
/* we'll do the lookup later, maybe user provided a custom JNDI name */
}
}
return transactionManager;
}
}

@ -0,0 +1,24 @@
/**
* Copyright (c) 2012, 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.device.mgt.core.service;
import org.wso2.carbon.core.AbstractAdmin;
public class DeviceManagementAdminService extends AbstractAdmin {
}

@ -0,0 +1,113 @@
/**
* Copyright (c) 2012, 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.device.mgt.core.service;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagerService;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import java.util.List;
public class DeviceManagementService implements DeviceManagerService {
@Override
public String getProviderType() {
return null;
}
@Override
public void enrollDevice(Device device) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(device.getType());
dms.enrollDevice(device);
}
@Override
public void modifyEnrollment(Device device) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(device.getType());
dms.modifyEnrollment(device);
}
@Override
public void disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(deviceId.getType());
dms.disenrollDevice(deviceId);
}
@Override
public boolean isRegistered(DeviceIdentifier deviceId) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(deviceId.getType());
return dms.isRegistered(deviceId);
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(deviceId.getType());
return dms.isActive(deviceId);
}
@Override
public void setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(deviceId.getType());
dms.setActive(deviceId, status);
}
@Override
public List<Device> getAllDevices(String type) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(type);
return dms.getAllDevices(type);
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(deviceId.getType());
return dms.getDevice(deviceId);
}
@Override
public void updateDeviceInfo(Device device) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(device.getType());
dms.updateDeviceInfo(device);
}
@Override
public void setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException {
DeviceManagerService dms =
DeviceManagementDataHolder.getInstance().getDeviceManagementRepository().
getDeviceManagementProvider(deviceId.getType());
dms.setOwnership(deviceId, ownershipType);
}
}

@ -17,18 +17,20 @@ package org.wso2.carbon.device.mgt.core.util;
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.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator; import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.io.File;
public class DeviceMgtDbCreator extends DatabaseCreator { public final class DeviceManagementSchemaInitializer extends DatabaseCreator {
private static final Log log = LogFactory.getLog(DeviceMgtDbCreator.class); private static final Log log = LogFactory.getLog(DeviceManagementSchemaInitializer.class);
private String rssDBScriptDirectory;// stores the the location of the database script that is run according to the databse type private static final String setupSQLScriptLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts" ;
public DeviceMgtDbCreator(DataSource dataSource) {
super(dataSource);
public DeviceManagementSchemaInitializer(DataSourceConfig config) {
super(DeviceManagerUtil.resolveDataSource(config));
} }
protected String getDbScriptLocation(String databaseType) { protected String getDbScriptLocation(String databaseType) {
@ -36,14 +38,7 @@ public class DeviceMgtDbCreator extends DatabaseCreator {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName); log.debug("Loading database script from :" + scriptName);
} }
return rssDBScriptDirectory.replaceFirst("DBTYPE", databaseType) + scriptName; return setupSQLScriptLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
} }
/**
* Sets database scripts directory
* @param rssDBScriptDirectory database scripts location
*/
public void setRssDBScriptDirectory(String rssDBScriptDirectory) {
this.rssDBScriptDirectory = rssDBScriptDirectory;
}
} }

@ -1,52 +1,39 @@
/* /**
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2012, 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 * Licensed under the Apache License, Version 2.0 (the "License");
* in compliance with the License. * you may not use this file except in compliance with the License.
* 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. *
* Unless required by applicable law or agreed to in writing, * http://www.apache.org/licenses/LICENSE-2.0
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * Unless required by applicable law or agreed to in writing, software
* KIND, either express or implied. See the License for the * distributed under the License is distributed on an "AS IS" BASIS,
* specific language governing permissions and limitations * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* under the License. * See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package org.wso2.carbon.device.mgt.core.util; package org.wso2.carbon.device.mgt.core.util;
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.w3c.dom.Document; import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.config.datasource.RDBMSConfig; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.ndatasource.common.DataSourceException; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.ndatasource.rdbms.RDBMSConfiguration; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.ndatasource.rdbms.RDBMSDataSource;
import org.wso2.securevault.SecretResolver;
import javax.naming.InitialContext;
import javax.sql.DataSource; import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File; import java.io.File;
import java.util.*; import java.util.Hashtable;
import java.util.List;
public class DeviceManagerUtil { public final class DeviceManagerUtil {
private static final Log log = LogFactory.getLog(DeviceManagerUtil.class); private static final Log log = LogFactory.getLog(DeviceManagerUtil.class);
private static SecretResolver secretResolver;
private static String jndiDataSourceName;
private static DataSource dataSource;
private static final String DEFAULT_PRIVILEGE_TEMPLATE_NAME = "CRUD_PRIVILEGES_DEFAULT";
/**
* Construct document from file resource
*
* @param file object
* @return Document
* @throws org.wso2.carbon.device.mgt.common.DeviceManagementException if error occurred constructing document from file resource
*/
public static Document convertToDocument(File file) throws DeviceManagementException { public static Document convertToDocument(File file) throws DeviceManagementException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); factory.setNamespaceAware(true);
@ -59,67 +46,38 @@ public class DeviceManagerUtil {
} }
} }
public static DataSource lookupDataSource(String dataSourceName, final Hashtable<Object, Object> jndiProperties) {
try {
if (jndiProperties == null || jndiProperties.isEmpty()) {
return (DataSource) InitialContext.doLookup(dataSourceName);
}
final InitialContext context = new InitialContext(jndiProperties);
return (DataSource) context.doLookup(dataSourceName);
} catch (Exception e) {
throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e);
}
}
public static void setJndiDataSourceName(String jndiDataSourceName) {
DeviceManagerUtil.jndiDataSourceName = jndiDataSourceName;
}
public static void setDataSource(DataSource dataSource) {
DeviceManagerUtil.dataSource = dataSource;
}
public static DataSource getDataSource() {
return dataSource;
}
public static Properties loadDataSourceProperties(RDBMSConfig config) {
Properties props = new Properties();
List<RDBMSConfig.DataSourceProperty> dsProps = config.getDataSourceProps();
for (RDBMSConfig.DataSourceProperty dsProp : dsProps) {
props.setProperty(dsProp.getName(), dsProp.getValue());
}
return props;
}
/** /**
* Create data source from properties * Resolve data source from the data source definition
* *
* @param properties set of data source properties * @param config data source configuration
* @param dataSourceClassName data source class name * @return data source resolved from the data source definition
* @return DataSource
*/ */
public static DataSource createDataSource(Properties properties, String dataSourceClassName) { public static DataSource resolveDataSource(DataSourceConfig config) {
RDBMSConfiguration config = new RDBMSConfiguration(); DataSource dataSource = null;
config.setDataSourceClassName(dataSourceClassName); if (config == null) {
List<RDBMSConfiguration.DataSourceProperty> dsProps = new ArrayList<RDBMSConfiguration.DataSourceProperty>(); throw new RuntimeException("Device Management Repository data source configuration " +
for (Map.Entry<Object, Object> entry : properties.entrySet()) { "is null and thus, is not initialized");
RDBMSConfiguration.DataSourceProperty property =
new RDBMSConfiguration.DataSourceProperty();
property.setName((String) entry.getKey());
property.setValue((String) entry.getValue());
dsProps.add(property);
} }
config.setDataSourceProps(dsProps); JNDILookupDefinition jndiConfig = config.getJndiLookupDefintion();
return createDataSource(config); if (jndiConfig != null) {
} if (log.isDebugEnabled()) {
log.debug("Initializing Device Management Repository data source using the JNDI " +
public static DataSource createDataSource(RDBMSConfiguration config) { "Lookup Definition");
try { }
RDBMSDataSource dataSource = new RDBMSDataSource(config); List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
return dataSource.getDataSource(); jndiConfig.getJndiProperties();
} catch (DataSourceException e) { if (jndiPropertyList != null) {
throw new RuntimeException("Error in creating data source: " + e.getMessage(), e); Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue());
}
dataSource =
DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties);
} else {
dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null);
}
} }
return dataSource;
} }
} }

@ -61,7 +61,7 @@ public class AndroidDeviceManagerService implements DeviceManagerService {
} }
@Override @Override
public void setActive(boolean status) throws DeviceManagementException { public void setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException {
} }

@ -61,7 +61,7 @@ public class IOSDeviceManagerService implements DeviceManagerService {
} }
@Override @Override
public void setActive(boolean status) throws DeviceManagementException { public void setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException {
} }

@ -61,7 +61,7 @@ public class WindowsDeviceManagerService implements DeviceManagerService {
} }
@Override @Override
public void setActive(boolean status) throws DeviceManagementException { public void setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException {
} }

@ -134,8 +134,6 @@
<artifactId>org.eclipse.equinox.common</artifactId> <artifactId>org.eclipse.equinox.common</artifactId>
<version>${eclipse.equinox.common.version}</version> <version>${eclipse.equinox.common.version}</version>
</dependency> </dependency>
<!--Test dependencies--> <!--Test dependencies-->
<!-- <!--
<dependency> <dependency>
@ -145,13 +143,41 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
--> -->
<dependency> <dependency>
<groupId>org.testng</groupId> <groupId>org.testng</groupId>
<artifactId>testng</artifactId> <artifactId>testng</artifactId>
<version>${testng.version}</version> <version>${testng.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<version>${carbon.platform.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
<version>${carbon.platform.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
<version>${carbon.platform.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.rdbms</artifactId>
<version>${carbon.platform.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.transaction.manager</artifactId>
<version>${carbon.platform.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.1_spec</artifactId>
<version>${jboss-transaction-api.version}</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>

Loading…
Cancel
Save