From c45895685bb66a253c40dc99f351ddeea3c099de Mon Sep 17 00:00:00 2001 From: ayyoob Date: Tue, 29 Mar 2016 11:40:58 +0530 Subject: [PATCH 01/10] Added device type multi tenancy capability. --- .../mgt/common/DeviceTypeIdentifier.java | 69 ++++ .../common/spi/DeviceManagementService.java | 13 + .../DeviceManagementPluginRepository.java | 57 +++- .../device/mgt/core/dao/DeviceTypeDAO.java | 58 +++- .../mgt/core/dao/impl/DeviceTypeDAOImpl.java | 312 ++++++++++-------- .../DeviceManagementProviderServiceImpl.java | 56 ++-- .../mgt/core/util/DeviceManagerUtil.java | 59 +++- .../core/DeviceManagementRepositoryTests.java | 68 ++-- .../mgt/core/TestDeviceManagementService.java | 12 +- ...licationManagementProviderServiceTest.java | 2 +- .../mgt/core/common/TestDataHolder.java | 1 + .../mgt/core/dao/DevicePersistTests.java | 2 +- .../src/test/resources/sql/h2.sql | 6 +- .../core/mgt/impl/MonitoringManagerImpl.java | 4 +- .../mgt/core/mgt/impl/ProfileManagerImpl.java | 7 +- .../policy/mgt/core/PolicyDAOTestCase.java | 2 +- .../src/test/resources/sql/CreateH2TestDB.sql | 4 +- .../test/resources/sql/CreateMySqlTestDB.sql | 2 + .../src/main/resources/dbscripts/cdm/h2.sql | 6 +- .../main/resources/dbscripts/cdm/mssql.sql | 8 +- .../main/resources/dbscripts/cdm/mysql.sql | 2 + .../main/resources/dbscripts/cdm/oracle.sql | 2 + .../resources/dbscripts/cdm/postgresql.sql | 4 +- 23 files changed, 518 insertions(+), 238 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java new file mode 100644 index 0000000000..1eb5e28e46 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.common; + +import java.io.Serializable; + +/** + * This class holds the information of the device type and its provider tenant. + */ +public class DeviceTypeIdentifier implements Serializable { + + private String deviceType; + private int tenantId; + private static final int DEFAULT_SHARE_WITH_ALL_TENANTS_ID = -1; + + public DeviceTypeIdentifier(String deviceType, int tenantId) { + this.deviceType = deviceType; + this.tenantId = tenantId; + } + + public DeviceTypeIdentifier(String deviceType) { + this.deviceType = deviceType; + this.tenantId = DEFAULT_SHARE_WITH_ALL_TENANTS_ID; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getDeviceType() { + return this.deviceType; + } + + public int getTenantId() { + return this.tenantId; + } + + @Override + public int hashCode() { + int result = this.deviceType.hashCode(); + result = 31 * result + ("@" + this.tenantId).hashCode(); + return result; + } + + @Override + public boolean equals(Object obj) { + return (obj instanceof DeviceTypeIdentifier) && deviceType.equals( + ((DeviceTypeIdentifier) obj).deviceType) && tenantId == ((DeviceTypeIdentifier) obj).tenantId; + } + + public boolean isSharedWithAllTenant() { + return tenantId == DEFAULT_SHARE_WITH_ALL_TENANTS_ID; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java index bf2e44f3d8..143fd1e8db 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java @@ -39,6 +39,19 @@ public interface DeviceManagementService extends ApplicationManager { */ String getType(); + /** + * This returns the tenant domain of the provider. + * @return + */ + String getProviderTenantDomain(); + + /** + * returns true if the device type is shared between all tenants and false if its not. + * + * @return + */ + boolean isSharedWithAllTenants(); + void init() throws DeviceManagementException; DeviceManager getDeviceManager(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index afeee53c8a..594d1be5e7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core; 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.DeviceTypeIdentifier; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; @@ -32,23 +33,29 @@ import java.util.Map; public class DeviceManagementPluginRepository implements DeviceManagerStartupListener { - private Map providers; + private Map providers; private boolean isInited; private static final Log log = LogFactory.getLog(DeviceManagementPluginRepository.class); public DeviceManagementPluginRepository() { - providers = Collections.synchronizedMap(new HashMap()); + providers = Collections.synchronizedMap(new HashMap()); DeviceManagementServiceComponent.registerStartupListener(this); } public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceType = provider.getType(); + String deviceType = provider.getType(); + String tenantDomain = provider.getProviderTenantDomain(); + boolean isSharedWithAllTenants = provider.isSharedWithAllTenants(); + int tenantId = DeviceManagerUtil.getTenantId(tenantDomain); + if (tenantId == -1) { + throw new DeviceManagementException("No tenant available for tenant domain " + tenantDomain); + } synchronized (providers) { try { if (isInited) { /* Initializing Device Management Service Provider */ provider.init(); - DeviceManagerUtil.registerDeviceType(deviceType); + DeviceManagerUtil.registerDeviceType(deviceType, tenantId, isSharedWithAllTenants); DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(deviceType, provider.getDeviceManager().requireDeviceAuthorization()); @@ -57,20 +64,47 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis throw new DeviceManagementException("Error occurred while adding device management provider '" + deviceType + "'", e); } - providers.put(deviceType, provider); + if (isSharedWithAllTenants) { + DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType); + providers.put(deviceTypeIdentifier, provider); + } else { + DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType, tenantId); + providers.put(deviceTypeIdentifier, provider); + } } } public void removeDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - providers.remove(provider.getType()); + String deviceTypeName=provider.getType(); + if(provider.isSharedWithAllTenants()){ + DeviceTypeIdentifier deviceTypeIdentifier =new DeviceTypeIdentifier(deviceTypeName); + providers.remove(deviceTypeIdentifier); + }else{ + int providerTenantId=DeviceManagerUtil.getTenantId(provider.getProviderTenantDomain()); + DeviceTypeIdentifier deviceTypeIdentifier =new DeviceTypeIdentifier(deviceTypeName, providerTenantId); + providers.remove(deviceTypeIdentifier); + } } - public DeviceManagementService getDeviceManagementService(String type) { - return providers.get(type); + public DeviceManagementService getDeviceManagementService(String type, int tenantId) { + //Priority need to be given to the tenant before public. + DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(type, tenantId); + DeviceManagementService provider = providers.get(deviceTypeIdentifier); + if (provider == null) { + deviceTypeIdentifier = new DeviceTypeIdentifier(type); + provider = providers.get(deviceTypeIdentifier); + } + return provider; } - public Map getAllDeviceManagementServices() { - return providers; + public Map getAllDeviceManagementServices(int tenantId) { + Map tenantProviders = new HashMap<>(); + for (DeviceTypeIdentifier identifier : providers.keySet()) { + if (identifier.getTenantId() == tenantId || identifier.isSharedWithAllTenant()) { + tenantProviders.put(identifier, providers.get(identifier)); + } + } + return tenantProviders; } @Override @@ -79,7 +113,8 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis for (DeviceManagementService provider : providers.values()) { try { provider.init(); - DeviceManagerUtil.registerDeviceType(provider.getType()); + int tenantId=DeviceManagerUtil.getTenantId(provider.getProviderTenantDomain()); + DeviceManagerUtil.registerDeviceType(provider.getType(), tenantId, provider.isSharedWithAllTenants()); //TODO: //This is a temporory fix. //windows and IOS cannot resolve user info by extracting certs diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java index d7217c90d1..53827abd6e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceTypeDAO.java @@ -27,18 +27,64 @@ import java.util.List; */ public interface DeviceTypeDAO { - void addDeviceType(DeviceType deviceType) throws DeviceManagementDAOException; + /** + * @param deviceType device that needs to be added + * @param providerTenantId provider tenant id whom the device type is associated with. + * @param isSharedWithAllTenants is this a shared device type or not. + * @throws DeviceManagementDAOException + */ + void addDeviceType(DeviceType deviceType, int providerTenantId, boolean isSharedWithAllTenants) + throws DeviceManagementDAOException; - void updateDeviceType(DeviceType deviceType) throws DeviceManagementDAOException; + /** + * @param deviceType deviceType that needs to be updated. + * @param providerTenantId provider tenant id whom the device type is associated with. + * @throws DeviceManagementDAOException + */ + void updateDeviceType(DeviceType deviceType, int providerTenantId) throws DeviceManagementDAOException; - List getDeviceTypes() throws DeviceManagementDAOException; + /** + * @param tenantId get device type detail of a specific tenant. + * @return list of all device types that are associated with the tenant this includes the shared device types. + * @throws DeviceManagementDAOException + */ + List getDeviceTypes(int tenantId) throws DeviceManagementDAOException; - List getDeviceTypes(int tenantId) throws DeviceManagementDAOException; + /** + * @param tenandId of the device type provider. + * @return return only the device types that are associated with the provider tenant. + * @throws DeviceManagementDAOException + */ + List getDeviceTypesByProvider(int tenandId) throws DeviceManagementDAOException; + /** + * @return sharedWithAllDeviceTypes This returns public shared device types. + * @throws DeviceManagementDAOException + */ + List getSharedDeviceTypes() throws DeviceManagementDAOException; + + /** + * @param id retrieve the device type with its id. + * @return the device type associated with the id. + * @throws DeviceManagementDAOException + */ DeviceType getDeviceType(int id) throws DeviceManagementDAOException; - DeviceType getDeviceType(String name) throws DeviceManagementDAOException; + /** + * @param name retreive the device type with it name. + * @param tenantId retreive the device type with its tenant id. + * @return the device type associated with its name and tenant id. + * @throws DeviceManagementDAOException + */ + DeviceType getDeviceType(String name, int tenantId) throws DeviceManagementDAOException; - void removeDeviceType(String type) throws DeviceManagementDAOException; + /** + * remove the device type from tenant. + * + * @param name remove the device type with it name. + * @param tenantId remove the device type with its tenant id. + * @throws DeviceManagementDAOException + */ + void removeDeviceType(String name, int tenantId) throws DeviceManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java index 0014e56f6f..bccddcee40 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceTypeDAOImpl.java @@ -32,143 +32,179 @@ import java.util.List; public class DeviceTypeDAOImpl implements DeviceTypeDAO { - @Override - public void addDeviceType(DeviceType deviceType) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - try { - conn = this.getConnection(); - 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(stmt, null); - } - } - - @Override - public void updateDeviceType(DeviceType deviceType) throws DeviceManagementDAOException { - - } - - @Override - public List getDeviceTypes() throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List deviceTypes = new ArrayList<>(); - try { - conn = this.getConnection(); - String sql = "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE"; - stmt = conn.prepareStatement(sql); - rs = stmt.executeQuery(); - - while (rs.next()) { - DeviceType deviceType = new DeviceType(); - deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); - deviceType.setName(rs.getString("DEVICE_TYPE")); - deviceTypes.add(deviceType); - } - return deviceTypes; - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the registered device types", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - - @Override - public List getDeviceTypes(int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List deviceTypes = new ArrayList<>(); - try { - conn = this.getConnection(); - String sql = - "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE where PROVIDER_TENANT_ID =" + - "? OR SHARED_WITH_ALL_TENANTS = TRUE"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - rs = stmt.executeQuery(); - - while (rs.next()) { - DeviceType deviceType = new DeviceType(); - deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); - deviceType.setName(rs.getString("DEVICE_TYPE")); - deviceTypes.add(deviceType); - } - return deviceTypes; - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the registered device types", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - - @Override - public DeviceType getDeviceType(int id) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - try { - conn = this.getConnection(); - String sql = "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE WHERE ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, id); - - rs = stmt.executeQuery(); - DeviceType deviceType = null; - while (rs.next()) { - deviceType = new DeviceType(); - deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); - deviceType.setName(rs.getString("DEVICE_TYPE")); - } - return deviceType; - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the registered device type", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - - @Override - public DeviceType getDeviceType(String type) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - DeviceType deviceType = null; - try { - conn = this.getConnection(); - String sql = "SELECT ID From DM_DEVICE_TYPE WHERE NAME = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, type); - rs = stmt.executeQuery(); - - if (rs.next()) { - deviceType = new DeviceType(); - deviceType.setId(rs.getInt("ID")); - deviceType.setName(type); - } - return deviceType; - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetch device type id for device type " + - "'" + type + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - - @Override - public void removeDeviceType(String type) throws DeviceManagementDAOException { - - } - - private Connection getConnection() throws SQLException { - return DeviceManagementDAOFactory.getConnection(); - } + @Override + public void addDeviceType(DeviceType deviceType, int providerTenantId, boolean isSharedWithAllTenants) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + stmt = conn.prepareStatement( + "INSERT INTO DM_DEVICE_TYPE (NAME,PROVIDER_TENANT_ID,SHARED_WITH_ALL_TENANTS) VALUES (?,?,?)"); + stmt.setString(1, deviceType.getName()); + stmt.setInt(2, providerTenantId); + stmt.setBoolean(3, isSharedWithAllTenants); + stmt.execute(); + } catch (SQLException e) { + throw new DeviceManagementDAOException( + "Error occurred while registering the device type '" + deviceType.getName() + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void updateDeviceType(DeviceType deviceType, int tenantId) + throws DeviceManagementDAOException { + } + + @Override + public List getDeviceTypes(int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List deviceTypes = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = + "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE where PROVIDER_TENANT_ID =" + + "? OR SHARED_WITH_ALL_TENANTS = TRUE"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + rs = stmt.executeQuery(); + + while (rs.next()) { + DeviceType deviceType = new DeviceType(); + deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); + deviceType.setName(rs.getString("DEVICE_TYPE")); + deviceTypes.add(deviceType); + } + return deviceTypes; + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the registered device types", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public List getDeviceTypesByProvider(int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List deviceTypes = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = + "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE where PROVIDER_TENANT_ID =?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + rs = stmt.executeQuery(); + + while (rs.next()) { + DeviceType deviceType = new DeviceType(); + deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); + deviceType.setName(rs.getString("DEVICE_TYPE")); + deviceTypes.add(deviceType); + } + return deviceTypes; + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the registered device types", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public List getSharedDeviceTypes() throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List deviceTypes = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = + "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE where " + + "SHARED_WITH_ALL_TENANTS = TRUE"; + stmt = conn.prepareStatement(sql); + rs = stmt.executeQuery(); + + while (rs.next()) { + DeviceType deviceType = new DeviceType(); + deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); + deviceType.setName(rs.getString("DEVICE_TYPE")); + deviceTypes.add(deviceType); + } + return deviceTypes; + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the registered device types", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public DeviceType getDeviceType(int id) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + try { + conn = this.getConnection(); + String sql = "SELECT ID AS DEVICE_TYPE_ID, NAME AS DEVICE_TYPE FROM DM_DEVICE_TYPE WHERE ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, id); + rs = stmt.executeQuery(); + DeviceType deviceType = null; + while (rs.next()) { + deviceType = new DeviceType(); + deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); + deviceType.setName(rs.getString("DEVICE_TYPE")); + } + return deviceType; + } catch (SQLException e) { + throw new DeviceManagementDAOException( + "Error occurred while fetching the registered device type", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public DeviceType getDeviceType(String type, int tenantId) throws + DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + DeviceType deviceType = null; + try { + conn = this.getConnection(); + String sql = "SELECT ID AS DEVICE_TYPE_ID FROM DM_DEVICE_TYPE WHERE (PROVIDER_TENANT_ID =? OR " + + "SHARED_WITH_ALL_TENANTS = TRUE) AND NAME =?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, type); + rs = stmt.executeQuery(); + if (rs.next()) { + deviceType = new DeviceType(); + deviceType.setId(rs.getInt("DEVICE_TYPE_ID")); + deviceType.setName(type); + } + return deviceType; + } catch (SQLException e) { + throw new DeviceManagementDAOException( + "Error occurred while fetch device type id for device type '" + type + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public void removeDeviceType(String type, int tenantId) throws DeviceManagementDAOException { + + } + + private Connection getConnection() throws SQLException { + return DeviceManagementDAOFactory.getConnection(); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index f70eb5dca5..0e4e490fa6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -67,7 +67,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean saveConfiguration(TenantConfiguration configuration) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(configuration.getType()).getDeviceManager(); + this.getPluginRepository().getDeviceManagementService(configuration.getType(), this.getTenantId()).getDeviceManager(); return dms.saveConfiguration(configuration); } @@ -79,7 +79,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public TenantConfiguration getConfiguration(String deviceType) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(deviceType).getDeviceManager(); + this.getPluginRepository().getDeviceManagementService(deviceType, this.getTenantId()).getDeviceManager(); if (dms == null) { if (log.isDebugEnabled()) { log.debug("Device type '" + deviceType + "' does not have an associated device management " + @@ -185,7 +185,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int enrolmentId = 0; try { DeviceManagementDAOFactory.beginTransaction(); - DeviceType type = deviceTypeDAO.getDeviceType(device.getType()); + DeviceType type = deviceTypeDAO.getDeviceType(device.getType(), tenantId); int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId); enrolmentId = enrollmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId); DeviceManagementDAOFactory.commitTransaction(); @@ -226,7 +226,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv try { int tenantId = this.getTenantId(); DeviceManagementDAOFactory.beginTransaction(); - DeviceType type = deviceTypeDAO.getDeviceType(device.getType()); + DeviceType type = deviceTypeDAO.getDeviceType(device.getType(), tenantId); deviceDAO.updateDevice(type.getId(), device, tenantId); enrollmentDAO.updateEnrollment(device.getEnrolmentInfo()); DeviceManagementDAOFactory.commitTransaction(); @@ -287,7 +287,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } return false; } - DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType()); + DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType(), tenantId); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.REMOVED); @@ -621,22 +621,40 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public List getAvailableDeviceTypes() throws DeviceManagementException { - List deviceTypesInDatabase; + List deviceTypesProvidedByTenant; + List publicSharedDeviceTypesInDB; List deviceTypesResponse = new ArrayList<>(); try { DeviceManagementDAOFactory.openConnection(); - deviceTypesInDatabase = deviceDAO.getDeviceTypes(); - Map registeredTypes = pluginRepository.getAllDeviceManagementServices(); - DeviceType deviceType; - if (registeredTypes != null && deviceTypesInDatabase != null) { - for (DeviceType aDeviceTypesInDatabase : deviceTypesInDatabase) { - if (registeredTypes.get(aDeviceTypesInDatabase.getName()) != null) { - deviceType = new DeviceType(); - deviceType.setId(aDeviceTypesInDatabase.getId()); - deviceType.setName(aDeviceTypesInDatabase.getName()); - deviceTypesResponse.add(deviceType); + int tenantId = this.getTenantId(); + deviceTypesProvidedByTenant = deviceTypeDAO.getDeviceTypesByProvider(tenantId); + publicSharedDeviceTypesInDB = deviceTypeDAO.getSharedDeviceTypes(); + Map registeredTypes = + pluginRepository.getAllDeviceManagementServices(tenantId); + Set deviceTypeSetForTenant = new HashSet<>(); + + if (registeredTypes != null) { + if (deviceTypesProvidedByTenant != null) { + for (DeviceType deviceType : deviceTypesProvidedByTenant) { + DeviceTypeIdentifier providerKey = new DeviceTypeIdentifier(deviceType.getName(), tenantId); + if (registeredTypes.get(providerKey) != null) { + deviceTypesResponse.add(deviceType); + deviceTypeSetForTenant.add(deviceType.getName()); + } + } + } + // Get the device from the public space, however if there is another device with same name then give + // priority to that + if (publicSharedDeviceTypesInDB != null) { + for (DeviceType deviceType : publicSharedDeviceTypesInDB) { + DeviceTypeIdentifier providerKey = new DeviceTypeIdentifier(deviceType.getName()); + if (registeredTypes.get(providerKey) != null && !deviceTypeSetForTenant.contains( + deviceType.getName())) { + deviceTypesResponse.add(deviceType); + } } } + } } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while obtaining the device types.", e); @@ -714,7 +732,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv try { for (DeviceIdentifier deviceId : deviceIds) { DeviceManagementService dms = - getPluginRepository().getDeviceManagementService(deviceId.getType()); + getPluginRepository().getDeviceManagementService(deviceId.getType(), this.getTenantId()); dms.notifyOperationToDevices(operation, deviceIds); } } catch (DeviceManagementException deviceMgtEx) { @@ -1068,7 +1086,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status status) throws DeviceManagementException { try { DeviceManagementDAOFactory.beginTransaction(); - DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType()); + DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType(), this.getTenantId()); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setStatus(status); deviceDAO.updateDevice(deviceType.getId(), device, this.getTenantId()); @@ -1171,7 +1189,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv private DeviceManager getDeviceManager(String deviceType) { DeviceManagementService deviceManagementService = - this.getPluginRepository().getDeviceManagementService(deviceType); + this.getPluginRepository().getDeviceManagementService(deviceType, this.getTenantId()); if (deviceManagementService == null) { if (log.isDebugEnabled()) { log.debug("Device type '" + deviceType + "' does not have an associated device management " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index 629787f529..ec798f2bdc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; +import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -33,6 +34,8 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.user.api.TenantManager; +import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.NetworkUtils; @@ -100,29 +103,32 @@ public final class DeviceManagerUtil { * Adds a new device type to the database if it does not exists. * * @param typeName device type + * @param tenantId provider tenant Id + * @param isSharedWithAllTenants is this device type shared with all tenants. * @return status of the operation */ - public static boolean registerDeviceType(String typeName) throws DeviceManagementException { + public static boolean registerDeviceType(String typeName, int tenantId, boolean isSharedWithAllTenants) + throws DeviceManagementException { boolean status; try { DeviceManagementDAOFactory.beginTransaction(); DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); - DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName); + DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName, tenantId); if (deviceType == null) { - DeviceType dt = new DeviceType(); - dt.setName(typeName); - deviceTypeDAO.addDeviceType(dt); + deviceType = new DeviceType(); + deviceType.setName(typeName); + deviceTypeDAO.addDeviceType(deviceType, tenantId, isSharedWithAllTenants); } DeviceManagementDAOFactory.commitTransaction(); status = true; } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); - throw new DeviceManagementException("Error occurred while registering the device type '" + - typeName + "'", e); + throw new DeviceManagementException("Error occurred while registering the device type '" + + typeName + "'", e); } catch (TransactionManagementException e) { DeviceManagementDAOFactory.rollbackTransaction(); - throw new DeviceManagementException("SQL occurred while registering the device type '" + - typeName + "'", e); + throw new DeviceManagementException("SQL occurred while registering the device type '" + + typeName + "'", e); } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -135,26 +141,24 @@ public final class DeviceManagerUtil { * @param typeName device type * @return status of the operation */ - public static boolean unregisterDeviceType(String typeName) throws DeviceManagementException { + public static boolean unregisterDeviceType(String typeName, int tenantId) throws DeviceManagementException { try { DeviceManagementDAOFactory.beginTransaction(); DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); - DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName); + DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName, tenantId); if (deviceType != null) { - DeviceType dt = new DeviceType(); - dt.setName(typeName); - deviceTypeDAO.removeDeviceType(typeName); + deviceTypeDAO.removeDeviceType(typeName, tenantId); } DeviceManagementDAOFactory.commitTransaction(); return true; } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceManagementException("Error occurred while registering the device type '" + - typeName + "'", e); + typeName + "'", e); } catch (TransactionManagementException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceManagementException("SQL occurred while registering the device type '" + - typeName + "'", e); + typeName + "'", e); } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -217,4 +221,27 @@ public final class DeviceManagerUtil { return "http://" + hostName + ":" + port; } + /** + * returns the tenant Id of the specific tenant Domain + * + * @param tenantDomain + * @return + * @throws DeviceManagementException + */ + public static int getTenantId(String tenantDomain) throws DeviceManagementException { + try { + if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + return MultitenantConstants.SUPER_TENANT_ID; + } + TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager(); + int tenantId = tenantManager.getTenantId(tenantDomain); + if (tenantId == -1) { + throw new DeviceManagementException("invalid tenant Domain :" + tenantDomain); + } + return tenantId; + } catch (UserStoreException e) { + throw new DeviceManagementException("invalid tenant Domain :" + tenantDomain); + } + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java index 127ee0d707..925d8a9e8d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java @@ -27,41 +27,45 @@ import org.wso2.carbon.device.mgt.core.common.TestDataHolder; public class DeviceManagementRepositoryTests { - private DeviceManagementPluginRepository repository; + private DeviceManagementPluginRepository repository; - @BeforeClass - public void initRepository() { - this.repository = new DeviceManagementPluginRepository(); - } + @BeforeClass + public void initRepository() { + this.repository = new DeviceManagementPluginRepository(); + } - @Test - public void testAddDeviceManagementService() { - DeviceManagementService sourceProvider = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE); - try { - this.getRepository().addDeviceManagementProvider(sourceProvider); - } catch (DeviceManagementException e) { - Assert.fail("Unexpected error occurred while invoking addDeviceManagementProvider functionality", e); - } - DeviceManagementService targetProvider = - this.getRepository().getDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE); - Assert.assertEquals(targetProvider.getType(), sourceProvider.getType()); - } + @Test + public void testAddDeviceManagementService() { + DeviceManagementService sourceProvider = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE, + TestDataHolder.SUPER_TENANT_DOMAIN); + try { + this.getRepository().addDeviceManagementProvider(sourceProvider); + } catch (DeviceManagementException e) { + Assert.fail("Unexpected error occurred while invoking addDeviceManagementProvider functionality", e); + } + DeviceManagementService targetProvider = + this.getRepository().getDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE, + TestDataHolder.SUPER_TENANT_ID); + Assert.assertEquals(targetProvider.getType(), sourceProvider.getType()); + } - @Test(dependsOnMethods = "testAddDeviceManagementService") - public void testRemoveDeviceManagementService() { - DeviceManagementService sourceProvider = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE); - try { - this.getRepository().removeDeviceManagementProvider(sourceProvider); - } catch (DeviceManagementException e) { - Assert.fail("Unexpected error occurred while invoking removeDeviceManagementProvider functionality", e); - } - DeviceManagementService targetProvider = - this.getRepository().getDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE); - Assert.assertNull(targetProvider); - } + @Test(dependsOnMethods = "testAddDeviceManagementService") + public void testRemoveDeviceManagementService() { + DeviceManagementService sourceProvider = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE, + TestDataHolder.SUPER_TENANT_DOMAIN); + try { + this.getRepository().removeDeviceManagementProvider(sourceProvider); + } catch (DeviceManagementException e) { + Assert.fail("Unexpected error occurred while invoking removeDeviceManagementProvider functionality", e); + } + DeviceManagementService targetProvider = + this.getRepository().getDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE, + TestDataHolder.SUPER_TENANT_ID); + Assert.assertNull(targetProvider); + } - private DeviceManagementPluginRepository getRepository() { - return repository; - } + private DeviceManagementPluginRepository getRepository() { + return repository; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java index 63128cbbdd..c94a00fe8d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java @@ -34,15 +34,25 @@ import java.util.List; public class TestDeviceManagementService implements DeviceManagementService { private String providerType; + private String tenantDomain; - public TestDeviceManagementService(String deviceType){ + public TestDeviceManagementService(String deviceType, String tenantDomain){ providerType = deviceType; + this.tenantDomain = tenantDomain; } @Override public String getType() { return providerType; } + @Override + public String getProviderTenantDomain() { return tenantDomain;} + + @Override + public boolean isSharedWithAllTenants() { + return true; + } + @Override public void init() throws DeviceManagementException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java index b98745f8a2..4c7996e381 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java @@ -43,7 +43,7 @@ public class ApplicationManagementProviderServiceTest { public void init() { deviceManagementPluginRepository = new DeviceManagementPluginRepository(); TestDeviceManagementService testDeviceManagementService = - new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE); + new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE, TestDataHolder.SUPER_TENANT_DOMAIN); try { deviceManagementPluginRepository.addDeviceManagementProvider(testDeviceManagementService); } catch (DeviceManagementException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java index 1d381abf1e..78dcab56ea 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java @@ -29,6 +29,7 @@ public class TestDataHolder { public static DeviceType initialTestDeviceType; public static String TEST_DEVICE_TYPE = "Test"; public static Integer SUPER_TENANT_ID = -1234; + public static String SUPER_TENANT_DOMAIN="carbon.super"; public static String initialDeviceIdentifier = "12345"; public static Device generateDummyDeviceData(String deviceType){ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java index d7996be3a1..22914836b7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/DevicePersistTests.java @@ -54,7 +54,7 @@ public class DevicePersistTests extends BaseDeviceManagementTest { DeviceType deviceType = TestDataHolder.generateDeviceTypeData(TestDataHolder.TEST_DEVICE_TYPE); try { DeviceManagementDAOFactory.beginTransaction(); - deviceTypeDAO.addDeviceType(deviceType); + deviceTypeDAO.addDeviceType(deviceType, TestDataHolder.SUPER_TENANT_ID, true); } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while adding device type '" + deviceType.getName() + "'"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index d172e2f5d2..f112ff49a7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -1,6 +1,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( - ID INT auto_increment NOT NULL, - NAME VARCHAR(300) DEFAULT NULL, + ID INT AUTO_INCREMENT NOT NULL, + NAME VARCHAR(300) NULL DEFAULT NULL, + PROVIDER_TENANT_ID INTEGER DEFAULT 0, + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID) ); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index f4c83d990f..fa5e8ae7f3 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; @@ -375,7 +376,8 @@ public class MonitoringManagerImpl implements MonitoringManager { List deviceTypes = new ArrayList<>(); try { DeviceManagementDAOFactory.openConnection(); - deviceTypes = deviceTypeDAO.getDeviceTypes(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + deviceTypes = deviceTypeDAO.getDeviceTypes(tenantId); } catch (Exception e) { log.error("Error occurred while getting the device types.", e); } finally { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java index 394124cbeb..bdfe27c420 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; @@ -184,8 +185,9 @@ public class ProfileManagerImpl implements ProfileManager { List deviceTypes; try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); DeviceManagementDAOFactory.openConnection(); - deviceTypes = deviceTypeDAO.getDeviceTypes(); + deviceTypes = deviceTypeDAO.getDeviceTypes(tenantId); } catch (SQLException e) { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } catch (DeviceManagementDAOException e) { @@ -236,7 +238,8 @@ public class ProfileManagerImpl implements ProfileManager { try { DeviceManagementDAOFactory.openConnection(); - deviceType = deviceTypeDAO.getDeviceType(deviceTypeName); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + deviceType = deviceTypeDAO.getDeviceType(deviceTypeName, tenantId); } catch (DeviceManagementDAOException e) { throw new ProfileManagementException("Error occurred while retrieving device type information", e); } catch (SQLException e) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java index 868931c422..9e44132e06 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java @@ -60,7 +60,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { try { DeviceManagementDAOFactory.beginTransaction(); DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); - deviceTypeDAO.addDeviceType(DeviceTypeCreator.getDeviceType()); + deviceTypeDAO.addDeviceType(DeviceTypeCreator.getDeviceType(), -1234, true); } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceManagementDAOException("Error occurred while adding dummy device type", e); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index 8b101ba8c1..83c3142af4 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -1,6 +1,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( - ID INT auto_increment NOT NULL, + ID INT AUTO_INCREMENT NOT NULL, NAME VARCHAR(300) NULL DEFAULT NULL, + PROVIDER_TENANT_ID INTEGER DEFAULT 0, + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID) ); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateMySqlTestDB.sql b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateMySqlTestDB.sql index a85059fa83..f5466feaf6 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateMySqlTestDB.sql +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateMySqlTestDB.sql @@ -25,6 +25,8 @@ DROP TABLE IF EXISTS `WSO2CDM`.`DM_DEVICE_TYPE` ; CREATE TABLE IF NOT EXISTS `WSO2CDM`.`DM_DEVICE_TYPE` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `NAME` VARCHAR(300) NULL DEFAULT NULL, + `PROVIDER_TENANT_ID` INTEGER DEFAULT 0, + `SHARED_WITH_ALL_TENANTS` BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (`ID`)) ENGINE = InnoDB DEFAULT CHARACTER SET = latin1; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 3a268960d1..f4c5357eed 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -1,6 +1,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( - ID INT auto_increment NOT NULL, - NAME VARCHAR(300) DEFAULT NULL, + ID INT AUTO_INCREMENT NOT NULL, + NAME VARCHAR(300) NULL DEFAULT NULL, + PROVIDER_TENANT_ID INTEGER DEFAULT 0, + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID) ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index bb55d05862..3287ebafe5 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -1,7 +1,9 @@ CREATE TABLE DM_DEVICE_TYPE ( - ID INTEGER IDENTITY NOT NULL, - NAME VARCHAR(300) DEFAULT NULL, - PRIMARY KEY (ID) + ID INTEGER IDENTITY NOT NULL, + NAME VARCHAR(300) DEFAULT NULL, + PROVIDER_TENANT_ID INTEGER DEFAULT 0, + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (ID) ); CREATE TABLE DM_DEVICE_CERTIFICATE ( diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index 545f939108..74defa7d89 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -1,6 +1,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( ID INTEGER AUTO_INCREMENT NOT NULL, NAME VARCHAR(300) DEFAULT NULL, + PROVIDER_TENANT_ID INTEGER DEFAULT 0, + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID) )ENGINE = InnoDB; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql index 728233d24b..c5032611d5 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -1,6 +1,8 @@ CREATE TABLE DM_DEVICE_TYPE ( ID NUMBER(10) NOT NULL, NAME VARCHAR2(300) DEFAULT NULL, + PROVIDER_TENANT_ID INTEGER DEFAULT 0, + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, CONSTRAINT PK_DM_DEVICE_TYPE PRIMARY KEY (ID) ) / diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index a1581e19d3..ef531b5a2a 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -1,6 +1,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( ID BIGSERIAL PRIMARY KEY, - NAME VARCHAR(300) DEFAULT NULL + NAME VARCHAR(300) DEFAULT NULL, + PROVIDER_TENANT_ID INTEGER DEFAULT 0, + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE ); CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( From 284a6645f03f7ef3731ecb41948facc2db75440b Mon Sep 17 00:00:00 2001 From: ayyoob Date: Tue, 29 Mar 2016 12:07:58 +0530 Subject: [PATCH 02/10] import required packages --- components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index 00640f76d4..2268272531 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -83,7 +83,8 @@ org.apache.catalina.core, org.apache.commons.collections, org.wso2.carbon.email.sender.*, - org.wso2.carbon + org.wso2.carbon, + org.wso2.carbon.base !org.wso2.carbon.device.mgt.core.internal, From 026d4ef01860262e7c2c316f74c54280a8f25d79 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Wed, 30 Mar 2016 12:17:46 +0530 Subject: [PATCH 03/10] removed analytics --- .../pom.xml | 144 ------------------ 1 file changed, 144 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.analytics/pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics/pom.xml deleted file mode 100644 index f7c66fd190..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics/pom.xml +++ /dev/null @@ -1,144 +0,0 @@ - - - - - - - org.wso2.carbon.devicemgt - device-mgt - 1.1.0-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.device.mgt.analytics - 1.1.0-SNAPSHOT - bundle - WSO2 Carbon - Device Analytics - WSO2 Carbon - Device Analytics - http://wso2.org - - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.testng - testng - - - org.wso2.tomcat - tomcat - - - org.wso2.tomcat - tomcat-servlet-api - - - org.wso2.carbon - org.wso2.carbon.core - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon - org.wso2.carbon.utils - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - - - org.wso2.carbon.analytics-common - org.wso2.carbon.databridge.agent - - - org.wso2.carbon.analytics-common - org.wso2.carbon.databridge.commons - - - org.wso2.carbon.analytics - org.wso2.carbon.analytics.api - - - org.wso2.carbon.registry - org.wso2.carbon.registry.indexing - - - org.json.wso2 - json - - - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - 1.4.0 - true - - - ${project.artifactId} - ${project.artifactId} - ${carbon.device.mgt.version} - Data Publisher - org.wso2.carbon.device.mgt.analytics.internal - - !org.wso2.carbon.device.mgt.analytics.internal, - org.wso2.carbon.device.mgt.analytics.*;version="${carbon.device.mgt.version}" - - - org.osgi.framework, - org.osgi.service.component, - org.apache.commons.logging.*, - org.wso2.carbon.context;version="${carbon.kernel.version.range}", - org.wso2.carbon.utils;version="${carbon.kernel.version.range}", - org.wso2.carbon.databridge.*;version="${carbon.analytics.common.version.range}", - org.wso2.carbon.analytics.*;version="${carbon.analytics.version.range}", - org.wso2.carbon.registry.core.*;resolution:=optional, - org.wso2.carbon.registry.common.*;version="${carbon.registry.imp.pkg.version.range}", - org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}", - org.json;version="${commons-json.version}", - javax.xml.bind, - javax.xml.bind.annotation, - javax.xml.parsers, - org.w3c.dom, - org.wso2.carbon.base - - - - - - - - \ No newline at end of file From fc725fa76749432c36ce1703ab4e489a0f1ce32a Mon Sep 17 00:00:00 2001 From: ayyoob Date: Wed, 30 Mar 2016 13:45:39 +0530 Subject: [PATCH 04/10] removed analytics --- components/device-mgt/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index 1de382fbd3..4938424351 100644 --- a/components/device-mgt/pom.xml +++ b/components/device-mgt/pom.xml @@ -39,7 +39,6 @@ org.wso2.carbon.device.mgt.common org.wso2.carbon.device.mgt.extensions org.wso2.carbon.device.mgt.ui - org.wso2.carbon.device.mgt.analytics org.wso2.carbon.device.mgt.analytics.data.publisher org.wso2.carbon.device.mgt.etc From 73a82f743f359a440e1e2e545e20dc99ada22778 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Wed, 30 Mar 2016 23:56:44 +0530 Subject: [PATCH 05/10] Adding the changes for device Info bean to stop returing null values and changes done for Device search unit classes --- .../mgt/common/device/details/DeviceInfo.java | 106 ++++++++++++++---- .../impl/DeviceInformationManagerImpl.java | 6 + .../device/mgt/core/Search/SearchDevice.java | 6 +- .../device/mgt/core/Search/util/Utils.java | 17 +-- 4 files changed, 108 insertions(+), 27 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java index 454608b915..dc6bcd886a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java @@ -25,7 +25,7 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; -public class DeviceInfo implements Serializable{ +public class DeviceInfo implements Serializable { private static final long serialVersionUID = 1998101733L; @@ -79,7 +79,11 @@ public class DeviceInfo implements Serializable{ } public String getIMEI() { - return IMEI; + if (IMEI != null) { + return IMEI; + } else { + return ""; + } } public void setIMEI(String IMEI) { @@ -87,7 +91,11 @@ public class DeviceInfo implements Serializable{ } public String getIMSI() { - return IMSI; + if (IMSI != null) { + return IMSI; + } else { + return ""; + } } public void setIMSI(String IMSI) { @@ -95,7 +103,11 @@ public class DeviceInfo implements Serializable{ } public String getDeviceModel() { - return deviceModel; + if (deviceModel != null) { + return deviceModel; + } else { + return ""; + } } public void setDeviceModel(String deviceModel) { @@ -103,7 +115,11 @@ public class DeviceInfo implements Serializable{ } public String getVendor() { - return vendor; + if (vendor != null) { + return vendor; + } else { + return ""; + } } public void setVendor(String vendor) { @@ -111,7 +127,11 @@ public class DeviceInfo implements Serializable{ } public String getOsVersion() { - return osVersion; + if (osVersion != null) { + return osVersion; + } else { + return ""; + } } public void setOsVersion(String osVersion) { @@ -119,7 +139,11 @@ public class DeviceInfo implements Serializable{ } public Double getBatteryLevel() { - return batteryLevel; + if (batteryLevel != null) { + return batteryLevel; + } else { + return 0.0; + } } public void setBatteryLevel(Double batteryLevel) { @@ -127,7 +151,11 @@ public class DeviceInfo implements Serializable{ } public Double getInternalTotalMemory() { - return internalTotalMemory; + if (internalTotalMemory != null) { + return internalTotalMemory; + } else { + return 0.0; + } } public void setInternalTotalMemory(Double internalTotalMemory) { @@ -135,7 +163,11 @@ public class DeviceInfo implements Serializable{ } public Double getInternalAvailableMemory() { - return internalAvailableMemory; + if (internalAvailableMemory != null) { + return internalAvailableMemory; + } else { + return 0.0; + } } public void setInternalAvailableMemory(Double internalAvailableMemory) { @@ -143,7 +175,11 @@ public class DeviceInfo implements Serializable{ } public Double getExternalTotalMemory() { - return externalTotalMemory; + if (externalTotalMemory != null) { + return externalTotalMemory; + } else { + return 0.0; + } } public void setExternalTotalMemory(Double externalTotalMemory) { @@ -151,7 +187,11 @@ public class DeviceInfo implements Serializable{ } public Double getExternalAvailableMemory() { - return externalAvailableMemory; + if (externalAvailableMemory != null) { + return externalAvailableMemory; + } else { + return 0.0; + } } public void setExternalAvailableMemory(Double externalAvailableMemory) { @@ -159,7 +199,11 @@ public class DeviceInfo implements Serializable{ } public String getOperator() { - return operator; + if (operator != null) { + return operator; + } else { + return ""; + } } public void setOperator(String operator) { @@ -167,7 +211,11 @@ public class DeviceInfo implements Serializable{ } public String getConnectionType() { - return connectionType; + if (connectionType != null) { + return connectionType; + } else { + return ""; + } } public void setConnectionType(String connectionType) { @@ -175,7 +223,11 @@ public class DeviceInfo implements Serializable{ } public Double getMobileSignalStrength() { - return mobileSignalStrength; + if (mobileSignalStrength != null) { + return mobileSignalStrength; + } else { + return 0.0; + } } public void setMobileSignalStrength(Double mobileSignalStrength) { @@ -183,7 +235,11 @@ public class DeviceInfo implements Serializable{ } public String getSsid() { - return ssid; + if (ssid != null) { + return ssid; + } else { + return ""; + } } public void setSsid(String ssid) { @@ -191,7 +247,11 @@ public class DeviceInfo implements Serializable{ } public Double getCpuUsage() { - return cpuUsage; + if (cpuUsage != null) { + return cpuUsage; + } else { + return 0.0; + } } public void setCpuUsage(Double cpuUsage) { @@ -199,7 +259,11 @@ public class DeviceInfo implements Serializable{ } public Double getTotalRAMMemory() { - return totalRAMMemory; + if (totalRAMMemory != null) { + return totalRAMMemory; + } else { + return 0.0; + } } public void setTotalRAMMemory(Double totalRAMMemory) { @@ -207,7 +271,11 @@ public class DeviceInfo implements Serializable{ } public Double getAvailableRAMMemory() { - return availableRAMMemory; + if (availableRAMMemory != null) { + return availableRAMMemory; + } else { + return 0.0; + } } public void setAvailableRAMMemory(Double availableRAMMemory) { @@ -222,7 +290,7 @@ public class DeviceInfo implements Serializable{ this.pluggedIn = pluggedIn; } - public void setDeviceDetailsMap(Map deviceDetailsMap) { + public void setDeviceDetailsMap(Map deviceDetailsMap) { this.deviceDetailsMap = deviceDetailsMap; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index d5111df20d..fb7e163767 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -101,6 +101,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { public void addDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException { try { + Device device = DeviceManagementDataHolder.getInstance(). + getDeviceManagementProvider().getDevice(deviceLocation.getDeviceIdentifier()); + deviceLocation.setDeviceId(device.getId()); DeviceManagementDAOFactory.beginTransaction(); deviceDetailsDAO.deleteDeviceLocation(deviceLocation.getDeviceId()); deviceDetailsDAO.addDeviceLocation(deviceLocation); @@ -111,6 +114,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } catch (DeviceDetailsMgtDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Error occurred while adding the device location information."); + } catch (DeviceManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + throw new DeviceDetailsMgtException("Error occurred while getting the device information."); } finally { DeviceManagementDAOFactory.closeConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java index c6904ea66c..bab5f5b228 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java @@ -27,8 +27,11 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; import org.wso2.carbon.device.mgt.common.search.Condition; import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import java.util.ArrayList; import java.util.List; @@ -40,7 +43,8 @@ public class SearchDevice extends BaseDeviceManagementTest { @BeforeClass @Override public void init() throws Exception { - + DeviceManagementProviderService deviceManagementProviderService = new DeviceManagementProviderServiceImpl(); + DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProviderService); } @Test diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java index 4a21cf9637..80a8ec4439 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java @@ -34,13 +34,7 @@ public class Utils { DeviceInfo deviceInfo = new DeviceInfo(); - - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setType(TestDataHolder.TEST_DEVICE_TYPE); - deviceIdentifier.setId("12345"); - - - deviceInfo.setDeviceIdentifier(deviceIdentifier); + deviceInfo.setDeviceIdentifier(Utils.getDeviceIdentifier()); deviceInfo.setDeviceId(1); deviceInfo.setIMSI("e6f236ac82537a8e"); @@ -88,6 +82,7 @@ public class Utils { DeviceLocation deviceLocation = new DeviceLocation(); + deviceLocation.setDeviceIdentifier(Utils.getDeviceIdentifier()); deviceLocation.setLatitude(76.2422); deviceLocation.setLongitude(81.43); deviceLocation.setStreet1("4"); @@ -100,6 +95,14 @@ public class Utils { return deviceLocation; } + + private static DeviceIdentifier getDeviceIdentifier(){ + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setType(TestDataHolder.TEST_DEVICE_TYPE); + deviceIdentifier.setId("12345"); + + return deviceIdentifier; + } } From 562ced1be761b6b8ef56885584217141bd812d08 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Thu, 31 Mar 2016 00:10:40 +0530 Subject: [PATCH 06/10] Added api application extension feature --- .../pom.xml | 134 ++++++++++++++++++ .../src/main/resources/build.properties | 1 + .../src/main/resources/p2.inf | 3 + features/apimgt-extensions/pom.xml | 1 + 4 files changed, 139 insertions(+) create mode 100644 features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml create mode 100644 features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/build.properties create mode 100644 features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/p2.inf diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml new file mode 100644 index 0000000000..63046f0ebd --- /dev/null +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml @@ -0,0 +1,134 @@ + + + + + + org.wso2.carbon.devicemgt + apimgt-extensions-feature + 1.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.apimgt.application.extension.feature + pom + 1.1.0-SNAPSHOT + WSO2 Carbon - API Management Application Extension Feature + http://wso2.org + This feature contains an implementation of a api application registration, which takes care of subscription + and generating keys. + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.application.extension + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-jaxrs-war + package + + copy + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.application.extension.api + war + true + ${project.build.directory}/maven-shared-archive-resources/webapps/ + api-application-registration.war + + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.carbon.apimgt.application.extension + ../../../features/etc/feature.properties + + + org.wso2.carbon.p2.category.type:server + org.eclipse.equinox.p2.type.group:false + + + + + org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.application.extension:${carbon.device.mgt.version} + + + + org.wso2.carbon.core.server:${carbon.kernel.version} + + + + + + + + + \ No newline at end of file diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/build.properties b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/build.properties new file mode 100644 index 0000000000..93c4b10701 --- /dev/null +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/build.properties @@ -0,0 +1 @@ +custom = true \ No newline at end of file diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/p2.inf b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/p2.inf new file mode 100644 index 0000000000..1d8124571f --- /dev/null +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/p2.inf @@ -0,0 +1,3 @@ +instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.apimgt.application.extension_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\ \ No newline at end of file diff --git a/features/apimgt-extensions/pom.xml b/features/apimgt-extensions/pom.xml index 8225ffc41e..c4a0b1bf82 100644 --- a/features/apimgt-extensions/pom.xml +++ b/features/apimgt-extensions/pom.xml @@ -36,6 +36,7 @@ org.wso2.carbon.apimgt.webapp.publisher.feature + org.wso2.carbon.apimgt.application.extension.feature From 1b4a9227d8779a9469c95e8c3ebee727cec10600 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Thu, 31 Mar 2016 04:24:30 +0530 Subject: [PATCH 07/10] merged web app publisher code and refactored jwt client extension to adhere to new artefact name --- .../pom.xml | 64 +++- .../apimgt/webapp/publisher/APIConfig.java | 61 +++- .../webapp/publisher/APIPublisherService.java | 7 +- .../publisher/APIPublisherServiceImpl.java | 96 ++++-- .../webapp/publisher/APIPublisherUtil.java | 122 +++++-- .../webapp/publisher/config/APIResource.java | 87 +++++ .../config/APIResourceConfiguration.java | 79 +++++ .../APIResourceManagementException.java | 38 +++ .../publisher/config/APIResourceManager.java | 69 ++++ .../internal/APIPublisherDataHolder.java | 37 ++ .../APIPublisherServiceComponent.java | 38 +++ .../APIPublisherLifecycleListener.java | 322 +++++++++++------- .../lifecycle/util/AnnotationUtil.java | 265 ++++++++++++++ .../pom.xml | 2 +- .../pom.xml | 6 +- .../jwt/client/extension/JWTClient.java | 12 +- .../client/extension/JWTClientManager.java | 12 +- .../extension/constant/JWTConstants.java | 2 +- .../client/extension/dto/AccessTokenInfo.java | 2 +- .../jwt/client/extension/dto/JWTConfig.java | 2 +- .../JWTClientAlreadyExistsException.java | 2 +- .../JWTClientConfigurationException.java | 2 +- .../exception/JWTClientException.java | 2 +- .../JWTClientExtensionDataHolder.java | 2 +- .../JWTClientExtensionServiceComponent.java | 6 +- .../client/extension/util/JWTClientUtil.java | 4 +- .../src/main/resources/p2.inf | 2 +- pom.xml | 5 + 28 files changed, 1137 insertions(+), 211 deletions(-) create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResource.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceConfiguration.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManagementException.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManager.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index 0102e4414e..7da850e7a9 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -1,5 +1,25 @@ - + + + apimgt-extensions @@ -61,6 +81,30 @@ org.apache.axis2.wso2 axis2 + + com.google.code.gson + gson + + + org.wso2.orbit.org.scannotation + scannotation + + + javax.ws.rs + jsr311-api + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + + + org.wso2.carbon.governance + org.wso2.carbon.governance.api + + + org.wso2.carbon.governance + org.wso2.carbon.governance.lcm + @@ -81,7 +125,8 @@ ${project.artifactId} ${carbon.device.mgt.version} API Management Webapp Publisher - org.wso2.carbon.apimgt.webapp.publisher.internal + org.wso2.carbon.apimgt.webapp.publisher.internal + !org.wso2.carbon.apimgt.webapp.publisher.internal, org.wso2.carbon.apimgt.webapp.publisher.* @@ -91,7 +136,8 @@ org.osgi.service.component, org.apache.commons.logging, javax.servlet, - javax.xml.bind.annotation, + javax.xml.*, + com.google.gson.*, org.apache.catalina, org.apache.catalina.core, org.wso2.carbon.apimgt.api, @@ -99,12 +145,20 @@ org.wso2.carbon.apimgt.impl, org.apache.axis2.*;version="${axis2.osgi.version.range}", org.wso2.carbon.core, - org.wso2.carbon.utils + org.apache.commons.lang, + org.wso2.carbon.utils, + org.wso2.carbon.apimgt.annotations.*, + org.wso2.carbon.governance.lcm.util.*, + org.wso2.carbon.registry.core.* + + scribe;scope=compile|runtime;inline=false; + + * - + \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIConfig.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIConfig.java index 4d5c661105..c71a0cba5b 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIConfig.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIConfig.java @@ -20,11 +20,16 @@ package org.wso2.carbon.apimgt.webapp.publisher; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; +import org.wso2.carbon.apimgt.api.model.URITemplate; +import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerFactory; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; +import java.util.List; +import java.util.Set; /** * This bean class carries the properties used by some API that needs to be published within the underlying @@ -48,20 +53,35 @@ public class APIConfig { private String name; private String owner; private String context; + private String contextTemplate; private String endpoint; private String version; private String transports; private APIProvider provider; private boolean isSecured; + private Set uriTemplates; + private List tenants; + private boolean isSharedWithAllTenants; + private String tenantDomain; + private String[] tags; public void init() throws APIManagementException { try { - this.provider = APIManagerFactory.getInstance().getAPIProvider(this.getOwner()); + this.provider = APIManagerFactory.getInstance().getAPIProvider(owner); } catch (APIManagementException e) { throw new APIManagementException("Error occurred while initializing API provider", e); } } + @XmlElement(name = "ContextTemplate", required = true) + public String getContextTemplate() { + return contextTemplate; + } + + public void setContextTemplate(String contextTemplate) { + this.contextTemplate = contextTemplate; + } + @XmlTransient public APIProvider getProvider() { return provider; @@ -136,4 +156,43 @@ public class APIConfig { isSecured = secured; } + @XmlElement(name = "UriTemplates", required = false) + public Set getUriTemplates() { + return uriTemplates; + } + + @SuppressWarnings("unused") + public void setUriTemplates(Set uriTemplates) { + this.uriTemplates = uriTemplates; + } + + @XmlElement(name = "isSharedWithAllTenants", required = false) + public boolean isSharedWithAllTenants() { + return isSharedWithAllTenants; + } + + @SuppressWarnings("unused") + public void setSharedWithAllTenants(boolean isSharedWithAllTenants) { + this.isSharedWithAllTenants = isSharedWithAllTenants; + } + + @XmlElement(name = "tenantDomain", required = false) + public String getTenantDomain() { + return tenantDomain; + } + + @SuppressWarnings("unused") + public void setTenantDomain(String tenantDomain) { + this.tenantDomain = tenantDomain; + } + + @XmlElement(name = "tags", required = false) + public String[] getTags() { + return tags; + } + + @SuppressWarnings("unused") + public void setTags(String[] tags) { + this.tags = tags; + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java index 32cb28f38d..c41a684968 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherService.java @@ -19,9 +19,9 @@ package org.wso2.carbon.apimgt.webapp.publisher; import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; - import java.util.List; /** @@ -39,7 +39,7 @@ public interface APIPublisherService { * @param api An instance of the bean that passes metadata related to the API being published * @throws APIManagementException Is thrown if some unexpected event occurs while publishing the API */ - void publishAPI(API api) throws APIManagementException; + void publishAPI(API api) throws APIManagementException, FaultGatewaysException; /** * This method removes an API that's already published within the underlying API-Management infrastructure. @@ -55,6 +55,5 @@ public interface APIPublisherService { * @param apis A list of the beans that passes metadata related to the APIs being published * @throws APIManagementException Is thrown if some unexpected event occurs while publishing the APIs */ - void publishAPIs(List apis) throws APIManagementException; - + void publishAPIs(List apis) throws APIManagementException, FaultGatewaysException; } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index 6d1eb4c3a9..dae050d1d7 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.apimgt.webapp.publisher; +import com.google.gson.JsonObject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.APIManagementException; @@ -25,8 +26,17 @@ import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.URITemplate; import org.wso2.carbon.apimgt.impl.APIManagerFactory; +import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; +import org.wso2.carbon.governance.lcm.util.CommonUtil; +import org.wso2.carbon.registry.core.exceptions.RegistryException; +import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import javax.xml.stream.XMLStreamException; +import java.io.FileNotFoundException; import java.util.List; /** @@ -38,33 +48,82 @@ public class APIPublisherServiceImpl implements APIPublisherService { private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class); @Override - public void publishAPI(API api) throws APIManagementException { + public void publishAPI(API api) throws APIManagementException, FaultGatewaysException { if (log.isDebugEnabled()) { log.debug("Publishing API '" + api.getId() + "'"); } - APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner()); - if (provider != null) { - if (!provider.isAPIAvailable(api.getId())) { - provider.addAPI(api); - log.info("Successfully published API '" + api.getId().getApiName() + "' with context '" + - api.getContext() + "' and version '" + api.getId().getVersion() + "'"); - } else { - try { + try { + String tenantDomain = MultitenantUtils.getTenantDomain(api.getApiOwner()); + int tenantId = + APIPublisherDataHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain); + // Below code snippet is added load API Lifecycle in tenant mode, where in it does not load when tenant is loaded. + RegistryService registryService = APIPublisherDataHolder.getInstance().getRegistryService(); + CommonUtil.addDefaultLifecyclesIfNotAvailable(registryService.getConfigSystemRegistry(tenantId), + CommonUtil.getRootSystemRegistry(tenantId)); + APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner()); + MultitenantUtils.getTenantDomain(api.getApiOwner()); + if (provider != null) { + if (!provider.isAPIAvailable(api.getId())) { + provider.addAPI(api); + log.info("Successfully published API '" + api.getId().getApiName() + "' with context '" + + api.getContext() + "' and version '" + api.getId().getVersion() + "'"); + } else { provider.updateAPI(api); log.info("An API already exists with the name '" + api.getId().getApiName() + "', context '" + - api.getContext() + "' and version '" + api.getId().getVersion() + - "'. Thus, the API config is updated"); - } catch (FaultGatewaysException e) { - throw new APIManagementException("Error occurred while updating API " + api.getId().getApiName() + - "' with context '" + api.getContext() + "' and version '" + api.getId().getVersion() + "'"); + api.getContext() + "' and version '" + api.getId().getVersion() + + "'. Thus, the API config is updated"); } + provider.saveSwagger20Definition(api.getId(), createSwaggerDefinition(api)); + } else { + throw new APIManagementException("API provider configured for the given API configuration is null. " + + "Thus, the API is not published"); } - } else { - throw new APIManagementException("API provider configured for the given API configuration is null. " + - "Thus, the API is not published"); + } catch (UserStoreException e) { + throw new APIManagementException("Failed to get the tenant id for the user " + api.getApiOwner(), e); + } catch (FileNotFoundException e) { + throw new APIManagementException("Failed to retrieve life cycle file ", e); + } catch (RegistryException e) { + throw new APIManagementException("Failed to access the registry ", e); + } catch (XMLStreamException e) { + throw new APIManagementException("Failed parsing the lifecycle xml.", e); } } + private String createSwaggerDefinition(API api) { + //{"paths":{"/controller/*":{"get":{"responses":{"200":{}}}},"/manager/*":{"get":{"responses":{"200":{}}}}}, + // "swagger":"2.0","info":{"title":"RaspberryPi","version":"1.0.0"}} + JsonObject swaggerDefinition = new JsonObject(); + + JsonObject paths = new JsonObject(); + for (URITemplate uriTemplate : api.getUriTemplates()) { + JsonObject response = new JsonObject(); + response.addProperty("200", ""); + + JsonObject responses = new JsonObject(); + responses.add("responses", response); + + JsonObject httpVerb = new JsonObject(); + httpVerb.add(uriTemplate.getHTTPVerb().toLowerCase(), responses); + + JsonObject path = new JsonObject(); + path.add(uriTemplate.getUriTemplate(), httpVerb); + + paths.add(uriTemplate.getUriTemplate(), httpVerb); + } + swaggerDefinition.add("paths", paths); + swaggerDefinition.addProperty("swagger", "2.0"); + + JsonObject info = new JsonObject(); + info.addProperty("title", api.getId().getApiName()); + info.addProperty("version", api.getId().getVersion()); + swaggerDefinition.add("info", info); + + return swaggerDefinition.toString(); + //return "{\"paths\":{\"/controller/*\":{\"get\":{\"responses\":{\"200\":{}}}}, + // \"/manager/*\":{\"get\":{\"responses\":{\"200\":{}}}}},\"swagger\":\"2.0\", + // \"info\":{\"title\":\"RaspberryPi\",\"version\":\"1.0.0\"}}"; + } + @Override public void removeAPI(APIIdentifier id) throws APIManagementException { if (log.isDebugEnabled()) { @@ -78,7 +137,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { } @Override - public void publishAPIs(List apis) throws APIManagementException { + public void publishAPIs(List apis) throws APIManagementException, FaultGatewaysException { if (log.isDebugEnabled()) { log.debug("Publishing a batch of APIs"); } @@ -93,5 +152,4 @@ public class APIPublisherServiceImpl implements APIPublisherService { log.debug("End of publishing the batch of APIs"); } } - } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java index 65ab0d46de..2a502825ad 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java @@ -1,42 +1,43 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * 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. + * 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.apimgt.webapp.publisher; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; -import org.wso2.carbon.apimgt.api.model.API; -import org.wso2.carbon.apimgt.api.model.APIIdentifier; -import org.wso2.carbon.apimgt.api.model.APIStatus; -import org.wso2.carbon.apimgt.api.model.URITemplate; +import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.user.api.TenantManager; +import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.NetworkUtils; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import java.util.*; public class APIPublisherUtil { + private static final String DEFAULT_API_VERSION = "1.0.0"; + public static final String API_VERSION_PARAM="{version}"; + enum HTTPMethod { GET, POST, DELETE, PUT, OPTIONS } @@ -54,21 +55,53 @@ public class APIPublisherUtil { public static API getAPI(APIConfig config) throws APIManagementException { APIProvider provider = config.getProvider(); - APIIdentifier id = new APIIdentifier(config.getOwner(), config.getName(), config.getVersion()); - + String apiVersion = config.getVersion(); + APIIdentifier id = new APIIdentifier(replaceEmailDomain(config.getOwner()), config.getName(), apiVersion); API api = new API(id); api.setApiOwner(config.getOwner()); - api.setContext(config.getContext()); + String context = config.getContext(); + context = context.startsWith("/") ? context : ("/" + context); + String providerDomain = config.getTenantDomain(); + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain)) { + //Create tenant aware context for API + context = "/t/" + providerDomain + context; + } + // This is to support the new Pluggable version strategy + // if the context does not contain any {version} segment, we use the default version strategy. + context = checkAndSetVersionParam(context); + api.setContextTemplate(context); + context = updateContextWithVersion(config.getVersion(), context); + api.setContext(context); api.setUrl(config.getEndpoint()); - api.setUriTemplates( - getURITemplates(config.getEndpoint(), APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN)); - api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY); api.addAvailableTiers(provider.getTiers()); api.setEndpointSecured(true); api.setStatus(APIStatus.PUBLISHED); api.setTransports(config.getTransports()); - api.setAsDefaultVersion(true); - api.setAsPublishedDefaultVersion(true); + api.setContextTemplate(config.getContextTemplate()); + api.setUriTemplates(config.getUriTemplates()); + Set tiers = new HashSet(); + tiers.add(new Tier(APIConstants.UNLIMITED_TIER)); + api.addAvailableTiers(tiers); + if (config.isSharedWithAllTenants()) { + api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_ALL_TENANTS); + api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY); + } else { + api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_CURRENT_TENANT); + api.setVisibility(APIConstants.API_PRIVATE_VISIBILITY); + } + api.setResponseCache(APIConstants.DISABLED); + + String endpointConfig = "{\"production_endpoints\":{\"url\":\" " + config.getEndpoint() + "\",\"config\":null},\"endpoint_type\":\"http\"}"; + api.setEndpointConfig(endpointConfig); + + if ("".equals(id.getVersion()) || (DEFAULT_API_VERSION.equals(id.getVersion()))) { + api.setAsDefaultVersion(Boolean.TRUE); + api.setAsPublishedDefaultVersion(Boolean.TRUE); + } + if (config.getTags() != null && config.getTags().length > 0) { + Set tags = new HashSet<>(Arrays.asList(config.getTags())); + api.addTags(tags); + } return api; } @@ -125,4 +158,35 @@ public class APIPublisherUtil { return getServerBaseUrl() + context; } + /** + * When an input is having '@',replace it with '-AT-' [This is required to persist API data in registry,as registry paths don't allow '@' sign.] + * @param input inputString + * @return String modifiedString + */ + private static String replaceEmailDomain(String input){ + if(input!=null&& input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR) ){ + input=input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR,APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT); + } + return input; + } + + private static String updateContextWithVersion(String version, String context) { + // This condition should not be true for any occasion but we keep it so that there are no loopholes in + // the flow. + context = context.replace(API_VERSION_PARAM, version); + return context; + } + + private static String checkAndSetVersionParam(String context) { + // This is to support the new Pluggable version strategy + // if the context does not contain any {version} segment, we use the default version strategy. + if(!context.contains(API_VERSION_PARAM)){ + if(!context.endsWith("/")){ + context = context + "/"; + } + context = context +API_VERSION_PARAM; + } + return context; + } + } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResource.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResource.java new file mode 100644 index 0000000000..2f28fbe6a5 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResource.java @@ -0,0 +1,87 @@ +/* + * 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.apimgt.webapp.publisher.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "Resource") +public class APIResource{ + + private String AuthType; + private String HttpVerb; + private String Uri; + private String UriTemplate; + private String consumes; + private String produces; + + public String getAuthType() { + return AuthType; + } + + @XmlElement(name = "AuthType", required = true) + public void setAuthType(String authType) { + AuthType = authType; + } + + public String getHttpVerb() { + return HttpVerb; + } + + @XmlElement(name = "HttpVerb", required = true) + public void setHttpVerb(String httpVerb) { + HttpVerb = httpVerb; + } + + public String getUri() { + return Uri; + } + + @XmlElement(name = "Uri", required = true) + public void setUri(String uri) { + Uri = uri; + } + + public String getUriTemplate() { + return UriTemplate; + } + + @XmlElement(name = "UriTemplate", required = true) + public void setUriTemplate(String uriTemplate) { + UriTemplate = uriTemplate; + } + + public String getConsumes() { + return consumes; + } + + @XmlElement(name = "Consumes", required = true) + public void setConsumes(String consumes) { + this.consumes = consumes; + } + + public String getProduces() { + return produces; + } + + @XmlElement(name = "Produces", required = true) + public void setProduces(String produces) { + this.produces = produces; + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceConfiguration.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceConfiguration.java new file mode 100644 index 0000000000..f25668fadb --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceConfiguration.java @@ -0,0 +1,79 @@ +/* + * 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.apimgt.webapp.publisher.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "ResourceConfiguration") +public class APIResourceConfiguration { + + private String name; + private String context; + private String version; + private List resources; + private String[] tags; + + public List getResources() { + return resources; + } + + @XmlElement(name = "Resources", required = true) + public void setResources(List resources) { + this.resources = resources; + } + + public String getContext() { + return context; + } + + @XmlElement(name = "Context", required = true) + public void setContext(String context) { + this.context = context; + } + + public String getName() { + return name; + } + + @XmlElement(name = "Name") + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + @XmlElement(name = "Version") + public void setVersion(String version) { + this.version = version; + } + + public String[] getTags() { + return tags; + } + + @XmlElement(name = "Tags") + public void setTags(String[] tags) { + this.tags = tags; + } + +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManagementException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManagementException.java new file mode 100644 index 0000000000..1007c50026 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManagementException.java @@ -0,0 +1,38 @@ +package org.wso2.carbon.apimgt.webapp.publisher.config; + +public class APIResourceManagementException extends Exception{ + private static final long serialVersionUID = -3151279311929070297L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public APIResourceManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public APIResourceManagementException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public APIResourceManagementException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public APIResourceManagementException() { + super(); + } + + public APIResourceManagementException(Throwable cause) { + super(cause); + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManager.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManager.java new file mode 100644 index 0000000000..c1f88d83ab --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManager.java @@ -0,0 +1,69 @@ +/* + * 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.apimgt.webapp.publisher.config; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.InputStream; +import java.util.List; +import java.util.Set; + +/** + * This class will add, update custom permissions defined in resources.xml in webapps. + */ +public class APIResourceManager { + + private static APIResourceManager resourceManager; + private List resourceList; + + private APIResourceManager(){}; + + public static APIResourceManager getInstance() { + if (resourceManager == null) { + synchronized (APIResourceManager.class) { + if (resourceManager == null) { + resourceManager = new APIResourceManager(); + } + } + } + return resourceManager; + } + + public void initializeResources(InputStream resourceStream) throws APIResourceManagementException { + try { + if(resourceStream != null){ + /* Un-marshaling Device Management configuration */ + JAXBContext cdmContext = JAXBContext.newInstance(APIResourceConfiguration.class); + Unmarshaller unmarshaller = cdmContext.createUnmarshaller(); + APIResourceConfiguration resourcesConfiguration = (APIResourceConfiguration) + unmarshaller.unmarshal(resourceStream); + if((resourcesConfiguration != null) && (resourcesConfiguration.getResources() != null)){ + this.resourceList = resourcesConfiguration.getResources(); + } + } + } catch (JAXBException e) { + throw new APIResourceManagementException("Error occurred while initializing Data Source config", e); + } + } + + public List getAPIResources(){ + return resourceList; + } +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java index d5b4d5e15c..bd291ce3be 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java @@ -18,13 +18,20 @@ */ package org.wso2.carbon.apimgt.webapp.publisher.internal; + import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; +import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.user.core.service.RealmService; +import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.ConfigurationContextService; public class APIPublisherDataHolder { private APIPublisherService apiPublisherService; private ConfigurationContextService configurationContextService; + private RealmService realmService; + private TenantManager tenantManager; + private RegistryService registryService; private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder(); @@ -57,4 +64,34 @@ public class APIPublisherDataHolder { return configurationContextService; } + public RealmService getRealmService() { + if (realmService == null) { + throw new IllegalStateException("Realm service is not initialized properly"); + } + 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 RegistryService getRegistryService() { + return registryService; + } + + public void setRegistryService(RegistryService registryService) { + this.registryService = registryService; + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java index 6d2344a14f..10a20d9a48 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java @@ -25,6 +25,8 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl; +import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.ConfigurationContextService; /** @@ -35,6 +37,18 @@ import org.wso2.carbon.utils.ConfigurationContextService; * policy="dynamic" * bind="setConfigurationContextService" * unbind="unsetConfigurationContextService" + * @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="registry.service" + * interface="org.wso2.carbon.registry.core.service.RegistryService" + * cardinality="1..1" + * policy="dynamic" + * bind="setRegistryService" + * unbind="unsetRegistryService" */ public class APIPublisherServiceComponent { @@ -95,4 +109,28 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setConfigurationContextService(null); } + protected void setRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Setting Realm Service"); + } + APIPublisherDataHolder.getInstance().setRealmService(realmService); + } + + protected void unsetRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Realm Service"); + } + APIPublisherDataHolder.getInstance().setRealmService(null); + } + + protected void setRegistryService(RegistryService registryService) { + if (registryService != null && log.isDebugEnabled()) { + log.debug("Registry service initialized"); + } + APIPublisherDataHolder.getInstance().setRegistryService(registryService); + } + + protected void unsetRegistryService(RegistryService registryService) { + APIPublisherDataHolder.getInstance().setRegistryService(null); + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java index 1c425b3c4e..a611a321ea 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java @@ -24,135 +24,209 @@ import org.apache.catalina.LifecycleListener; import org.apache.catalina.core.StandardContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.api.model.API; -import org.wso2.carbon.apimgt.webapp.publisher.APIConfig; -import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; -import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil; +import org.wso2.carbon.apimgt.api.model.*; +import org.wso2.carbon.apimgt.webapp.publisher.*; +import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource; +import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; - +import org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationUtil; +import org.wso2.carbon.base.MultitenantConstants; import javax.servlet.ServletContext; +import java.io.IOException; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; @SuppressWarnings("unused") public class APIPublisherLifecycleListener implements LifecycleListener { - private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0"; - - private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled"; - private static final String PARAM_MANAGED_API_NAME = "managed-api-name"; - private static final String PARAM_MANAGED_API_VERSION = "managed-api-version"; - private static final String PARAM_MANAGED_API_CONTEXT = "managed-api-context"; - private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint"; - private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner"; - private static final String PARAM_MANAGED_API_TRANSPORTS = "managed-api-transports"; - private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured"; - - private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class); - - @Override - public void lifecycleEvent(LifecycleEvent lifecycleEvent) { - if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { - StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); - ServletContext servletContext = context.getServletContext(); - - - String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); - boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); - - if (isManagedApi) { - APIConfig apiConfig = this.buildApiConfig(servletContext); - try { - apiConfig.init(); - API api = APIPublisherUtil.getAPI(apiConfig); - APIPublisherService apiPublisherService = - APIPublisherDataHolder.getInstance().getApiPublisherService(); - if (apiPublisherService == null) { - throw new IllegalStateException("API Publisher service is not initialized properly"); - } - apiPublisherService.publishAPI(api); - } catch (Throwable e) { - /* Throwable is caught as none of the RuntimeExceptions that can potentially occur at this point - does not seem to be logged anywhere else within the framework */ - log.error("Error occurred while publishing API '" + apiConfig.getName() + "' with the context '" + - apiConfig.getContext() + "' and version '" + apiConfig.getVersion() + "'", e); - } - } - } - } - - private APIConfig buildApiConfig(ServletContext servletContext) { - APIConfig apiConfig = new APIConfig(); - - String name = servletContext.getInitParameter(PARAM_MANAGED_API_NAME); - if (name == null || name.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("'managed-api-name' attribute is not configured. Therefore, using the default, " + - "which is the name of the web application"); - } - name = servletContext.getServletContextName(); - } - apiConfig.setName(name); - - String version = servletContext.getInitParameter(PARAM_MANAGED_API_VERSION); - if (version == null || version.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("'managed-api-version' attribute is not configured. Therefore, using the " + - "default, which is '1.0.0'"); - } - version = API_CONFIG_DEFAULT_VERSION; - } - apiConfig.setVersion(version); - - String context = servletContext.getInitParameter(PARAM_MANAGED_API_CONTEXT); - if (context == null || context.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("'managed-api-context' attribute is not configured. Therefore, using the default, " + - "which is the original context assigned to the web application"); - } - context = servletContext.getContextPath(); - } - apiConfig.setContext(context); - - String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT); - if (endpoint == null || endpoint.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("'managed-api-endpoint' attribute is not configured"); - } - endpoint = APIPublisherUtil.getApiEndpointUrl(context); - } - apiConfig.setEndpoint(endpoint); - - String owner = servletContext.getInitParameter(PARAM_MANAGED_API_OWNER); - if (owner == null || owner.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("'managed-api-owner' attribute is not configured"); - } - } - apiConfig.setOwner(owner); - - String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED); - boolean isSecured; - if (isSecuredParam == null || isSecuredParam.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " + - "which is 'true'"); - } - isSecured = false; - } else { - isSecured = Boolean.parseBoolean(isSecuredParam); - } - apiConfig.setSecured(isSecured); - - String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS); - if (transports == null || transports.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " + - "which is 'https'"); - } - transports = "https"; - } - apiConfig.setTransports(transports); - - return apiConfig; - } + private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0"; + + private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled"; + private static final String PARAM_MANAGED_API_NAME = "managed-api-name"; + private static final String PARAM_MANAGED_API_VERSION = "managed-api-version"; + private static final String PARAM_MANAGED_API_CONTEXT = "managed-api-context"; + private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint"; + private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner"; + private static final String PARAM_MANAGED_API_TRANSPORTS = "managed-api-transports"; + private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured"; + private static final String PARAM_MANAGED_API_APPLICATION = "managed-api-application"; + private static final String PARAM_MANAGED_API_CONTEXT_TEMPLATE = "managed-api-context-template"; + private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants"; + private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain"; + private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class); + + @Override + public void lifecycleEvent(LifecycleEvent lifecycleEvent) { + if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { + StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); + ServletContext servletContext = context.getServletContext(); + String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); + boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); + + if (isManagedApi) { + try { + AnnotationUtil annotationUtil = new AnnotationUtil(context); + Set annotatedAPIClasses = annotationUtil. + scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); + List apiDefinitions = annotationUtil.extractAPIInfo(annotatedAPIClasses); + + for (APIResourceConfiguration apiDefinition : apiDefinitions) { + APIConfig apiConfig = this.buildApiConfig(servletContext, apiDefinition); + try { + int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().getTenantId(apiConfig.getTenantDomain()); + boolean isTenantActive = APIPublisherDataHolder.getInstance().getTenantManager().isTenantActive(tenantId); + if (isTenantActive) { + apiConfig.init(); + API api = APIPublisherUtil.getAPI(apiConfig); + APIPublisherService apiPublisherService = + APIPublisherDataHolder.getInstance().getApiPublisherService(); + if (apiPublisherService == null) { + throw new IllegalStateException( + "API Publisher service is not initialized properly"); + } + apiPublisherService.publishAPI(api); + } else { + log.error("No tenant [" + apiConfig.getTenantDomain() + "] found when publishing the webapp"); + } + } catch (Throwable e) { + log.error("Error occurred while publishing API '" + apiConfig.getName() + + "' with the context '" + apiConfig.getContext() + + "' and version '" + apiConfig.getVersion() + "'", e); + } + } + } catch (IOException e) { + log.error("Error enconterd while discovering annotated classes", e); + } catch (ClassNotFoundException e) { + log.error("Error while scanning class for annotations", e); + } + } + } + } + + private List mergeAPIDefinitions(List inputList) { + //TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two + // classes + return null; + } + + /** + * Build the API Configuration to be passed to APIM, from a given list of URL templates + * + * @param servletContext + * @return + */ + private APIConfig buildApiConfig(ServletContext servletContext, APIResourceConfiguration apidef) { + APIConfig apiConfig = new APIConfig(); + + String name = apidef.getName(); + if (name == null || name.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("API Name not set in @API Annotation"); + } + name = servletContext.getServletContextName(); + } + apiConfig.setName(name); + + String version = apidef.getVersion(); + if (version == null || version.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("'API Version not set in @API Annotation'"); + } + version = API_CONFIG_DEFAULT_VERSION; + } + apiConfig.setVersion(version); + + + String context = apidef.getContext(); + if (context == null || context.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("'API Context not set in @API Annotation'"); + } + context = servletContext.getContextPath(); + } + apiConfig.setContext(context); + + String[] tags = apidef.getTags(); + if (tags == null || tags.length == 0) { + if (log.isDebugEnabled()) { + log.debug("'API tag not set in @API Annotation'"); + } + } else { + apiConfig.setTags(tags); + } + + String contextTemplate = servletContext.getInitParameter(PARAM_MANAGED_API_CONTEXT_TEMPLATE); + if (contextTemplate == null || contextTemplate.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("'managed-api-context-template' attribute is not configured. Therefore, using the default," + + " " + + "which is the original context template assigned to the web application"); + } + contextTemplate = servletContext.getContextPath(); + } + apiConfig.setContextTemplate(contextTemplate); + + String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT); + if (endpoint == null || endpoint.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("'managed-api-endpoint' attribute is not configured"); + } + endpoint = APIPublisherUtil.getApiEndpointUrl(context); + } + apiConfig.setEndpoint(endpoint); + + String owner = servletContext.getInitParameter(PARAM_MANAGED_API_OWNER); + if (owner == null || owner.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("'managed-api-owner' attribute is not configured"); + } + } + apiConfig.setOwner(owner); + + String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED); + boolean isSecured; + if (isSecuredParam == null || isSecuredParam.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " + + "which is 'true'"); + } + isSecured = false; + } else { + isSecured = Boolean.parseBoolean(isSecuredParam); + } + apiConfig.setSecured(isSecured); + + String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS); + if (transports == null || transports.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " + + "which is 'https'"); + } + transports = "https"; + } + apiConfig.setTransports(transports); + + String sharingValueParam = servletContext.getInitParameter(PARAM_SHARED_WITH_ALL_TENANTS); + boolean isSharedWithAllTenants = (sharingValueParam == null || (!sharingValueParam.isEmpty()) && Boolean.parseBoolean(sharingValueParam) ); + apiConfig.setSharedWithAllTenants(isSharedWithAllTenants); + + String tenantDomain = servletContext.getInitParameter(PARAM_PROVIDER_TENANT_DOMAIN); + tenantDomain = (tenantDomain!= null && !tenantDomain.isEmpty()) ? tenantDomain : MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; + apiConfig.setTenantDomain(tenantDomain); + + Set uriTemplates = new LinkedHashSet(); + for (APIResource apiResource : apidef.getResources()) { + URITemplate template = new URITemplate(); + template.setAuthType(apiResource.getAuthType()); + template.setHTTPVerb(apiResource.getHttpVerb()); + template.setResourceURI(apiResource.getUri()); + template.setUriTemplate(apiResource.getUriTemplate()); + uriTemplates.add(template); + } + apiConfig.setUriTemplates(uriTemplates); + + return apiConfig; + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java new file mode 100644 index 0000000000..31372e70c3 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java @@ -0,0 +1,265 @@ +/* + * 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.apimgt.webapp.publisher.lifecycle.util; + +import org.apache.catalina.core.StandardContext; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.scannotation.AnnotationDB; +import org.scannotation.WarUrlFinder; +import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource; +import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration; +import javax.servlet.ServletContext; +import javax.ws.rs.*; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.*; + +public class AnnotationUtil { + + private static final Log log = LogFactory.getLog(AnnotationUtil.class); + + private static final String PACKAGE_ORG_APACHE = "org.apache"; + private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus"; + private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework"; + private static final String AUTH_TYPE = "Any"; + private static final String PROTOCOL_HTTP = "http"; + private static final String SERVER_HOST = "carbon.local.ip"; + private static final String HTTP_PORT = "httpPort"; + public static final String DIR_WEB_INF_LIB = "/WEB-INF/lib"; + public static final String STRING_ARR = "string_arr"; + public static final String STRING = "string"; + + private StandardContext context; + private Method[] pathClazzMethods; + private Class pathClazz; + private ClassLoader classLoader; + private ServletContext servletContext; + + + public AnnotationUtil(final StandardContext context) { + this.context = context; + servletContext = context.getServletContext(); + classLoader = servletContext.getClassLoader(); + } + + /** + * Scan the context for classes with annotations + * @return + * @throws IOException + */ + public Set scanStandardContext(String className) throws IOException { + AnnotationDB db = new AnnotationDB(); + db.addIgnoredPackages(PACKAGE_ORG_APACHE); + db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS); + db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK); + + URL[] libPath = WarUrlFinder.findWebInfLibClasspaths(servletContext); + URL classPath = WarUrlFinder.findWebInfClassesPath(servletContext); + URL[] urls = (URL[]) ArrayUtils.add(libPath, libPath.length, classPath); + + db.scanArchives(urls); + + //Returns a list of classes with given Annotation + return db.getAnnotationIndex().get(className); + } + + /** + * Method identifies the URL templates and context by reading the annotations of a class + * @param entityClasses + * @return + */ + public List extractAPIInfo(Set entityClasses) + throws ClassNotFoundException { + + List apiResourceConfigs = new ArrayList(); + + if (entityClasses != null && !entityClasses.isEmpty()) { + for (final String className : entityClasses) { + + APIResourceConfiguration resource = + AccessController.doPrivileged(new PrivilegedAction() { + public APIResourceConfiguration run() { + Class clazz = null; + APIResourceConfiguration apiResourceConfig = null; + try { + clazz = classLoader.loadClass(className); + Class apiClazz = (Class) + classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); + Annotation apiAnno = clazz.getAnnotation(apiClazz); + + List resourceList = null; + apiResourceConfig = new APIResourceConfiguration(); + + if (apiAnno != null) { + + Method[] apiClazzMethods = apiClazz.getMethods(); + + if (log.isDebugEnabled()) { + log.debug("Application Context root = " + servletContext.getContextPath()); + } + + try { + for(int k=0;k) classLoader.loadClass(Path.class.getName()); + pathClazzMethods = pathClazz.getMethods(); + + Annotation rootContectAnno = clazz.getAnnotation(pathClazz); + if (rootContectAnno != null) { + rootContext = invokeMethod(pathClazzMethods[0], rootContectAnno, STRING); + if (log.isDebugEnabled()) { + log.debug("API Root Context = " + rootContext); + } + } + + Method[] annotatedMethods = clazz.getDeclaredMethods(); + resourceList = getApiResources(rootContext, annotatedMethods); + apiResourceConfig.setResources(resourceList); + } catch (Throwable throwable) { + log.error("Error encountered while scanning for annotations", throwable); + } + } + } catch (ClassNotFoundException e) { + log.error("Error when passing the api annotation for device type apis."); + } + return apiResourceConfig; + } + }); + apiResourceConfigs.add(resource); + } + } + return apiResourceConfigs; + } + + private List getApiResources(String rootContext, Method[] annotatedMethods) throws Throwable { + List resourceList; + resourceList = new ArrayList(); + for (Method method : annotatedMethods) { + Annotation methodContextAnno = method.getAnnotation(pathClazz); + if (methodContextAnno != null) { + String subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING); + APIResource resource = new APIResource(); + resource.setUriTemplate(makeContextURLReady(subCtx)); + + String serverIP = System.getProperty(SERVER_HOST); + String httpServerPort = System.getProperty(HTTP_PORT); + + resource.setUri(PROTOCOL_HTTP + "://" + serverIP + ":" + httpServerPort + makeContextURLReady(rootContext) + makeContextURLReady(subCtx)); + resource.setAuthType(AUTH_TYPE); + + Annotation[] annotations = method.getDeclaredAnnotations(); + for(int i=0; i consumesClass = (Class) classLoader.loadClass(Consumes.class.getName()); + Method[] consumesClassMethods = consumesClass.getMethods(); + Annotation consumesAnno = method.getAnnotation(consumesClass); + resource.setConsumes(invokeMethod(consumesClassMethods[0], consumesAnno, STRING_ARR)); + } + if(annotations[i].annotationType().getName().equals(Produces.class.getName())){ + Class producesClass = (Class) classLoader.loadClass(Produces.class.getName()); + Method[] producesClassMethods = producesClass.getMethods(); + Annotation producesAnno = method.getAnnotation(producesClass); + resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR)); + } + } + resourceList.add(resource); + } + } + return resourceList; + } + + private String makeContextURLReady(String context){ + if(context != null && !context.equalsIgnoreCase("")){ + if(context.startsWith("/")){ + return context; + }else{ + return "/"+context; + } + } + return ""; + } + + /** + * When an annotation and method is passed, this method invokes that executes said method against the annotation + * @param method + * @param annotation + * @param returnType + * @return + * @throws Throwable + */ + private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable { + InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation); + switch (returnType){ + case STRING: + return (String) methodHandler.invoke(annotation, method, null); + case STRING_ARR: + return ((String[])methodHandler.invoke(annotation, method, null))[0]; + default: + return null; + } + } + + /** + * When an annotation and method is passed, this method invokes that executes said method against the annotation + */ + private String[] invokeMethod(Method method, Annotation annotation) throws Throwable { + InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation); + return ((String[])methodHandler.invoke(annotation, method, null)); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml index 2eb681d946..d135f26832 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml @@ -125,7 +125,7 @@ javax.servlet;resolution:=optional, javax.xml.*;resolution:=optional, org.apache.commons.lang, - javax.ws.rs;resolution:=optional, + javax.ws.rs;version="0.0.0", org.scannotation diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml index dd3fe2d9e7..0f86757cea 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml @@ -133,10 +133,10 @@ ${project.artifactId} ${carbon.device.mgt.version} Device Management JWT Client Bundle - org.wso2.carbon.device.mgt.jwt.client.extension.internal + org.wso2.carbon.identity.jwt.client.extension.internal - !org.wso2.carbon.device.mgt.jwt.client.extension.internal, - org.wso2.carbon.device.mgt.jwt.client.extension.* + !org.wso2.carbon.identity.jwt.client.extension.internal, + org.wso2.carbon.identity.jwt.client.extension.* org.osgi.framework, diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClient.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClient.java index 0aa903d29a..fc50292de5 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClient.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClient.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.jwt.client.extension; +package org.wso2.carbon.identity.jwt.client.extension; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSAlgorithm; @@ -39,11 +39,11 @@ import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.KeyStoreManager; -import org.wso2.carbon.device.mgt.jwt.client.extension.constant.JWTConstants; -import org.wso2.carbon.device.mgt.jwt.client.extension.dto.AccessTokenInfo; -import org.wso2.carbon.device.mgt.jwt.client.extension.dto.JWTConfig; -import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException; -import org.wso2.carbon.device.mgt.jwt.client.extension.util.JWTClientUtil; +import org.wso2.carbon.identity.jwt.client.extension.constant.JWTConstants; +import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; +import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig; +import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; +import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil; import java.io.File; import java.io.IOException; diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClientManager.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClientManager.java index cafed79cb9..bea6664a10 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClientManager.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/JWTClientManager.java @@ -16,17 +16,17 @@ * under the License. */ -package org.wso2.carbon.device.mgt.jwt.client.extension; +package org.wso2.carbon.identity.jwt.client.extension; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.jwt.client.extension.dto.JWTConfig; -import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientAlreadyExistsException; -import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientConfigurationException; -import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException; -import org.wso2.carbon.device.mgt.jwt.client.extension.util.JWTClientUtil; +import org.wso2.carbon.identity.jwt.client.extension.dto.JWTConfig; +import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientAlreadyExistsException; +import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientConfigurationException; +import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; +import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/constant/JWTConstants.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/constant/JWTConstants.java index 41358fe627..106c522800 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/constant/JWTConstants.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/constant/JWTConstants.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.jwt.client.extension.constant; +package org.wso2.carbon.identity.jwt.client.extension.constant; /** * This holds the constants related JWT client component. diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/AccessTokenInfo.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/AccessTokenInfo.java index 9c12c653ff..146ddf128a 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/AccessTokenInfo.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/AccessTokenInfo.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.jwt.client.extension.dto; +package org.wso2.carbon.identity.jwt.client.extension.dto; /** * This holds the token information that return from the token endpoint. diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/JWTConfig.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/JWTConfig.java index 6c41ae8c03..ba0b7ffe9b 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/JWTConfig.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/dto/JWTConfig.java @@ -1,4 +1,4 @@ -package org.wso2.carbon.device.mgt.jwt.client.extension.dto; +package org.wso2.carbon.identity.jwt.client.extension.dto; import java.util.ArrayList; import java.util.List; diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientAlreadyExistsException.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientAlreadyExistsException.java index cdcbfb64b2..fab6d324c1 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientAlreadyExistsException.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientAlreadyExistsException.java @@ -17,7 +17,7 @@ * */ -package org.wso2.carbon.device.mgt.jwt.client.extension.exception; +package org.wso2.carbon.identity.jwt.client.extension.exception; public class JWTClientAlreadyExistsException extends Exception { public JWTClientAlreadyExistsException() { diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientConfigurationException.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientConfigurationException.java index a7f9d742d4..cd7e947fe0 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientConfigurationException.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientConfigurationException.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.jwt.client.extension.exception; +package org.wso2.carbon.identity.jwt.client.extension.exception; public class JWTClientConfigurationException extends Exception { public JWTClientConfigurationException() { diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientException.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientException.java index e434fbcb23..0808292371 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientException.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/exception/JWTClientException.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.jwt.client.extension.exception; +package org.wso2.carbon.identity.jwt.client.extension.exception; public class JWTClientException extends Exception{ public JWTClientException() { diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionDataHolder.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionDataHolder.java index 39d50961a7..8e66fd49ab 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionDataHolder.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionDataHolder.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.jwt.client.extension.internal; +package org.wso2.carbon.identity.jwt.client.extension.internal; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java index 72dd99a56d..ff59df5fd3 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/internal/JWTClientExtensionServiceComponent.java @@ -16,12 +16,12 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.jwt.client.extension.internal; +package org.wso2.carbon.identity.jwt.client.extension.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.device.mgt.jwt.client.extension.util.JWTClientUtil; +import org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; @@ -30,7 +30,7 @@ import org.wso2.carbon.user.core.service.RealmService; import java.io.IOException; /** - * @scr.component name="org.wso2.carbon.device.mgt.jwt.client.extension.internal.JWTClientExtensionServiceComponent" + * @scr.component name="org.wso2.carbon.identity.jwt.client.extension.internal.JWTClientExtensionServiceComponent" * immediate="true" * @scr.reference name="registry.service" * interface="org.wso2.carbon.registry.core.service.RegistryService" diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java index 087fd17294..9cb0792487 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.jwt.client.extension.util; +package org.wso2.carbon.identity.jwt.client.extension.util; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; @@ -29,7 +29,7 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.jwt.client.extension.internal.JWTClientExtensionDataHolder; +import org.wso2.carbon.identity.jwt.client.extension.internal.JWTClientExtensionDataHolder; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher.feature/src/main/resources/p2.inf index 417de1a4cc..70f1acd33f 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher.feature/src/main/resources/p2.inf +++ b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher.feature/src/main/resources/p2.inf @@ -1,2 +1,2 @@ instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/conf/device-analytics-config.xml,target:${installFolder}/../../conf/etc/device-analytics-config.xml,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.analytics.data.publisher_${feature.version}/conf/device-analytics-config.xml,target:${installFolder}/../../conf/etc/device-analytics-config.xml,overwrite:true);\ \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8df08f3384..74257bdccc 100644 --- a/pom.xml +++ b/pom.xml @@ -445,6 +445,11 @@ + + org.wso2.carbon.governance + org.wso2.carbon.governance.lcm + ${carbon.governance.version} + From 3a3e9cc6492474975507dd50e9d381f17a3aaf6b Mon Sep 17 00:00:00 2001 From: ayyoob Date: Thu, 31 Mar 2016 05:55:03 +0530 Subject: [PATCH 08/10] changed analytics components to released version --- .../device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml | 2 +- pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml index d135f26832..6cb83f5974 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml @@ -125,7 +125,7 @@ javax.servlet;resolution:=optional, javax.xml.*;resolution:=optional, org.apache.commons.lang, - javax.ws.rs;version="0.0.0", + javax.ws.rs;version="0.0.0";resolution:=optional, org.scannotation diff --git a/pom.xml b/pom.xml index 74257bdccc..3711d3cfe9 100644 --- a/pom.xml +++ b/pom.xml @@ -1727,8 +1727,8 @@ [5.0.11,6.0.0) - 1.0.6-SNAPSHOT - [1.0.6,2.0.0] + 1.0.5 + [1.0.5,2.0.0] 4.4.8 From 733884cba7e114f1f584084e43c17797d99b7b9f Mon Sep 17 00:00:00 2001 From: ayyoob Date: Thu, 31 Mar 2016 15:10:37 +0530 Subject: [PATCH 09/10] added web app tenant authorisation for tenant for non managed api scenario --- .../framework/WebappAuthenticationValve.java | 13 +++++ .../authorizer/WebappTenantAuthorizer.java | 49 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java index b701b9bf96..f7211fef13 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -26,6 +26,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; import org.wso2.carbon.tomcat.ext.valves.CompositeValve; import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; +import org.wso2.carbon.webapp.authenticator.framework.authorizer.WebappTenantAuthorizer; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; @@ -44,6 +45,8 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { return; } + + WebappAuthenticator authenticator = WebappAuthenticatorFactory.getAuthenticator(request); if (authenticator == null) { String msg = "Failed to load an appropriate authenticator to authenticate the request"; @@ -51,6 +54,11 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { return; } AuthenticationInfo authenticationInfo = authenticator.authenticate(request, response); + if (isManagedAPI(request) && (authenticationInfo.getStatus() == WebappAuthenticator.Status.CONTINUE || + authenticationInfo.getStatus() == WebappAuthenticator.Status.SUCCESS)) { + WebappAuthenticator.Status status = WebappTenantAuthorizer.authorize(request, authenticationInfo); + authenticationInfo.setStatus(status); + } if (authenticationInfo.getTenantId() != -1) { try { PrivilegedCarbonContext.startTenantFlow(); @@ -77,6 +85,11 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { return (param == null || !Boolean.parseBoolean(param) || isNonSecuredEndPoint(request)); } + private boolean isManagedAPI(Request request) { + String param = request.getContext().findParameter("managed-api-enabled"); + return (param != null && Boolean.parseBoolean(param)); + } + private boolean isContextSkipped(Request request) { String ctx = request.getContext().getPath(); if (ctx == null || "".equals(ctx)) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java new file mode 100644 index 0000000000..e6a55eba89 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java @@ -0,0 +1,49 @@ +/* + * 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.webapp.authenticator.framework.authorizer; + +import org.apache.catalina.connector.Request; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; +import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; + +/** + * This class represents the methods that are used to authorize requests based on the tenant subscription. + */ +public class WebappTenantAuthorizer { + private static final String SHARED_WITH_ALL_TENANTS_PARAM_NAME = "isSharedWithAllTenants"; + private static final String PROVIDER_TENANT_DOMAIN_PARAM_NAME = "providerTenantDomain"; + + public static WebappAuthenticator.Status authorize(Request request, AuthenticationInfo authenticationInfo) { + String tenantDomain = authenticationInfo.getTenantDomain(); + if (tenantDomain != null && isSharedWithAllTenants(request) || isProviderTenant(request, tenantDomain)) { + return WebappAuthenticator.Status.CONTINUE; + } + return WebappAuthenticator.Status.FAILURE; + } + + private static boolean isSharedWithAllTenants(Request request) { + String param = request.getContext().findParameter(SHARED_WITH_ALL_TENANTS_PARAM_NAME); + return (param == null || Boolean.parseBoolean(param)); + } + + private static boolean isProviderTenant(Request request, String requestTenantDomain) { + String param = request.getContext().findParameter(PROVIDER_TENANT_DOMAIN_PARAM_NAME); + return (param == null || requestTenantDomain.equals(param)); + } +} From e60a383f4d8dae092ed2f4b67e35fdea1a64f56d Mon Sep 17 00:00:00 2001 From: geethkokila Date: Thu, 31 Mar 2016 18:07:05 +0530 Subject: [PATCH 10/10] Adding fixes to the device search --- .../org.wso2.carbon.device.mgt.core/pom.xml | 10 +- .../mgt/dao/impl/DeviceDetailsDAOImpl.java | 48 +++++----- .../search/mgt/dao/impl/SearchDAOImpl.java | 18 ++-- .../search/mgt/impl/QueryBuilderImpl.java | 46 +++++---- .../mgt/impl/ResultSetAggregatorImpl.java | 38 ++++++-- .../mgt/core/search/mgt/impl/Utils.java | 4 - .../device/mgt/core/Search/SearchDevice.java | 96 +++++++++++++++---- .../src/test/resources/sql/h2.sql | 16 ++-- .../src/main/resources/dbscripts/cdm/h2.sql | 16 ++-- .../main/resources/dbscripts/cdm/mssql.sql | 16 ++-- .../main/resources/dbscripts/cdm/mysql.sql | 16 ++-- .../main/resources/dbscripts/cdm/oracle.sql | 16 ++-- .../resources/dbscripts/cdm/postgresql.sql | 16 ++-- 13 files changed, 204 insertions(+), 152 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index d6de8899f0..b741f5adf1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -238,11 +238,11 @@ - - - - - + + com.google.code.gson + gson + 1.7.1 + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java index a6822ce5ae..23c73b936b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java @@ -47,31 +47,27 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { try { conn = this.getConnection(); - stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_DETAIL (DEVICE_ID, IMEI, IMSI, DEVICE_MODEL, " + + stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_DETAIL (DEVICE_ID, DEVICE_MODEL, " + "VENDOR, OS_VERSION, BATTERY_LEVEL, INTERNAL_TOTAL_MEMORY, INTERNAL_AVAILABLE_MEMORY, " + - "EXTERNAL_TOTAL_MEMORY, EXTERNAL_AVAILABLE_MEMORY, OPERATOR, CONNECTION_TYPE, " + - "MOBILE_SIGNAL_STRENGTH, SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?,? ); "); + "EXTERNAL_TOTAL_MEMORY, EXTERNAL_AVAILABLE_MEMORY, CONNECTION_TYPE, " + + "SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setInt(1, deviceInfo.getDeviceId()); - stmt.setString(2, deviceInfo.getIMEI()); - stmt.setString(3, deviceInfo.getIMSI()); - stmt.setString(4, deviceInfo.getDeviceModel()); - stmt.setString(5, deviceInfo.getVendor()); - stmt.setString(6, deviceInfo.getOsVersion()); - stmt.setDouble(7, deviceInfo.getBatteryLevel()); - stmt.setDouble(8, deviceInfo.getInternalTotalMemory()); - stmt.setDouble(9, deviceInfo.getInternalAvailableMemory()); - stmt.setDouble(10, deviceInfo.getExternalTotalMemory()); - stmt.setDouble(11, deviceInfo.getExternalAvailableMemory()); - stmt.setString(12, deviceInfo.getOperator()); - stmt.setString(13, deviceInfo.getConnectionType()); - stmt.setDouble(14, deviceInfo.getMobileSignalStrength()); - stmt.setString(15, deviceInfo.getSsid()); - stmt.setDouble(16, deviceInfo.getCpuUsage()); - stmt.setDouble(17, deviceInfo.getTotalRAMMemory()); - stmt.setDouble(18, deviceInfo.getAvailableRAMMemory()); - stmt.setBoolean(19, deviceInfo.isPluggedIn()); + stmt.setString(2, deviceInfo.getDeviceModel()); + stmt.setString(3, deviceInfo.getVendor()); + stmt.setString(4, deviceInfo.getOsVersion()); + stmt.setDouble(5, deviceInfo.getBatteryLevel()); + stmt.setDouble(6, deviceInfo.getInternalTotalMemory()); + stmt.setDouble(7, deviceInfo.getInternalAvailableMemory()); + stmt.setDouble(8, deviceInfo.getExternalTotalMemory()); + stmt.setDouble(9, deviceInfo.getExternalAvailableMemory()); + stmt.setString(10, deviceInfo.getConnectionType()); + stmt.setString(11, deviceInfo.getSsid()); + stmt.setDouble(12, deviceInfo.getCpuUsage()); + stmt.setDouble(13, deviceInfo.getTotalRAMMemory()); + stmt.setDouble(14, deviceInfo.getAvailableRAMMemory()); + stmt.setBoolean(15, deviceInfo.isPluggedIn()); stmt.execute(); @@ -128,8 +124,8 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { while (rs.next()) { deviceInfo.setDeviceId(rs.getInt("DEVICE_ID")); - deviceInfo.setIMEI(rs.getString("IMEI")); - deviceInfo.setIMSI(rs.getString("IMSI")); +// deviceInfo.setIMEI(rs.getString("IMEI")); +// deviceInfo.setIMSI(rs.getString("IMSI")); deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); deviceInfo.setVendor(rs.getString("VENDOR")); deviceInfo.setOsVersion(rs.getString("OS_VERSION")); @@ -138,9 +134,9 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); - deviceInfo.setOperator(rs.getString("OPERATOR")); +// deviceInfo.setOperator(rs.getString("OPERATOR")); deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); - deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); +// deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); deviceInfo.setSsid(rs.getString("SSID")); deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java index 5409091a67..e80da38167 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java @@ -78,12 +78,12 @@ public class SearchDAOImpl implements SearchDAO { deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); - deviceInfo.setIMEI(rs.getString("IMEI")); - deviceInfo.setIMSI(rs.getString("IMSI")); +// deviceInfo.setIMEI(rs.getString("IMEI")); +// deviceInfo.setIMSI(rs.getString("IMSI")); deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); - deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); - deviceInfo.setOperator(rs.getString("OPERATOR")); +// deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); +// deviceInfo.setOperator(rs.getString("OPERATOR")); deviceInfo.setOsVersion(rs.getString("OS_VERSION")); deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); deviceInfo.setSsid(rs.getString("SSID")); @@ -143,7 +143,7 @@ public class SearchDAOImpl implements SearchDAO { Device device = new Device(); device.setId(rs.getInt("ID")); device.setDescription(rs.getString("DESCRIPTION")); - device.setName("NAME"); + device.setName(rs.getString("NAME")); device.setType(rs.getString("DEVICE_TYPE_NAME")); device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); @@ -160,12 +160,12 @@ public class SearchDAOImpl implements SearchDAO { deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); - deviceInfo.setIMEI(rs.getString("IMEI")); - deviceInfo.setIMSI(rs.getString("IMSI")); +// deviceInfo.setIMEI(rs.getString("IMEI")); +// deviceInfo.setIMSI(rs.getString("IMSI")); deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); - deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); - deviceInfo.setOperator(rs.getString("OPERATOR")); +// deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); +// deviceInfo.setOperator(rs.getString("OPERATOR")); deviceInfo.setOsVersion(rs.getString("OS_VERSION")); deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); deviceInfo.setSsid(rs.getString("SSID")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java index fcc2e26372..9dc36109c4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -82,11 +82,19 @@ public class QueryBuilderImpl implements QueryBuilder { } Map> queries = new HashMap<>(); - queries.put(Constants.GENERAL, Utils.convertStringToList(this.getGenericQueryPart() + this.processAND(andColumns) + - this.processOR(orColumns))); - queries.put(Constants.PROP_AND, this.processANDProperties(otherANDColumns)); - queries.put(Constants.PROP_OR, this.processORProperties(otherORColumns)); - queries.put(Constants.LOCATION, this.processLocation(locConditon)); + if ((!andColumns.isEmpty()) || (!orColumns.isEmpty())) { + queries.put(Constants.GENERAL, Utils.convertStringToList(this.getGenericQueryPart() + this.processAND(andColumns) + + this.processOR(orColumns))); + } + if (!otherANDColumns.isEmpty()) { + queries.put(Constants.PROP_AND, this.processANDProperties(otherANDColumns)); + } + if (!otherORColumns.isEmpty()) { + queries.put(Constants.PROP_OR, this.processORProperties(otherORColumns)); + } + if (locConditon != null && locConditon.getValue() != null) { + queries.put(Constants.LOCATION, this.processLocation(locConditon)); + } if (log.isDebugEnabled()) { log.debug("General Query : " + queries.get(Constants.GENERAL)); @@ -164,12 +172,12 @@ public class QueryBuilderImpl implements QueryBuilder { private String buildLocationQuery(String location) { String query = this.getGenericQueryPart(); - query = query + " OR STREET1 LIKE \'%" + location + "%\'"; - query = query + " OR STREET2 LIKE \'%" + location + "%\'"; - query = query + " OR CITY LIKE \'%" + location + "%\'"; - query = query + " OR STATE LIKE \'%" + location + "%\'"; - query = query + " OR COUNTRY LIKE \'%" + location + "%\'"; - query = query + " OR ZIP LIKE \'%" + location + "%\'"; + query = query + " AND DL.STREET1 LIKE \'%" + location + "%\'"; + query = query + " OR DL.STREET2 LIKE \'%" + location + "%\'"; + query = query + " OR DL.CITY LIKE \'%" + location + "%\'"; + query = query + " OR DL.STATE LIKE \'%" + location + "%\'"; + query = query + " OR DL.COUNTRY LIKE \'%" + location + "%\'"; + query = query + " OR DL.ZIP LIKE \'%" + location + "%\'"; return query; } @@ -177,13 +185,13 @@ public class QueryBuilderImpl implements QueryBuilder { return "SELECT D.ID, D.DESCRIPTION, D.NAME, \n" + " D.DEVICE_TYPE_ID, D.DEVICE_IDENTIFICATION, DT.ID AS DEVICE_TYPE_ID, \n" + - "DT.NAME AS DEVICE_TYPE_NAME, DD.DEVICE_ID, DD.IMEI, DD.IMSI, DD.DEVICE_MODEL, DD.VENDOR, \n" + + "DT.NAME AS DEVICE_TYPE_NAME, DD.DEVICE_ID, DD.DEVICE_MODEL, DD.VENDOR, \n" + "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + - "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.OPERATOR, DD.CONNECTION_TYPE, \n" + - "DD.MOBILE_SIGNAL_STRENGTH, DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.CONNECTION_TYPE, \n" + + "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + "DD.PLUGGED_IN, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + "DL.STATE, DL.COUNTRY FROM DM_DEVICE_DETAIL AS DD, DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, " + - "DM_DEVICE_TYPE AS DT WHERE D.TENANT_ID = " + + "DM_DEVICE_TYPE AS DT WHERE DEVICE_TYPE_ID=D.DEVICE_TYPE_ID AND D.TENANT_ID = " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -193,14 +201,14 @@ public class QueryBuilderImpl implements QueryBuilder { return "SELECT D.ID, D.DESCRIPTION, D.NAME, \n" + " D.DEVICE_TYPE_ID, D.DEVICE_IDENTIFICATION, DT.ID AS DEVICE_TYPE_ID, \n" + - "DT.NAME AS DEVICE_TYPE_NAME, DD.DEVICE_ID, DD.IMEI, DD.IMSI, DD.DEVICE_MODEL, DD.VENDOR, \n" + + "DT.NAME AS DEVICE_TYPE_NAME, DD.DEVICE_ID, DD.DEVICE_MODEL, DD.VENDOR, \n" + "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + - "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.OPERATOR, DD.CONNECTION_TYPE, \n" + - "DD.MOBILE_SIGNAL_STRENGTH, DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.CONNECTION_TYPE, \n" + + "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + "DD.PLUGGED_IN, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + "DL.STATE, DL.COUNTRY, DI.KEY_FIELD, DI.VALUE_FIELD FROM DM_DEVICE_DETAIL AS DD, " + "DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, \n" + - "DM_DEVICE_INFO AS DI, DM_DEVICE_TYPE AS DT WHERE D.TENANT_ID = " + + "DM_DEVICE_INFO AS DI, DM_DEVICE_TYPE AS DT WHERE DEVICE_TYPE_ID=D.DEVICE_TYPE_ID AND D.TENANT_ID = " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java index 069b1630ac..dc33400b6e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java @@ -23,10 +23,7 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; import org.wso2.carbon.device.mgt.core.search.mgt.Constants; import org.wso2.carbon.device.mgt.core.search.mgt.ResultSetAggregator; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; public class ResultSetAggregatorImpl implements ResultSetAggregator { @@ -37,24 +34,36 @@ public class ResultSetAggregatorImpl implements ResultSetAggregator { Map andMap = this.convertToMap(deviceWrappers.get(Constants.PROP_AND)); Map orMap = this.convertToMap(deviceWrappers.get(Constants.PROP_OR)); Map locationMap = this.convertToMap(deviceWrappers.get(Constants.LOCATION)); - + Map finalMap = new HashMap<>(); List finalResult = new ArrayList<>(); - for (Integer a : andMap.keySet()) { - if (generalQueryMap.containsKey(a)) { - if (!finalResult.contains(a)) { + + if (andMap.isEmpty()) { + finalMap = generalQueryMap; + finalResult = this.convertDeviceMapToList(generalQueryMap); + } else { + for (Integer a : andMap.keySet()) { + if (generalQueryMap.isEmpty()) { finalResult.add(andMap.get(a)); + finalMap.put(a, andMap.get(a)); + } else if (generalQueryMap.containsKey(a)) { + if (!finalMap.containsKey(a)) { + finalResult.add(andMap.get(a)); + finalMap.put(a, andMap.get(a)); + } } } } for (Integer a : orMap.keySet()) { - if (!finalResult.contains(a)) { + if (!finalMap.containsKey(a)) { finalResult.add(orMap.get(a)); + finalMap.put(a, orMap.get(a)); } } for (Integer a : locationMap.keySet()) { - if (!finalResult.contains(a)) { + if (!finalMap.containsKey(a)) { finalResult.add(locationMap.get(a)); + finalMap.put(a, locationMap.get(a)); } } @@ -72,4 +81,13 @@ public class ResultSetAggregatorImpl implements ResultSetAggregator { } return deviceWrapperMap; } + + private List convertDeviceMapToList(Map map) { + List list = new ArrayList<>(); + + for (Integer a : map.keySet()) { + list.add(map.get(a)); + } + return list; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java index bd0b7a816a..cef647d727 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java @@ -32,8 +32,6 @@ public class Utils { Map colonmsMap = new HashMap<>(); - colonmsMap.put("IMEI", "IMEI"); - colonmsMap.put("IMSI", "IMSI"); colonmsMap.put("deviceModel", "DEVICE_MODEL"); colonmsMap.put("vendor", "VENDOR"); colonmsMap.put("osVersion", "OS_VERSION"); @@ -42,9 +40,7 @@ public class Utils { colonmsMap.put("internalAvailableMemory", "INTERNAL_AVAILABLE_MEMORY"); colonmsMap.put("externalTotalMemory", "EXTERNAL_TOTAL_MEMORY"); colonmsMap.put("externalAvailableMemory", "EXTERNAL_AVAILABLE_MEMORY"); - colonmsMap.put("operator", "OPERATOR"); colonmsMap.put("connectionType", "CONNECTION_TYPE"); - colonmsMap.put("mobileSignalStrength", "MOBILE_SIGNAL_STRENGTH"); colonmsMap.put("ssid", "SSID"); colonmsMap.put("cpuUsage", "CPU_USAGE"); colonmsMap.put("totalRAMMemory", "TOTAL_RAM_MEMORY"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java index bab5f5b228..88acffe514 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core.search; +import com.google.gson.Gson; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.annotations.BeforeClass; @@ -61,36 +62,93 @@ public class SearchDevice extends BaseDeviceManagementTest { cond.setState(Condition.State.AND); conditions.add(cond); - Condition cond2 = new Condition(); - cond2.setKey("CPU_USAGE"); - cond2.setOperator(">"); - cond2.setValue("40"); - cond2.setState(Condition.State.OR); - conditions.add(cond2); - - Condition cond3 = new Condition(); - cond3.setKey("LOCATION"); - cond3.setOperator("="); - cond3.setValue("Colombo"); - cond3.setState(Condition.State.AND); - conditions.add(cond3); +// Condition cond2 = new Condition(); +// cond2.setKey("CPU_USAGE"); +// cond2.setOperator(">"); +// cond2.setValue("40"); +// cond2.setState(Condition.State.OR); +// conditions.add(cond2); +// +// Condition cond3 = new Condition(); +// cond3.setKey("LOCATION"); +// cond3.setOperator("="); +// cond3.setValue("Colombo"); +// cond3.setState(Condition.State.AND); +// conditions.add(cond3); context.setConditions(conditions); -// Gson gson = new Gson(); -// -// String aaa = gson.toJson(context); -// -// log.info(aaa); - SearchManagerService service = new SearchManagerServiceImpl(); List deviceWrappers = service.search(context); + Gson gson = new Gson(); + String bbbb = gson.toJson(deviceWrappers); + log.info(bbbb); + + for (DeviceWrapper dw : deviceWrappers) { log.debug(dw.getDevice().getDescription()); log.debug(dw.getDevice().getDeviceIdentifier()); } } + +// @Test +// public void doValidLocationSearch() throws Exception{ +// +// SearchContext context = new SearchContext(); +// List conditions = new ArrayList<>(); +// +// Condition cond = new Condition(); +// cond.setKey("LOCATION"); +// cond.setOperator("="); +// cond.setValue("Karan"); +// cond.setState(Condition.State.AND); +// conditions.add(cond); +// +// context.setConditions(conditions); +// +// SearchManagerService service = new SearchManagerServiceImpl(); +// List deviceWrappers = service.search(context); +// +// Gson gson = new Gson(); +// String bbbb = gson.toJson(deviceWrappers); +// log.info("Valid Search " + bbbb); +// +// +// for (DeviceWrapper dw : deviceWrappers) { +// log.debug(dw.getDevice().getDescription()); +// log.debug(dw.getDevice().getDeviceIdentifier()); +// } +// } +// +// @Test +// public void doInvalidLocationSearch() throws Exception{ +// +// SearchContext context = new SearchContext(); +// List conditions = new ArrayList<>(); +// +// Condition cond = new Condition(); +// cond.setKey("LOCATION"); +// cond.setOperator("="); +// cond.setValue("Colombo"); +// cond.setState(Condition.State.AND); +// conditions.add(cond); +// +// context.setConditions(conditions); +// +// SearchManagerService service = new SearchManagerServiceImpl(); +// List deviceWrappers = service.search(context); +// +// Gson gson = new Gson(); +// String bbbb = gson.toJson(deviceWrappers); +// log.info("Invalid Search " + bbbb); +// +// +// for (DeviceWrapper dw : deviceWrappers) { +// log.debug(dw.getDevice().getDescription()); +// log.debug(dw.getDevice().getDeviceIdentifier()); +// } +// } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index ebacfbfd90..d61153d30f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -460,23 +460,19 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - IMEI VARCHAR(100) NULL, - IMSI VARCHAR(100) NULL, DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, BATTERY_LEVEL DECIMAL(4) NULL, - INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - OPERATOR VARCHAR(45) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, CONNECTION_TYPE VARCHAR(10) NULL, - MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, SSID VARCHAR(45) NULL, CPU_USAGE DECIMAL(5) NULL, - TOTAL_RAM_MEMORY DECIMAL(5) NULL, - AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, PLUGGED_IN INT(1) NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 3dfaa9e13b..e77513b350 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -461,23 +461,19 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - IMEI VARCHAR(100) NULL, - IMSI VARCHAR(100) NULL, DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, BATTERY_LEVEL DECIMAL(4) NULL, - INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - OPERATOR VARCHAR(45) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, CONNECTION_TYPE VARCHAR(10) NULL, - MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, SSID VARCHAR(45) NULL, CPU_USAGE DECIMAL(5) NULL, - TOTAL_RAM_MEMORY DECIMAL(5) NULL, - AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, PLUGGED_IN INT(1) NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index bae7db4986..d46cfdf5fd 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -432,23 +432,19 @@ DROP TABLE IF EXISTS DM_DEVICE_DETAIL ; CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - IMEI VARCHAR(100) NULL, - IMSI VARCHAR(100) NULL, DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, BATTERY_LEVEL DECIMAL(4) NULL, - INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - OPERATOR VARCHAR(45) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, CONNECTION_TYPE VARCHAR(10) NULL, - MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, SSID VARCHAR(45) NULL, CPU_USAGE DECIMAL(5) NULL, - TOTAL_RAM_MEMORY DECIMAL(5) NULL, - AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, PLUGGED_IN INT(1) NULL, PRIMARY KEY (ID), INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx (DEVICE_ID ASC), diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index b7431857ec..485c954c4c 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -445,23 +445,19 @@ DROP TABLE IF EXISTS DM_DEVICE_DETAIL ; CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, - IMEI VARCHAR(100) NULL, - IMSI VARCHAR(100) NULL, DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, BATTERY_LEVEL DECIMAL(4) NULL, - INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - OPERATOR VARCHAR(45) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, CONNECTION_TYPE VARCHAR(10) NULL, - MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, SSID VARCHAR(45) NULL, CPU_USAGE DECIMAL(5) NULL, - TOTAL_RAM_MEMORY DECIMAL(5) NULL, - AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, PLUGGED_IN INT(1) NULL, PRIMARY KEY (ID), INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx (DEVICE_ID ASC), diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql index f7a68e3ee1..4ec9750cbe 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -745,23 +745,19 @@ END; CREATE TABLE DM_DEVICE_DETAIL ( ID NUMBER(10) NOT NULL, DEVICE_ID NUMBER(10) NOT NULL, - IMEI VARCHAR2(100) NULL, - IMSI VARCHAR2(100) NULL, DEVICE_MODEL VARCHAR2(45) NULL, VENDOR VARCHAR2(45) NULL, OS_VERSION VARCHAR2(45) NULL, BATTERY_LEVEL NUMBER(4) NULL, - INTERNAL_TOTAL_MEMORY NUMBER(5) NULL, - INTERNAL_AVAILABLE_MEMORY NUMBER(5) NULL, - EXTERNAL_TOTAL_MEMORY NUMBER(5) NULL, - EXTERNAL_AVAILABLE_MEMORY NUMBER(5) NULL, - OPERATOR VARCHAR2(45) NULL, + INTERNAL_TOTAL_MEMORY NUMBER(30) NULL, + INTERNAL_AVAILABLE_MEMORY NUMBER(30) NULL, + EXTERNAL_TOTAL_MEMORY NUMBER(30) NULL, + EXTERNAL_AVAILABLE_MEMORY NUMBER(30) NULL, CONNECTION_TYPE VARCHAR2(10) NULL, - MOBILE_SIGNAL_STRENGTH NUMBER(5) NULL, SSID VARCHAR2(45) NULL, CPU_USAGE NUMBER(5) NULL, - TOTAL_RAM_MEMORY NUMBER(5) NULL, - AVAILABLE_RAM_MEMORY NUMBER(5) NULL, + TOTAL_RAM_MEMORY NUMBER(30) NULL, + AVAILABLE_RAM_MEMORY NUMBER(30) NULL, PLUGGED_IN NUMBER(10) NULL, PRIMARY KEY (ID) , diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 40e2a47540..c608b4930e 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -391,23 +391,19 @@ CREATE INDEX DM_DEVICE_LOCATION_DEVICE_idx ON DM_DEVICE_LOCATION (DEVICE_ID ASC) CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ID INT NOT NULL DEFAULT NEXTVAL ('DM_DEVICE_DETAIL_seq'), DEVICE_ID INT NOT NULL, - IMEI VARCHAR(100) NULL, - IMSI VARCHAR(100) NULL, DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, BATTERY_LEVEL DECIMAL(4) NULL, - INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, - EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, - OPERATOR VARCHAR(45) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, CONNECTION_TYPE VARCHAR(10) NULL, - MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, SSID VARCHAR(45) NULL, CPU_USAGE DECIMAL(5) NULL, - TOTAL_RAM_MEMORY DECIMAL(5) NULL, - AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, PLUGGED_IN INT NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE