From 9e5891a7281c631a7cef485d2e4e8bb3125462e9 Mon Sep 17 00:00:00 2001 From: Dileesha Rajapakse Date: Fri, 18 Dec 2015 15:34:50 +0530 Subject: [PATCH 01/13] Fixed EMM-1116 --- .../src/main/resources/dbscripts/cdm/postgresql.sql | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 f04cb691b7..4299ac52b6 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 @@ -4,10 +4,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( ); CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( - ID BIGSERIAL PRIMARY KEY, + ID BIGSERIAL NOT NULL PRIMARY KEY, SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, - CERTIFICATE BYTEA DEFAULT NULL, - PRIMARY KEY (ID) + CERTIFICATE BYTEA DEFAULT NULL ); CREATE TABLE IF NOT EXISTS DM_DEVICE ( From 6441c201e5939c8e5d614957d4e9812a66857e94 Mon Sep 17 00:00:00 2001 From: harshanl Date: Fri, 18 Dec 2015 22:17:07 +0530 Subject: [PATCH 02/13] Added search support for pagination --- .../device/mgt/common/PaginationRequest.java | 89 +++++++ .../operation/mgt/OperationManager.java | 6 +- .../carbon/device/mgt/core/dao/DeviceDAO.java | 124 +++++++-- .../core/dao/impl/AbstractDeviceDAOImpl.java | 204 ++++++++++++++- .../dao/impl/device/GenericDeviceDAOImpl.java | 242 ++++++++++++++--- .../dao/impl/device/OracleDeviceDAOImpl.java | 243 ++++++++++++++++-- .../impl/device/PostgreSQLDeviceDAOImpl.java | 240 +++++++++++++++-- .../impl/device/SQLServerDeviceDAOImpl.java | 242 +++++++++++++++-- .../operation/mgt/OperationManagerImpl.java | 9 +- .../core/operation/mgt/dao/OperationDAO.java | 5 +- .../mgt/dao/impl/GenericOperationDAOImpl.java | 13 +- .../operation/OracleOperationDAOImpl.java | 13 +- .../operation/PostgreSQLOperationDAOImpl.java | 13 +- .../operation/SQLServerOperationDAOImpl.java | 14 +- .../DeviceManagementProviderService.java | 55 +++- .../DeviceManagementProviderServiceImpl.java | 189 +++++++++++++- .../authenticator/OAuthAuthenticator.java | 3 - 17 files changed, 1516 insertions(+), 188 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java new file mode 100644 index 0000000000..ae813f50a8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common; + +/** + * This class holds required parameters for a querying a paginated response. + */ +public class PaginationRequest { + + private int startIndex; + private int rowCount; + private String owner; + private String status; + private String type; + private String deviceName; + private String ownership; + + public int getStartIndex() { + return startIndex; + } + + public void setStartIndex(int startIndex) { + this.startIndex = startIndex; + } + + public int getRowCount() { + return rowCount; + } + + public void setRowCount(int rowCount) { + this.rowCount = rowCount; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDeviceName() { + return deviceName; + } + + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + public String getOwnership() { + return ownership; + } + + public void setOwnership(String ownership) { + this.ownership = ownership; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java index 710facd64f..1d86b618f8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.common.operation.mgt; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import java.util.List; @@ -52,13 +53,12 @@ public interface OperationManager { * Method to retrieve all the operations applied to a device with pagination support. * * @param deviceId DeviceIdentifier of the device - * @param index Starting row number - * @param limit No of rows to fetch + * @param request PaginationRequest object holding the data for pagination * @return PaginationResult - Result including the required parameters necessary to do pagination. * @throws OperationManagementException If some unusual behaviour is observed while fetching the * operation list. */ - PaginationResult getOperations(DeviceIdentifier deviceId, int index, int limit) throws OperationManagementException; + PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException; /** * Method to retrieve the list of available operations to a device. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index dceabe6825..6b204b008d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -18,11 +18,8 @@ package org.wso2.carbon.device.mgt.core.dao; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status; -import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import java.util.HashMap; @@ -34,7 +31,7 @@ import java.util.List; public interface DeviceDAO { /** - * This method is used to add a device. + * This method is used to get the device count by device-type. * * @param type device type. * @param tenantId tenant id. @@ -43,6 +40,46 @@ public interface DeviceDAO { */ int getDeviceCount(String type, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to get the device count by user. + * + * @param username username of the user. + * @param tenantId tenant id. + * @return returns the device count of given user. + * @throws DeviceManagementDAOException + */ + int getDeviceCountByUser(String username, int tenantId) throws DeviceManagementDAOException; + + /** + * This method is used to get the device count by device name (pattern). + * + * @param deviceName name of the device. + * @param tenantId tenant id. + * @return returns the device count of given user. + * @throws DeviceManagementDAOException + */ + int getDeviceCountByName(String deviceName, int tenantId) throws DeviceManagementDAOException; + + /** + * This method is used to get the device count by status. + * + * @param status enrollment status. + * @param tenantId tenant id. + * @return returns the device count of given status. + * @throws DeviceManagementDAOException + */ + int getDeviceCount(EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException; + + /** + * This method is used to get the device count by ownership. + * + * @param ownerShip Ownership of devices. + * @param tenantId tenant id. + * @return returns the device count of given ownership. + * @throws DeviceManagementDAOException + */ + int getDeviceCountByOwnership(EnrolmentInfo.OwnerShip ownerShip, int tenantId) throws DeviceManagementDAOException; + /** * This method is used to add a device. * @@ -127,32 +164,30 @@ public interface DeviceDAO { /** * This method is used to retrieve the devices of a given tenant as a paginated result. * - * @param index start index of result set. - * @param limit number of records to be returned. + * @param request PaginationRequest object holding the data for pagination * @param tenantId tenant id. - * @return returns a PaginationResult including the requested data. + * @return returns paginated list of devices. * @throws DeviceManagementDAOException */ - PaginationResult getDevices(int index, int limit, int tenantId) throws DeviceManagementDAOException; + List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; /** * This method is used to retrieve the devices of a given tenant and type as a paginated result. * * @param type device type. - * @param index start index of result set. - * @param limit number of records to be returned. + * @param request PaginationRequest object holding the data for pagination * @param tenantId tenant id. - * @return returns a PaginationResult including the requested data. + * @return returns paginated list of devices of provided type. * @throws DeviceManagementDAOException */ - PaginationResult getDevices(String type, int index, int limit, int tenantId) throws DeviceManagementDAOException; + List getDevices(String type, PaginationRequest request, int tenantId) throws DeviceManagementDAOException; /** * This method is used to retrieve all the devices of a given tenant and device type. * * @param type device type. * @param tenantId tenant id. - * @return returns list of devices. + * @return returns list of devices of provided type. * @throws DeviceManagementDAOException */ List getDevices(String type, int tenantId) throws DeviceManagementDAOException; @@ -162,11 +197,22 @@ public interface DeviceDAO { * * @param username user name. * @param tenantId tenant id. - * @return returns list of devices. + * @return returns list of devices of given user. * @throws DeviceManagementDAOException */ List getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve devices of a given user. + * + * @param username user name. + * @param request PaginationRequest object holding the data for pagination + * @param tenantId tenant id. + * @return returns paginated list of devices in which owner matches (search) with given username. + * @throws DeviceManagementDAOException + */ + List getDevicesOfUser(String username, PaginationRequest request, int tenantId) throws DeviceManagementDAOException; + /** * This method is used to retrieve the device count of a given tenant. * @@ -176,6 +222,16 @@ public interface DeviceDAO { */ int getDeviceCount(int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve the device count of a given tenant for the given search terms. + * + * @param request paginated request used to search devices. + * @param tenantId tenant id. + * @return returns the device count. + * @throws DeviceManagementDAOException + */ + int getDeviceCount(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; + /** * This method is used to retrieve the available device types of a given tenant. * @@ -194,6 +250,18 @@ public interface DeviceDAO { */ List getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve devices of a given device name. + * + * @param deviceName device name. + * @param request PaginationRequest object holding the data for pagination + * @param tenantId tenant id. + * @return returns paginated list of devices which name matches (search) given device-name. + * @throws DeviceManagementDAOException + */ + List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException; + /** * This method is used to add an enrollment information of a given device. * @@ -246,11 +314,35 @@ public interface DeviceDAO { * * @param status enrollment status. * @param tenantId tenant id. - * @return returns list of devices. + * @return returns list of devices of given status. * @throws DeviceManagementDAOException */ List getDevicesByStatus(EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve devices of a given ownership. + * + * @param ownerShip Ownership of devices. + * @param request PaginationRequest object holding the data for pagination + * @param tenantId tenant id. + * @return returns list of devices of given ownership. + * @throws DeviceManagementDAOException + */ + List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException; + + /** + * This method is used to retrieve devices of a given enrollment status. + * + * @param status enrollment status. + * @param request PaginationRequest object holding the data for pagination + * @param tenantId tenant id. + * @return returns paginated list of devices of given status. + * @throws DeviceManagementDAOException + */ + List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException; + /** * This method is used to retrieve the enrollment id of a given device and status. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 92deb13643..c1e4718df1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -22,6 +22,7 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo.Status; +import org.wso2.carbon.device.mgt.common.PaginationRequest; 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; @@ -343,9 +344,12 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { int deviceCount = 0; try { conn = this.getConnection(); - String sql = "SELECT COUNT(ID) AS DEVICE_COUNT FROM DM_DEVICE WHERE TENANT_ID = ? "; + String sql = "SELECT COUNT(d1.DEVICE_ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 WHERE " + + "d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); rs = stmt.executeQuery(); if (rs.next()) { deviceCount = rs.getInt("DEVICE_COUNT"); @@ -358,6 +362,87 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return deviceCount; } + @Override + public int getDeviceCount(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { + int deviceCount = 0; + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + String deviceType = request.getType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + String status = request.getStatus(); + boolean isStatusProvided = false; + try { + conn = this.getConnection(); + String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID " + + "AND d.TENANT_ID = ?"; + + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + + sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerProvided = true; + } + + if (status != null && !status.isEmpty()) { + sql = sql + " AND e.STATUS = ?"; + isStatusProvided = true; + } + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + int paramIdx = 2; + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, request.getType()); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, request.getDeviceName() + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, request.getOwnership()); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, request.getOwner() + "%"); + } + if (isStatusProvided) { + stmt.setString(paramIdx++, request.getStatus()); + } + rs = stmt.executeQuery(); + if (rs.next()) { + deviceCount = rs.getInt("DEVICE_COUNT"); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + + "registered devices", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return deviceCount; + } + @Override public int getDeviceCount(String type, int tenantId) throws DeviceManagementDAOException { Connection conn; @@ -366,11 +451,13 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { int deviceCount = 0; try { conn = this.getConnection(); - String sql = "SELECT COUNT(d.ID) AS DEVICE_COUNT FROM DM_DEVICE d, (SELECT t.ID AS TYPE_ID FROM DM_DEVICE_TYPE t " + - "WHERE t.NAME = ?) d1 WHERE TYPE_ID = d.DEVICE_TYPE_ID AND d.TENANT_ID = ?"; + String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, type); stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); rs = stmt.executeQuery(); if (rs.next()) { deviceCount = rs.getInt("DEVICE_COUNT"); @@ -383,6 +470,117 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return deviceCount; } + @Override + public int getDeviceCountByUser(String username, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + int deviceCount = 0; + try { + conn = this.getConnection(); + String sql = "SELECT COUNT(e1.DEVICE_ID) AS DEVICE_COUNT FROM DM_DEVICE d, (SELECT e.DEVICE_ID " + + "FROM DM_ENROLMENT e WHERE e.TENANT_ID = ? AND e.OWNER LIKE ?) " + + "e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID AND t.ID = d.DEVICE_TYPE_ID"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, username + "%"); + ResultSet rs = stmt.executeQuery(); + + if (rs.next()) { + deviceCount = rs.getInt("DEVICE_COUNT"); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + + username + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return deviceCount; + } + + @Override + public int getDeviceCountByName(String deviceName, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + int deviceCount = 0; + try { + conn = this.getConnection(); + String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, deviceName + "%"); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + ResultSet rs = stmt.executeQuery(); + + if (rs.next()) { + deviceCount = rs.getInt("DEVICE_COUNT"); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the device count that matches " + + "'" + deviceName + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return deviceCount; + } + + @Override + public int getDeviceCountByOwnership(EnrolmentInfo.OwnerShip ownerShip, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + int deviceCount = 0; + try { + conn = this.getConnection(); + String sql = "SELECT COUNT(d.ID) AS DEVICE_COUNT FROM (SELECT e.DEVICE_ID FROM DM_ENROLMENT e WHERE " + + "TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, ownerShip.toString()); + stmt.setInt(3, tenantId); + ResultSet rs = stmt.executeQuery(); + + if (rs.next()) { + deviceCount = rs.getInt("DEVICE_COUNT"); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + + "'" + ownerShip + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return deviceCount; + } + + @Override + public int getDeviceCount(Status status, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + int deviceCount = 0; + try { + conn = this.getConnection(); + String sql = "SELECT COUNT(d.ID) AS DEVICE_COUNT FROM (SELECT e.DEVICE_ID FROM DM_ENROLMENT e WHERE " + + "TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + ResultSet rs = stmt.executeQuery(); + + if (rs.next()) { + deviceCount = rs.getInt("DEVICE_COUNT"); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + + "'" + status + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return deviceCount; + } + /** * Get the list of devices that matches with the given device name. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index e6bf3b7843..134ccb8dff 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -20,12 +20,11 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; import java.sql.Connection; import java.sql.PreparedStatement; @@ -40,27 +39,82 @@ import java.util.List; public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override - public PaginationResult getDevices(int index, int limit, int tenantId) + public List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - PaginationResult result = new PaginationResult(); Connection conn; PreparedStatement stmt = null; ResultSet rs = null; List devices = null; + String deviceType = request.getType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + String status = request.getStatus(); + boolean isStatusProvided = false; try { conn = this.getConnection(); - String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?"; -// String sql = "SELECT * FROM DM_DEVICE WHERE TENANT_ID = ? LIMIT ?,?"; + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + + sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerProvided = true; + } + //Add the query for status + if (status != null && !status.isEmpty()) { + sql = sql + " AND e.STATUS = ?"; + isStatusProvided = true; + } + + sql = sql + " LIMIT ?,?"; + stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setInt(2, tenantId); - stmt.setInt(3, index); - stmt.setInt(4, limit); + int paramIdx = 2; + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, request.getType()); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, request.getDeviceName() + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, request.getOwnership()); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, request.getOwner() + "%"); + } + if (isStatusProvided) { + stmt.setString(paramIdx++, request.getStatus()); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -73,17 +127,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } - int count = this.getDeviceCount(tenantId); - result.setData(devices); - result.setRecordsFiltered(count); - result.setRecordsTotal(count); - return result; + return devices; } @Override - public PaginationResult getDevices(String type, int index, int limit, int tenantId) + public List getDevices(String type, PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - PaginationResult result = new PaginationResult(); Connection conn; PreparedStatement stmt = null; ResultSet rs = null; @@ -96,14 +145,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?"; -// String sql = "SELECT * FROM DM_DEVICE d, (SELECT t.ID AS TYPE_ID FROM DM_DEVICE_TYPE t WHERE t.NAME = ?)" + -// " d1 WHERE TYPE_ID = d.DEVICE_TYPE_ID AND d.TENANT_ID = ? LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setString(1, type); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); - stmt.setInt(4, index); - stmt.setInt(5, limit); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -115,14 +162,149 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } - int count = this.getDeviceCount(type, tenantId); - result.setData(devices); - result.setRecordsFiltered(count); - result.setRecordsTotal(count); - return result; + return devices; + } + + @Override + public List getDevicesOfUser(String username, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.TENANT_ID = ? AND e.OWNER LIKE ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "AND t.ID = d.DEVICE_TYPE_ID LIMIT ?,?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, username + "%"); + stmt.setInt(3, request.getStartIndex()); + stmt.setInt(4, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + + username + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, deviceName + "%"); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + + "'" + deviceName + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ?,?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, ownerShip.toString()); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + + "'" + ownerShip + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ?,?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + + "'" + status + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; } - private Connection getConnection() throws SQLException { + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index d1a6c57001..c75162ae4a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -19,12 +19,13 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; + import java.sql.Connection; import java.sql.PreparedStatement; @@ -39,26 +40,82 @@ import java.util.List; public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override - public PaginationResult getDevices(int index, int limit, int tenantId) + public List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - PaginationResult result = new PaginationResult(); Connection conn; PreparedStatement stmt = null; ResultSet rs = null; List devices = null; + String deviceType = request.getType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + String status = request.getStatus(); + boolean isStatusProvided = false; try { conn = this.getConnection(); - String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + + sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerProvided = true; + } + //Add the query for status + if (status != null && !status.isEmpty()) { + sql = sql + " AND e.STATUS = ?"; + isStatusProvided = true; + } + + sql = sql + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setInt(2, tenantId); - stmt.setInt(3, index); - stmt.setInt(4, limit); + int paramIdx = 2; + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, request.getType()); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, request.getDeviceName() + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, request.getOwnership()); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, request.getOwner() + "%"); + } + if (isStatusProvided) { + stmt.setString(paramIdx++, request.getStatus()); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -71,17 +128,12 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } - int count = this.getDeviceCount(tenantId); - result.setData(devices); - result.setRecordsFiltered(count); - result.setRecordsTotal(count); - return result; + return devices; } @Override - public PaginationResult getDevices(String type, int index, int limit, int tenantId) + public List getDevices(String type, PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - PaginationResult result = new PaginationResult(); Connection conn; PreparedStatement stmt = null; ResultSet rs = null; @@ -98,8 +150,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(1, type); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); - stmt.setInt(4, index); - stmt.setInt(5, limit); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -111,14 +163,151 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } - int count = this.getDeviceCount(type, tenantId); - result.setData(devices); - result.setRecordsFiltered(count); - result.setRecordsTotal(count); - return result; + return devices; + } + + @Override + public List getDevicesOfUser(String username, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.TENANT_ID = ? AND e.OWNER LIKE ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "AND t.ID = d.DEVICE_TYPE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, username + "%"); + stmt.setInt(3, request.getStartIndex()); + stmt.setInt(4, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + + username + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? ROWS" + + " FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + + "'" + status + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, deviceName + "%"); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + + "'" + deviceName + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? " + + "ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, ownerShip.toString()); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + + "'" + ownerShip + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; } - private Connection getConnection() throws SQLException { + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 612a431fb1..ce22de94f9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -19,12 +19,12 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; import java.sql.Connection; import java.sql.PreparedStatement; @@ -39,26 +39,82 @@ import java.util.List; public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override - public PaginationResult getDevices(int index, int limit, int tenantId) + public List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - PaginationResult result = new PaginationResult(); Connection conn; PreparedStatement stmt = null; ResultSet rs = null; List devices = null; + String deviceType = request.getType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + String status = request.getStatus(); + boolean isStatusProvided = false; try { conn = this.getConnection(); - String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + + sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerProvided = true; + } + //Add the query for status + if (status != null && !status.isEmpty()) { + sql = sql + " AND e.STATUS = ?"; + isStatusProvided = true; + } + + sql = sql + " LIMIT ? OFFSET ?"; + stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setInt(2, tenantId); - stmt.setInt(3, limit); - stmt.setInt(4, index); + int paramIdx = 2; + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, request.getType()); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, request.getDeviceName() + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, request.getOwnership()); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, request.getOwner() + "%"); + } + if (isStatusProvided) { + stmt.setString(paramIdx++, request.getStatus()); + } + stmt.setInt(paramIdx, request.getRowCount()); + stmt.setInt(paramIdx++, request.getStartIndex()); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -71,17 +127,12 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } - int count = this.getDeviceCount(tenantId); - result.setData(devices); - result.setRecordsFiltered(count); - result.setRecordsTotal(count); - return result; + return devices; } @Override - public PaginationResult getDevices(String type, int index, int limit, int tenantId) + public List getDevices(String type, PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - PaginationResult result = new PaginationResult(); Connection conn; PreparedStatement stmt = null; ResultSet rs = null; @@ -98,8 +149,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(1, type); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); - stmt.setInt(4, limit); - stmt.setInt(5, index); + stmt.setInt(4, request.getRowCount()); + stmt.setInt(5, request.getStartIndex()); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -111,14 +162,149 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } - int count = this.getDeviceCount(type, tenantId); - result.setData(devices); - result.setRecordsFiltered(count); - result.setRecordsTotal(count); - return result; + return devices; + } + + @Override + public List getDevicesOfUser(String username, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.TENANT_ID = ? AND e.OWNER LIKE ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "AND t.ID = d.DEVICE_TYPE_ID LIMIT ? OFFSET ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, username + "%"); + stmt.setInt(3, request.getRowCount()); + stmt.setInt(4, request.getStartIndex()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + + username + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getRowCount()); + stmt.setInt(5, request.getStartIndex()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + + "'" + status + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, deviceName + "%"); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getRowCount()); + stmt.setInt(5, request.getStartIndex()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + + "'" + deviceName + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, ownerShip.toString()); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getRowCount()); + stmt.setInt(5, request.getStartIndex()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + + "'" + ownerShip + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; } - private Connection getConnection() throws SQLException { + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 8e47ac2024..393712fb5a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -19,12 +19,12 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; import java.sql.Connection; import java.sql.PreparedStatement; @@ -39,26 +39,82 @@ import java.util.List; public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override - public PaginationResult getDevices(int index, int limit, int tenantId) + public List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - PaginationResult result = new PaginationResult(); Connection conn; PreparedStatement stmt = null; ResultSet rs = null; List devices = null; + String deviceType = request.getType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + String status = request.getStatus(); + boolean isStatusProvided = false; try { conn = this.getConnection(); - String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + + sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerProvided = true; + } + //Add the query for status + if (status != null && !status.isEmpty()) { + sql = sql + " AND e.STATUS = ?"; + isStatusProvided = true; + } + + sql = sql + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setInt(2, tenantId); - stmt.setInt(3, index); - stmt.setInt(4, limit); + int paramIdx = 2; + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, request.getType()); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, request.getDeviceName() + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, request.getOwnership()); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, request.getOwner() + "%"); + } + if (isStatusProvided) { + stmt.setString(paramIdx++, request.getStatus()); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -71,17 +127,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } - int count = this.getDeviceCount(tenantId); - result.setData(devices); - result.setRecordsFiltered(count); - result.setRecordsTotal(count); - return result; + return devices; } @Override - public PaginationResult getDevices(String type, int index, int limit, int tenantId) + public List getDevices(String type, PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - PaginationResult result = new PaginationResult(); Connection conn; PreparedStatement stmt = null; ResultSet rs = null; @@ -98,8 +149,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setString(1, type); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); - stmt.setInt(4, index); - stmt.setInt(5, limit); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -111,14 +162,151 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } - int count = this.getDeviceCount(type, tenantId); - result.setData(devices); - result.setRecordsFiltered(count); - result.setRecordsTotal(count); - return result; + return devices; + } + + @Override + public List getDevicesOfUser(String username, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.TENANT_ID = ? AND e.OWNER LIKE ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "AND t.ID = d.DEVICE_TYPE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, username + "%"); + stmt.setInt(3, request.getStartIndex()); + stmt.setInt(4, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + + username + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? ROWS" + + " FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + + "'" + status + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, deviceName + "%"); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + + "'" + deviceName + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; + } + + @Override + public List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, + int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? " + + "ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, ownerShip.toString()); + stmt.setInt(3, tenantId); + stmt.setInt(4, request.getStartIndex()); + stmt.setInt(5, request.getRowCount()); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + + "'" + ownerShip + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return devices; } - private Connection getConnection() throws SQLException { + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index e0018eaafe..b6bcb4ce1c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -21,10 +21,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; @@ -190,7 +187,7 @@ public class OperationManagerImpl implements OperationManager { } @Override - public PaginationResult getOperations(DeviceIdentifier deviceId, int index, int limit) + public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException { PaginationResult paginationResult = null; int enrolmentId; @@ -215,7 +212,7 @@ public class OperationManagerImpl implements OperationManager { deviceId.getType()); } List operationList = - operationDAO.getOperationsForDevice(enrolmentId, index, limit); + operationDAO.getOperationsForDevice(enrolmentId, request); for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { Operation operation = OperationDAOUtil.convertOperation(dtoOperation); operations.add(operation); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java index 78097cf8dd..c24887d1bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.device.mgt.core.operation.mgt.dao; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import java.util.List; @@ -37,14 +38,14 @@ public interface OperationDAO { List getOperationsByDeviceAndStatus(int enrolmentId, Operation.Status status) throws OperationManagementDAOException; - List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, Operation.Status status) + List getOperationsByDeviceAndStatus(int enrolmentId, PaginationRequest request, Operation.Status status) throws OperationManagementDAOException; List getOperationsForDevice(int enrolmentId) throws OperationManagementDAOException; int getOperationCountForDevice(int enrolmentId) throws OperationManagementDAOException; - List getOperationsForDevice(int enrolmentId, int index, int limit) throws OperationManagementDAOException; + List getOperationsForDevice(int enrolmentId, PaginationRequest request) throws OperationManagementDAOException; Operation getNextOperation(int enrolmentId) throws OperationManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 8864026826..b866285ff0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; @@ -276,7 +277,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } @Override - public List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, + public List getOperationsByDeviceAndStatus(int enrolmentId, PaginationRequest request, Operation.Status status) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -293,8 +294,8 @@ public class GenericOperationDAOImpl implements OperationDAO { stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setString(2, status.toString()); - stmt.setInt(3, index); - stmt.setInt(4, limit); + stmt.setInt(3, request.getStartIndex()); + stmt.setInt(4, request.getRowCount()); rs = stmt.executeQuery(); while (rs.next()) { @@ -360,7 +361,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } @Override - public List getOperationsForDevice(int enrolmentId, int index, int limit) + public List getOperationsForDevice(int enrolmentId, PaginationRequest request) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; @@ -374,8 +375,8 @@ public class GenericOperationDAOImpl implements OperationDAO { "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); - stmt.setInt(2, index); - stmt.setInt(3, limit); + stmt.setInt(2, request.getStartIndex()); + stmt.setInt(3, request.getRowCount()); rs = stmt.executeQuery(); while (rs.next()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java index eb16c2feda..30fa360dd9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; @@ -37,7 +38,7 @@ import java.util.List; public class OracleOperationDAOImpl extends GenericOperationDAOImpl { @Override - public List getOperationsForDevice(int enrolmentId, int index, int limit) + public List getOperationsForDevice(int enrolmentId, PaginationRequest request) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; @@ -52,8 +53,8 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); - stmt.setInt(2, index); - stmt.setInt(3, limit); + stmt.setInt(2, request.getStartIndex()); + stmt.setInt(3, request.getRowCount()); rs = stmt.executeQuery(); while (rs.next()) { @@ -80,7 +81,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { } @Override - public List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, + public List getOperationsByDeviceAndStatus(int enrolmentId, PaginationRequest request, Operation.Status status) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -97,8 +98,8 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setString(2, status.toString()); - stmt.setInt(3, index); - stmt.setInt(4, limit); + stmt.setInt(3, request.getStartIndex()); + stmt.setInt(4, request.getRowCount()); rs = stmt.executeQuery(); while (rs.next()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java index 192ee388b8..0d107ead1d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; @@ -37,7 +38,7 @@ import java.util.List; public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { @Override - public List getOperationsForDevice(int enrolmentId, int index, int limit) + public List getOperationsForDevice(int enrolmentId, PaginationRequest request) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; @@ -51,8 +52,8 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); - stmt.setInt(2, limit); - stmt.setInt(3, index); + stmt.setInt(2, request.getRowCount()); + stmt.setInt(3, request.getStartIndex()); rs = stmt.executeQuery(); while (rs.next()) { @@ -79,7 +80,7 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { } @Override - public List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, + public List getOperationsByDeviceAndStatus(int enrolmentId, PaginationRequest request, Operation.Status status) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -96,8 +97,8 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setString(2, status.toString()); - stmt.setInt(3, limit); - stmt.setInt(4, index); + stmt.setInt(3, request.getRowCount()); + stmt.setInt(4, request.getStartIndex()); rs = stmt.executeQuery(); while (rs.next()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java index 5849e8b0a1..d4768fc876 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java @@ -18,7 +18,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; -import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; @@ -38,7 +38,7 @@ import java.util.List; public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { @Override - public List getOperationsForDevice(int enrolmentId, int index, int limit) + public List getOperationsForDevice(int enrolmentId, PaginationRequest request) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; @@ -53,8 +53,8 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); - stmt.setInt(2, index); - stmt.setInt(3, limit); + stmt.setInt(2, request.getStartIndex()); + stmt.setInt(3, request.getRowCount()); rs = stmt.executeQuery(); while (rs.next()) { @@ -81,7 +81,7 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { } @Override - public List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, + public List getOperationsByDeviceAndStatus(int enrolmentId, PaginationRequest request, Operation.Status status) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -98,8 +98,8 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setString(2, status.toString()); - stmt.setInt(3, index); - stmt.setInt(4, limit); + stmt.setInt(3, request.getStartIndex()); + stmt.setInt(4, request.getRowCount()); rs = stmt.executeQuery(); while (rs.next()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 4ab5651cff..8c1a3cb7f3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -43,24 +43,22 @@ public interface DeviceManagementProviderService extends OperationManager { * Method to retrieve all the devices with pagination support. * * @param deviceType Device platform - * @param index Starting row number - * @param limit No of rows to fetch + * @param request PaginationRequest object holding the data for pagination * @return PaginationResult - Result including the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the * devices. */ - PaginationResult getAllDevices(String deviceType, int index, int limit) throws DeviceManagementException; + PaginationResult getAllDevices(String deviceType, PaginationRequest request) throws DeviceManagementException; /** * Method to retrieve all the devices with pagination support. * - * @param index Starting row number - * @param limit No of rows to fetch + * @param request PaginationRequest object holding the data for pagination * @return PaginationResult - Result including the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the * devices. */ - PaginationResult getAllDevices(int index, int limit) throws DeviceManagementException; + PaginationResult getAllDevices(PaginationRequest request) throws DeviceManagementException; void sendEnrolmentInvitation(EmailMessageProperties config) throws DeviceManagementException; @@ -78,6 +76,29 @@ public interface DeviceManagementProviderService extends OperationManager { */ TenantConfiguration getConfiguration(String deviceType) throws DeviceManagementException; + /** + * Method to get the list of devices owned by an user with paging information. + * + * @param userName Username of the user + * @param request PaginationRequest object holding the data for pagination + * @return List of devices owned by a particular user along with the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + PaginationResult getDevicesOfUser(String userName, PaginationRequest request) throws DeviceManagementException; + + /** + * Method to get the list of devices filtered by the ownership with paging information. + * + * @param ownerShip Ownership type of devices + * @param request PaginationRequest object holding the data for pagination + * @return List of devices owned by a particular user along with the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + PaginationResult getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request) + throws DeviceManagementException; + /** * Method to get the list of devices owned by an user. * @@ -116,6 +137,17 @@ public interface DeviceManagementProviderService extends OperationManager { */ List getDevicesByName(String deviceName) throws DeviceManagementException; + /** + * This method is used to retrieve list of devices that matches with the given device name with paging information. + * + * @param deviceName name of the device + * @param request PaginationRequest object holding the data for pagination + * @return List of devices in given status along with the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + PaginationResult getDevicesByName(String deviceName, PaginationRequest request) throws DeviceManagementException; + void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status active) throws DeviceManagementException; /** @@ -127,6 +159,17 @@ public interface DeviceManagementProviderService extends OperationManager { */ List getDevicesByStatus(EnrolmentInfo.Status status) throws DeviceManagementException; + /** + * This method is used to retrieve list of devices based on the device status with paging information. + * + * @param status Device status + * @param request PaginationRequest object holding the data for pagination + * @return List of devices in given status along with the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * device list + */ + PaginationResult getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request) throws DeviceManagementException; + License getLicense(String deviceType, String languageCode) throws DeviceManagementException; void addLicense(String deviceType, License license) throws DeviceManagementException; 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 c1bc8cfa94..16a1fa105e 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 @@ -288,7 +288,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (log.isDebugEnabled()) { log.debug("Device not found for id '" + deviceId.getId() + "'"); } - throw new DeviceManagementException("Device not found"); + return false; + } + + if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.REMOVED)) { + if (log.isDebugEnabled()) { + log.debug("Device has already disenrolled : " + deviceId.getId() + "'"); + } + return false; } DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType()); @@ -387,13 +394,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public PaginationResult getAllDevices(String deviceType, int index, int limit) throws DeviceManagementException { - PaginationResult paginationResult; + public PaginationResult getAllDevices(String deviceType, PaginationRequest request) throws DeviceManagementException { + PaginationResult paginationResult = new PaginationResult(); List devices = new ArrayList<>(); - List allDevices; + List allDevices = new ArrayList<>(); + int count = 0; + int tenantId = this.getTenantId(); try { DeviceManagementDAOFactory.openConnection(); - paginationResult = deviceDAO.getDevices(deviceType, index, limit, this.getTenantId()); + allDevices = deviceDAO.getDevices(deviceType, request, tenantId); + count = deviceDAO.getDeviceCount(deviceType, tenantId); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while retrieving device list pertaining to " + "the current tenant", e); @@ -402,7 +412,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - allDevices = (List) paginationResult.getData(); for (Device device : allDevices) { DeviceManager deviceManager = this.getDeviceManager(device.getType()); if (deviceManager == null) { @@ -422,17 +431,22 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv devices.add(device); } paginationResult.setData(devices); + paginationResult.setRecordsFiltered(count); + paginationResult.setRecordsTotal(count); return paginationResult; } @Override - public PaginationResult getAllDevices(int index, int limit) throws DeviceManagementException { - PaginationResult paginationResult; + public PaginationResult getAllDevices(PaginationRequest request) throws DeviceManagementException { + PaginationResult paginationResult = new PaginationResult(); List devices = new ArrayList<>(); - List allDevices; + List allDevices = new ArrayList<>(); + int count = 0; + int tenantId = this.getTenantId(); try { DeviceManagementDAOFactory.openConnection(); - paginationResult = deviceDAO.getDevices(index, limit, this.getTenantId()); + allDevices = deviceDAO.getDevices(request, tenantId); + count = deviceDAO.getDeviceCount(request, tenantId); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while retrieving device list pertaining to " + "the current tenant", e); @@ -441,7 +455,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - allDevices = (List) paginationResult.getData(); for (Device device : allDevices) { DeviceManager deviceManager = this.getDeviceManager(device.getType()); if (deviceManager == null) { @@ -461,6 +474,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv devices.add(device); } paginationResult.setData(devices); + paginationResult.setRecordsFiltered(count); + paginationResult.setRecordsTotal(count); return paginationResult; } @@ -862,9 +877,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public PaginationResult getOperations(DeviceIdentifier deviceId, int index, int limit) + public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException { - return DeviceManagementDataHolder.getInstance().getOperationManager().getOperations(deviceId, index, limit); + return DeviceManagementDataHolder.getInstance().getOperationManager().getOperations(deviceId, request); } @Override @@ -946,6 +961,87 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } + @Override + public PaginationResult getDevicesOfUser(String username, PaginationRequest request) + throws DeviceManagementException { + PaginationResult result = new PaginationResult(); + int deviceCount = 0; + int tenantId = this.getTenantId(); + List devices = new ArrayList<>(); + List userDevices = new ArrayList<>(); + try { + DeviceManagementDAOFactory.openConnection(); + userDevices = deviceDAO.getDevicesOfUser(username, request, tenantId); + deviceCount = deviceDAO.getDeviceCountByUser(username, tenantId); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while retrieving the list of devices that " + + "belong to the user '" + username + "'", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + for (Device device : userDevices) { + DeviceManager deviceManager = this.getDeviceManager(device.getType()); + if (deviceManager == null) { + if (log.isDebugEnabled()) { + log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + + "Therefore, not attempting method 'isEnrolled'"); + } + devices.add(device); + continue; + } + Device dmsDevice = + deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (dmsDevice != null) { + device.setFeatures(dmsDevice.getFeatures()); + device.setProperties(dmsDevice.getProperties()); + } + devices.add(device); + } + result.setData(devices); + result.setRecordsTotal(deviceCount); + result.setRecordsFiltered(deviceCount); + return result; + } + + @Override + public PaginationResult getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, + PaginationRequest request) + throws DeviceManagementException { + PaginationResult result = new PaginationResult(); + List devices = new ArrayList<>(); + List allDevices; + int deviceCount = 0; + int tenantId = this.getTenantId(); + try { + DeviceManagementDAOFactory.openConnection(); + allDevices = deviceDAO.getDevicesByOwnership(ownerShip, request, tenantId); + deviceCount = deviceDAO.getDeviceCountByOwnership(ownerShip, tenantId); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException( + "Error occurred while fetching the list of devices that matches to ownership : '" + ownerShip + "'", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + for (Device device : allDevices) { + Device dmsDevice = this.getDeviceManager(device.getType()). + getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (dmsDevice != null) { + device.setFeatures(dmsDevice.getFeatures()); + device.setProperties(dmsDevice.getProperties()); + } + devices.add(device); + } + result.setData(devices); + result.setRecordsTotal(deviceCount); + result.setRecordsFiltered(deviceCount); + return result; + } + @Override public List getAllDevicesOfRole(String role) throws DeviceManagementException { List devices = new ArrayList<>(); @@ -1022,7 +1118,40 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv devices.add(device); } return devices; + } + @Override + public PaginationResult getDevicesByName(String deviceName, PaginationRequest request) + throws DeviceManagementException { + PaginationResult result = new PaginationResult(); + int tenantId = this.getTenantId(); + List devices = new ArrayList<>(); + List allDevices = new ArrayList<>(); + try { + DeviceManagementDAOFactory.openConnection(); + allDevices = deviceDAO.getDevicesByName(deviceName, request, tenantId); + int deviceCount = deviceDAO.getDeviceCountByName(deviceName, tenantId); + result.setRecordsTotal(deviceCount); + result.setRecordsFiltered(deviceCount); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while fetching the list of devices that matches to '" + + deviceName + "'", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + for (Device device : allDevices) { + Device dmsDevice = this.getDeviceManager(device.getType()). + getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (dmsDevice != null) { + device.setFeatures(dmsDevice.getFeatures()); + device.setProperties(dmsDevice.getProperties()); + } + devices.add(device); + } + result.setData(devices); + return result; } @Override @@ -1091,6 +1220,40 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return devices; } + @Override + public PaginationResult getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request) + throws DeviceManagementException { + PaginationResult result = new PaginationResult(); + List devices = new ArrayList<>(); + List allDevices = new ArrayList<>(); + int tenantId = this.getTenantId(); + try { + DeviceManagementDAOFactory.openConnection(); + allDevices = deviceDAO.getDevicesByStatus(status, request, tenantId); + int deviceCount = deviceDAO.getDeviceCount(status, tenantId); + result.setRecordsTotal(deviceCount); + result.setRecordsFiltered(deviceCount); + } catch (DeviceManagementDAOException e) { + throw new DeviceManagementException( + "Error occurred while fetching the list of devices that matches to status: '" + status + "'", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + for (Device device : allDevices) { + Device dmsDevice = this.getDeviceManager(device.getType()). + getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (dmsDevice != null) { + device.setFeatures(dmsDevice.getFeatures()); + device.setProperties(dmsDevice.getProperties()); + } + devices.add(device); + } + result.setData(devices); + return result; + } + private int getTenantId() { return CarbonContext.getThreadLocalCarbonContext().getTenantId(); } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index c82a57646b..06bfe4f99d 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -141,9 +141,6 @@ public class OAuthAuthenticator implements WebappAuthenticator { tokenValue = tokenValue.substring(matcher.end()); } } - if (log.isDebugEnabled()) { - log.debug("Oauth Token : " + tokenValue); - } return tokenValue; } From b25438097e8be54738f9e6cde48e9c4a75103853 Mon Sep 17 00:00:00 2001 From: Dileesha Rajapakse Date: Fri, 18 Dec 2015 23:26:01 +0530 Subject: [PATCH 03/13] Fixed issues in EnrollmentDAOImpl --- .../carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java index 61e9979802..f3a5a58511 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java @@ -71,7 +71,6 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { PreparedStatement stmt = null; ResultSet rs = null; int status = -1; - int rows; try { conn = this.getConnection(); String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, " + @@ -86,12 +85,12 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { stmt.setString(6, enrolmentInfo.getOwner()); stmt.setInt(7, tenantId); stmt.setInt(8, enrolmentInfo.getId()); - rows = stmt.executeUpdate(); + stmt.executeUpdate(); - if (rows > 0) { + rs = stmt.getGeneratedKeys(); + if (rs.next()) { status = 1; } - return status; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e); From 36462e2e4e1ede4166e128e3d89e49dd3965182c Mon Sep 17 00:00:00 2001 From: prabathabey Date: Sat, 19 Dec 2015 12:07:08 +0530 Subject: [PATCH 04/13] Improving performance of webapp authenticator valve implementation --- .../pom.xml | 10 +- .../OAuthTokenValidationStubFactory.java | 119 ++++++++++++++++++ .../authenticator/BasicAuthAuthenticator.java | 17 +++ .../CertificateAuthenticator.java | 17 +++ .../authenticator/JWTAuthenticator.java | 17 +++ .../authenticator/OAuthAuthenticator.java | 46 +++++-- .../authenticator/WebappAuthenticator.java | 8 ++ .../oauth/OAuth2TokenValidator.java | 1 + .../oauth/OAuthValidatorFactory.java | 29 ++++- .../oauth/impl/RemoteOAuthValidator.java | 63 +++++----- .../framework/config/AuthenticatorConfig.java | 35 ++++++ ...uthenticatorFrameworkServiceComponent.java | 8 ++ pom.xml | 12 +- 13 files changed, 333 insertions(+), 49 deletions(-) create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 3dad448cc6..7684fb68e9 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -105,9 +105,15 @@ org.apache.axis2.client, org.apache.commons.codec.binary, org.apache.commons.httpclient, - org.wso2.carbon.core.security + org.wso2.carbon.core.security, + org.apache.axis2.context, + org.apache.commons.httpclient.params, + org.apache.commons.pool, + org.apache.commons.pool.impl, + org.apache.http.client, + org.apache.http.conn, + org.apache.http.impl.client - diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java new file mode 100644 index 0000000000..85e22d4519 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java @@ -0,0 +1,119 @@ +/* + * 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.Utils; + +import org.apache.axis2.AxisFault; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.pool.PoolableObjectFactory; +import org.apache.http.client.HttpClient; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.impl.client.DefaultHttpClient; +import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; +import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthConstants; +import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +public class OAuthTokenValidationStubFactory implements PoolableObjectFactory { + + private String url; + private String basicAuthHeader; + private static final Log log = LogFactory.getLog(OAuthTokenValidationStubFactory.class); + + private HttpClient httpClient; + + public OAuthTokenValidationStubFactory(String url, String adminUsername, String adminPassword, + Properties properties) { + this.url = url; + this.basicAuthHeader = new String(Base64.encodeBase64((adminUsername + ":" + adminPassword).getBytes())); + + MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); + connectionManager.getParams().setDefaultMaxConnectionsPerHost( + Integer.parseInt(properties.getProperty("MaxConnectionsPerHost"))); + connectionManager.getParams().setMaxTotalConnections( + Integer.parseInt(properties.getProperty("MaxTotalConnections"))); + this.httpClient = new DefaultHttpClient((ClientConnectionManager) connectionManager); + } + + @Override + public Object makeObject() throws Exception { + return this.createStub(); + } + + @Override + public void destroyObject(Object o) throws Exception { + + } + + @Override + public boolean validateObject(Object o) { + return true; + } + + @Override + public void activateObject(Object o) throws Exception { + if (log.isDebugEnabled()) { + log.debug("OAuth token validate stub instance is activated"); + } + } + + @Override + public void passivateObject(Object o) throws Exception { + if (o instanceof OAuth2TokenValidationServiceStub) { + OAuth2TokenValidationServiceStub stub = (OAuth2TokenValidationServiceStub) o; + stub._getServiceClient().cleanupTransport(); + stub._getServiceClient().setOptions(null); + } + } + + private OAuth2TokenValidationServiceStub createStub() throws OAuthTokenValidationException { + OAuth2TokenValidationServiceStub stub; + try { + stub = new OAuth2TokenValidationServiceStub(url); + ServiceClient client = stub._getServiceClient(); + client.getServiceContext().getConfigurationContext().setProperty( + HTTPConstants.CACHED_HTTP_CLIENT, httpClient); + + List
headerList = new ArrayList<>(); + Header header = new Header(); + header.setName(HTTPConstants.HEADER_AUTHORIZATION); + header.setValue(OAuthConstants.AUTHORIZATION_HEADER_PREFIX_BASIC + " " + basicAuthHeader); + headerList.add(header); + + Options options = client.getOptions(); + options.setProperty(HTTPConstants.HTTP_HEADERS, headerList); + options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true"); + client.setOptions(options); + } catch (AxisFault axisFault) { + throw new OAuthTokenValidationException("Exception occurred while creating the " + + "OAuth2TokenValidationServiceStub.", axisFault); + } + return stub; + } + +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java index 902c796b55..7b83a90923 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java @@ -27,6 +27,8 @@ import org.apache.tomcat.util.buf.MessageBytes; import org.wso2.carbon.webapp.authenticator.framework.Constants; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; +import java.util.Properties; + public class BasicAuthAuthenticator implements WebappAuthenticator { private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth"; @@ -55,6 +57,21 @@ public class BasicAuthAuthenticator implements WebappAuthenticator { return BasicAuthAuthenticator.BASIC_AUTH_AUTHENTICATOR; } + @Override + public String getProperty(String name) { + return null; + } + + @Override + public Properties getProperties() { + return null; + } + + @Override + public void setProperties(Properties properties) { + + } + private Credentials getCredentials(Request request) { Credentials credentials = null; MessageBytes authorization = diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index 2dd530c16f..cb59559ad5 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -15,6 +15,7 @@ import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkData import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; import java.security.cert.X509Certificate; +import java.util.Properties; /** * This authenticator authenticates HTTP requests using certificates. @@ -93,4 +94,20 @@ public class CertificateAuthenticator implements WebappAuthenticator { public String getName() { return CERTIFICATE_AUTHENTICATOR; } + + @Override + public String getProperty(String name) { + return null; + } + + @Override + public Properties getProperties() { + return null; + } + + @Override + public void setProperties(Properties properties) { + + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index 6e8439368a..a174fb09cb 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -39,6 +39,7 @@ import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkData import java.security.interfaces.RSAPublicKey; import java.text.ParseException; +import java.util.Properties; import java.util.StringTokenizer; /** @@ -141,4 +142,20 @@ public class JWTAuthenticator implements WebappAuthenticator { public String getName() { return JWTAuthenticator.JWT_AUTHENTICATOR; } + + @Override + public String getProperty(String name) { + return null; + } + + @Override + public Properties getProperties() { + return null; + } + + @Override + public void setProperties(Properties properties) { + + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index c82a57646b..095d70e578 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -24,16 +24,17 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; -import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; -import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.carbon.webapp.authenticator.framework.*; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; +import org.wso2.carbon.webapp.authenticator.framework.Constants; import org.wso2.carbon.webapp.authenticator.framework.Utils.Utils; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthValidatorFactory; +import java.util.Properties; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -46,9 +47,23 @@ public class OAuthAuthenticator implements WebappAuthenticator { private static final String BEARER_TOKEN_TYPE = "bearer"; private static final String RESOURCE_KEY = "resource"; + private Properties properties; + private OAuth2TokenValidator tokenValidator; private static final Log log = LogFactory.getLog(OAuthAuthenticator.class); + public OAuthAuthenticator() { + String url = properties.getProperty("TokenValidationEndpointUrl"); + String adminUsername = properties.getProperty("Username"); + String adminPassword = properties.getProperty("Password"); + boolean isRemote = Boolean.parseBoolean(properties.getProperty("IsRemote")); + + Properties validatorProperties = new Properties(); + validatorProperties.setProperty("MaxTotalConnections", properties.getProperty("MaxTotalConnections")); + validatorProperties.setProperty("MaxConnectionsPerHost", properties.getProperty("MaxTotalConnectionsPerHost")); + this.tokenValidator = OAuthValidatorFactory.getNewValidator(url, adminUsername, adminPassword, isRemote, validatorProperties); + } + @Override public boolean canHandle(Request request) { MessageBytes authorization = @@ -93,9 +108,8 @@ public class OAuthAuthenticator implements WebappAuthenticator { String bearerToken = this.getBearerToken(request); //Set the resource context param. This will be used in scope validation. String resource = requestUri + ":" + requestMethod; - //Get the appropriate OAuth validator from OAuthValidatorFactory. - OAuth2TokenValidator oAuth2TokenValidator = OAuthValidatorFactory.getValidator(); - OAuthValidationResponse oAuthValidationResponse = oAuth2TokenValidator.validateToken(bearerToken, resource); + + OAuthValidationResponse oAuthValidationResponse = tokenValidator.validateToken(bearerToken, resource); if (oAuthValidationResponse.isValid()) { String username = oAuthValidationResponse.getUserName(); @@ -127,6 +141,24 @@ public class OAuthAuthenticator implements WebappAuthenticator { return OAuthAuthenticator.OAUTH_AUTHENTICATOR; } + @Override + public String getProperty(String name) { + if (properties == null) { + return null; + } + return properties.getProperty(name); + } + + @Override + public Properties getProperties() { + return properties; + } + + @Override + public void setProperties(Properties properties) { + this.properties = properties; + } + private String getBearerToken(Request request) { MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders(). diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java index d3493e329d..7817ba10d3 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java @@ -22,6 +22,8 @@ import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; +import java.util.Properties; + public interface WebappAuthenticator { enum Status { @@ -34,4 +36,10 @@ public interface WebappAuthenticator { String getName(); + String getProperty(String name); + + Properties getProperties(); + + void setProperties(Properties properties); + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuth2TokenValidator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuth2TokenValidator.java index 50ef34081c..760058dbe3 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuth2TokenValidator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuth2TokenValidator.java @@ -31,4 +31,5 @@ public interface OAuth2TokenValidator { * @return OAuthValidationResponse with the validated results. */ OAuthValidationResponse validateToken(String accessToken, String resource) throws OAuthTokenValidationException; + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthValidatorFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthValidatorFactory.java index 44fefdf9bc..7bc293bbb3 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthValidatorFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthValidatorFactory.java @@ -21,6 +21,8 @@ import org.wso2.carbon.core.security.AuthenticatorsConfiguration; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.impl.RemoteOAuthValidator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.impl.LocalOAuthValidator; +import java.util.Properties; + /** * The class validate the configurations and provide the most suitable implementation according to the configuration. * Factory class for OAuthValidator. @@ -32,18 +34,19 @@ public class OAuthValidatorFactory { private static final String AUTHENTICATOR_CONFIG_ADMIN_USERNAME = "adminUsername"; private static final String AUTHENTICATOR_CONFIG_ADMIN_PASSWORD = "adminPassword"; private static final String AUTHENTICATOR_CONFIG_OAUTH_AUTHENTICATOR_NAME = "OAuthAuthenticator"; - private static String OAUTH_ENDPOINT_POSTFIX = + private static final String OAUTH_ENDPOINT_POSTFIX = "/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/"; /** * This factory method checks the authenticators.xml configuration file and provides an appropriate implementation * of OAuth2TokenValidator. + * * @return OAuth2TokenValidator */ public static OAuth2TokenValidator getValidator() throws IllegalArgumentException { AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration. - getAuthenticatorConfig(AUTHENTICATOR_CONFIG_OAUTH_AUTHENTICATOR_NAME); + getAuthenticatorConfig(AUTHENTICATOR_CONFIG_OAUTH_AUTHENTICATOR_NAME); boolean isRemote; String hostUrl; String adminUserName; @@ -54,18 +57,34 @@ public class OAuthValidatorFactory { hostUrl = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_HOST_URL); adminUserName = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_USERNAME); adminPassword = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_PASSWORD); - }else{ + } else { throw new IllegalArgumentException("OAuth Authenticator configuration parameters need to be defined in " + - "Authenticators.xml."); + "Authenticators.xml."); } if (isRemote) { if (!(hostUrl == null || hostUrl.trim().isEmpty())) { hostUrl = hostUrl + OAUTH_ENDPOINT_POSTFIX; - return new RemoteOAuthValidator(hostUrl, adminUserName, adminPassword); + return new RemoteOAuthValidator(hostUrl, adminUserName, adminPassword, null); } else { throw new IllegalArgumentException("Remote server host can't be empty in authenticators.xml."); } } return new LocalOAuthValidator(); } + + public static OAuth2TokenValidator getNewValidator( + String url, String adminUsername, String adminPassword, boolean isRemote, + Properties properties) throws IllegalArgumentException { + if (isRemote) { + if (!(url == null || url.trim().isEmpty())) { + url = url + OAUTH_ENDPOINT_POSTFIX; + return new RemoteOAuthValidator(url, adminUsername, adminPassword, properties); + } else { + throw new IllegalArgumentException("Remote server host can't be empty in OAuthAuthenticator " + + "configuration."); + } + } + return new LocalOAuthValidator(); + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java index 1a6142f390..58eb3a0611 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java @@ -23,12 +23,17 @@ import org.apache.axis2.client.ServiceClient; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Header; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.pool.ObjectPool; +import org.apache.commons.pool.impl.GenericObjectPool; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_TokenValidationContextParam; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import org.wso2.carbon.webapp.authenticator.framework.Utils.OAuthTokenValidationStubFactory; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthConstants; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; @@ -37,30 +42,25 @@ import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthV import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; +import java.util.Properties; /** * Handles the OAuth2 token validation from remote IS servers using remote OAuthValidation service-stub. */ public class RemoteOAuthValidator implements OAuth2TokenValidator { - private String hostURL; - private String adminUserName; - private String adminPassword; + private GenericObjectPool stubs; - public RemoteOAuthValidator(String hostURL, String adminUserName, String adminPassword) { - this.hostURL = hostURL; - this.adminUserName = adminUserName; - this.adminPassword = adminPassword; - } + private static final Log log = LogFactory.getLog(RemoteOAuthValidator.class); - private String getBasicAuthCredentials() { - byte[] bytesEncoded = Base64.encodeBase64((adminUserName + ":" + adminPassword).getBytes()); - return new String(bytesEncoded); + public RemoteOAuthValidator(String hostURL, String adminUserName, String adminPassword, Properties properties) { + this.stubs = new GenericObjectPool( + new OAuthTokenValidationStubFactory(hostURL, adminUserName, adminPassword, properties)); } @Override public OAuthValidationResponse validateToken(String accessToken, String resource) throws - OAuthTokenValidationException { + OAuthTokenValidationException { OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); OAuth2TokenValidationRequestDTO_OAuth2AccessToken oauthToken = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); @@ -79,29 +79,25 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator { tokenValidationContextParams[0] = resourceContextParam; validationRequest.setContext(tokenValidationContextParams); - OAuth2TokenValidationServiceStub tokenValidationService; - try { - tokenValidationService = new OAuth2TokenValidationServiceStub(hostURL); - } catch (AxisFault axisFault) { - throw new OAuthTokenValidationException("Exception occurred while obtaining the " + - "OAuth2TokenValidationServiceStub.", axisFault); - } - ServiceClient client = tokenValidationService._getServiceClient(); - Options options = client.getOptions(); - List
headerList = new ArrayList<>(); - Header header = new Header(); - header.setName(HTTPConstants.HEADER_AUTHORIZATION); - header.setValue(OAuthConstants.AUTHORIZATION_HEADER_PREFIX_BASIC + " " + getBasicAuthCredentials()); - headerList.add(header); - options.setProperty(HTTPConstants.HTTP_HEADERS, headerList); - client.setOptions(options); OAuth2TokenValidationResponseDTO tokenValidationResponse; + OAuth2TokenValidationServiceStub stub = null; try { - tokenValidationResponse = tokenValidationService. - findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); + stub = (OAuth2TokenValidationServiceStub) stubs.borrowObject(); + tokenValidationResponse = stub. + findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); } catch (RemoteException e) { - throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote IS server for " + - "OAuth2 token validation.", e); + throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote " + + "IS server for OAuth2 token validation.", e); + } catch (Exception e) { + throw new OAuthTokenValidationException("Error occurred while borrowing an oauth token validation " + + "service stub from the pool", e); + } finally { + try { + stubs.returnObject(stub); + } catch (Exception e) { + log.warn("Error occurred while returning the object back to the oauth token validation service " + + " stub pool", e); + } } boolean isValid = tokenValidationResponse.getValid(); String userName; @@ -115,6 +111,7 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator { oAuthValidationResponse.setErrorMsg(tokenValidationResponse.getErrorMsg()); return oAuthValidationResponse; } - return new OAuthValidationResponse(userName,tenantDomain,isValid); + return new OAuthValidationResponse(userName, tenantDomain, isValid); } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java index 6db4b46b03..d1669bed88 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java @@ -18,14 +18,18 @@ */ package org.wso2.carbon.webapp.authenticator.framework.config; +import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; @XmlRootElement(name = "Authenticator") public class AuthenticatorConfig { private String name; private String className; + private List params; @XmlElement(name = "Name", required = true) public String getName() { @@ -45,4 +49,35 @@ public class AuthenticatorConfig { this.className = className; } + @XmlElementWrapper(name = "Parameters", nillable = true) + @XmlElement(name = "Parameter", nillable = false) + public List getParams() { + return params; + } + + @XmlRootElement(name = "Parameter") + public static class Parameter { + private String name; + private String value; + + @XmlAttribute(name = "Name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlElement(name = "Value") + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java index 1fcb7a58c8..eef67ebaf7 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java @@ -36,6 +36,7 @@ import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticator import java.util.ArrayList; import java.util.List; +import java.util.Properties; /** * @scr.component name="org.wso2.carbon.webapp.authenticator" immediate="true" @@ -79,6 +80,13 @@ public class WebappAuthenticatorFrameworkServiceComponent { for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) { WebappAuthenticator authenticator = (WebappAuthenticator) Class.forName(config.getClassName()). newInstance(); + if (config.getParams() != null || !config.getParams().isEmpty()) { + Properties properties = new Properties(); + for (AuthenticatorConfig.Parameter param : config.getParams()) { + properties.setProperty(param.getName(), param.getValue()); + } + authenticator.setProperties(properties); + } repository.addAuthenticator(authenticator); } AuthenticatorFrameworkDataHolder.getInstance().setWebappAuthenticatorRepository(repository); diff --git a/pom.xml b/pom.xml index 15c69fe23d..238e9a596d 100644 --- a/pom.xml +++ b/pom.xml @@ -1263,6 +1263,12 @@ neethi ${neethi.version} + + + commons-pool.wso2 + commons-pool + ${commons.pool.wso2.version} + @@ -1554,8 +1560,10 @@ 2.0.4 2.0.4.wso2v4 - - github-scm + + github-scm + + 1.5.6.wso2v1 From 262e53ddcccf9080942bf783f8a715bfd4f0480f Mon Sep 17 00:00:00 2001 From: prabathabey Date: Sat, 19 Dec 2015 13:09:31 +0530 Subject: [PATCH 05/13] Further optimizing webapp authenticator valve implementation --- .../pom.xml | 3 ++- .../OAuthTokenValidationStubFactory.java | 13 ++++++----- .../authenticator/BasicAuthAuthenticator.java | 5 ++++ .../CertificateAuthenticator.java | 5 ++++ .../authenticator/JWTAuthenticator.java | 5 ++++ .../authenticator/OAuthAuthenticator.java | 23 ++++++++++++++++--- .../authenticator/WebappAuthenticator.java | 2 ++ .../framework/config/AuthenticatorConfig.java | 11 +++++---- ...uthenticatorFrameworkServiceComponent.java | 5 ++-- .../conf/webapp-authenticator-config.xml | 8 +++++++ 10 files changed, 63 insertions(+), 17 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 7684fb68e9..3414eea46f 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -112,7 +112,8 @@ org.apache.commons.pool.impl, org.apache.http.client, org.apache.http.conn, - org.apache.http.impl.client + org.apache.http.impl.client, + org.apache.http.impl.conn diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java index 85e22d4519..88ceb34aeb 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java @@ -31,6 +31,9 @@ import org.apache.commons.pool.PoolableObjectFactory; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthConstants; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; @@ -52,12 +55,10 @@ public class OAuthTokenValidationStubFactory implements PoolableObjectFactory { this.url = url; this.basicAuthHeader = new String(Base64.encodeBase64((adminUsername + ":" + adminPassword).getBytes())); - MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); - connectionManager.getParams().setDefaultMaxConnectionsPerHost( - Integer.parseInt(properties.getProperty("MaxConnectionsPerHost"))); - connectionManager.getParams().setMaxTotalConnections( - Integer.parseInt(properties.getProperty("MaxTotalConnections"))); - this.httpClient = new DefaultHttpClient((ClientConnectionManager) connectionManager); + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + connectionManager.setDefaultMaxPerRoute(Integer.parseInt(properties.getProperty("MaxConnectionsPerHost"))); + connectionManager.setMaxTotal(Integer.parseInt(properties.getProperty("MaxTotalConnections"))); + this.httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); } @Override diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java index 7b83a90923..06878d8ef8 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java @@ -33,6 +33,11 @@ public class BasicAuthAuthenticator implements WebappAuthenticator { private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth"; + @Override + public void init() { + + } + @Override public boolean canHandle(Request request) { MessageBytes authorization = diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index cb59559ad5..ec2880d539 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -26,6 +26,11 @@ public class CertificateAuthenticator implements WebappAuthenticator { private static final String CERTIFICATE_AUTHENTICATOR = "CertificateAuth"; private static final String CERTIFICATE_VERIFICATION_HEADER = "certificate-verification-header"; + @Override + public void init() { + + } + @Override public boolean canHandle(Request request) { String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index 0f4cb51015..d48e4d0a29 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -52,6 +52,11 @@ public class JWTAuthenticator implements WebappAuthenticator { private static final String JWT_AUTHENTICATOR = "JWT"; private static final String JWT_ASSERTION_HEADER = "X-JWT-Assertion"; + @Override + public void init() { + + } + @Override public boolean canHandle(Request request) { String authorizationHeader = request.getHeader(JWTAuthenticator.JWT_ASSERTION_HEADER); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 83838b87e1..1b29c9b389 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -52,16 +52,33 @@ public class OAuthAuthenticator implements WebappAuthenticator { private static final Log log = LogFactory.getLog(OAuthAuthenticator.class); - public OAuthAuthenticator() { + @Override + public void init() { + if (properties == null) { + throw new IllegalArgumentException("Required properties needed to initialize OAuthAuthenticator are " + + "not provided"); + } String url = properties.getProperty("TokenValidationEndpointUrl"); + if (url == null || url.isEmpty()) { + throw new IllegalArgumentException("OAuth token validation endpoint url is not provided"); + } String adminUsername = properties.getProperty("Username"); + if (adminUsername == null) { + throw new IllegalArgumentException("Username to connect to the OAuth token validation endpoint is " + + "not provided"); + } String adminPassword = properties.getProperty("Password"); + if (adminPassword == null) { + throw new IllegalArgumentException("Password to connect to the OAuth token validation endpoint is " + + "not provided"); + } boolean isRemote = Boolean.parseBoolean(properties.getProperty("IsRemote")); Properties validatorProperties = new Properties(); validatorProperties.setProperty("MaxTotalConnections", properties.getProperty("MaxTotalConnections")); - validatorProperties.setProperty("MaxConnectionsPerHost", properties.getProperty("MaxTotalConnectionsPerHost")); - this.tokenValidator = OAuthValidatorFactory.getNewValidator(url, adminUsername, adminPassword, isRemote, validatorProperties); + validatorProperties.setProperty("MaxConnectionsPerHost", properties.getProperty("MaxConnectionsPerHost")); + this.tokenValidator = + OAuthValidatorFactory.getNewValidator(url, adminUsername, adminPassword, isRemote, validatorProperties); } @Override diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java index 7817ba10d3..5090920624 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java @@ -30,6 +30,8 @@ public interface WebappAuthenticator { SUCCESS, FAILURE, CONTINUE } + void init(); + boolean canHandle(Request request); AuthenticationInfo authenticate(Request request, Response response); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java index d1669bed88..6a36ba2498 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java @@ -18,10 +18,7 @@ */ package org.wso2.carbon.webapp.authenticator.framework.config; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.*; import java.util.List; @XmlRootElement(name = "Authenticator") @@ -55,6 +52,10 @@ public class AuthenticatorConfig { return params; } + public void setParams(List params) { + this.params = params; + } + @XmlRootElement(name = "Parameter") public static class Parameter { private String name; @@ -69,7 +70,7 @@ public class AuthenticatorConfig { this.name = name; } - @XmlElement(name = "Value") + @XmlValue public String getValue() { return value; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java index eef67ebaf7..c2684f9c97 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java @@ -80,13 +80,14 @@ public class WebappAuthenticatorFrameworkServiceComponent { for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) { WebappAuthenticator authenticator = (WebappAuthenticator) Class.forName(config.getClassName()). newInstance(); - if (config.getParams() != null || !config.getParams().isEmpty()) { + if (config.getParams() != null && !config.getParams().isEmpty()) { Properties properties = new Properties(); for (AuthenticatorConfig.Parameter param : config.getParams()) { properties.setProperty(param.getName(), param.getValue()); } authenticator.setProperties(properties); } + authenticator.init(); repository.addAuthenticator(authenticator); } AuthenticatorFrameworkDataHolder.getInstance().setWebappAuthenticatorRepository(repository); @@ -99,7 +100,7 @@ public class WebappAuthenticatorFrameworkServiceComponent { log.debug("Web Application Authenticator Framework Bundle has been started successfully"); } } catch (Throwable e) { - log.error("Error occurred while initializing the bundle", e); + log.error("Error occurred while initializing the bundle", e); } } diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml index 067d8cd3ce..5099328df7 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml @@ -3,6 +3,14 @@ OAuth org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator + + https://localhost:9443 + admin + admin + true + 10000 + 10000 + BasicAuth From 337afa5da2a6b38b838a9d92df78fd0f067e375f Mon Sep 17 00:00:00 2001 From: prabathabey Date: Sat, 19 Dec 2015 13:27:45 +0530 Subject: [PATCH 06/13] Revert "Further optimizing webapp authenticator valve implementation" This reverts commit 262e53ddcccf9080942bf783f8a715bfd4f0480f. --- .../pom.xml | 3 +-- .../OAuthTokenValidationStubFactory.java | 13 +++++------ .../authenticator/BasicAuthAuthenticator.java | 5 ---- .../CertificateAuthenticator.java | 5 ---- .../authenticator/JWTAuthenticator.java | 5 ---- .../authenticator/OAuthAuthenticator.java | 23 +++---------------- .../authenticator/WebappAuthenticator.java | 2 -- .../framework/config/AuthenticatorConfig.java | 11 ++++----- ...uthenticatorFrameworkServiceComponent.java | 5 ++-- .../conf/webapp-authenticator-config.xml | 8 ------- 10 files changed, 17 insertions(+), 63 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 3414eea46f..7684fb68e9 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -112,8 +112,7 @@ org.apache.commons.pool.impl, org.apache.http.client, org.apache.http.conn, - org.apache.http.impl.client, - org.apache.http.impl.conn + org.apache.http.impl.client diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java index 88ceb34aeb..85e22d4519 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java @@ -31,9 +31,6 @@ import org.apache.commons.pool.PoolableObjectFactory; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthConstants; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; @@ -55,10 +52,12 @@ public class OAuthTokenValidationStubFactory implements PoolableObjectFactory { this.url = url; this.basicAuthHeader = new String(Base64.encodeBase64((adminUsername + ":" + adminPassword).getBytes())); - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setDefaultMaxPerRoute(Integer.parseInt(properties.getProperty("MaxConnectionsPerHost"))); - connectionManager.setMaxTotal(Integer.parseInt(properties.getProperty("MaxTotalConnections"))); - this.httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); + MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); + connectionManager.getParams().setDefaultMaxConnectionsPerHost( + Integer.parseInt(properties.getProperty("MaxConnectionsPerHost"))); + connectionManager.getParams().setMaxTotalConnections( + Integer.parseInt(properties.getProperty("MaxTotalConnections"))); + this.httpClient = new DefaultHttpClient((ClientConnectionManager) connectionManager); } @Override diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java index 06878d8ef8..7b83a90923 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java @@ -33,11 +33,6 @@ public class BasicAuthAuthenticator implements WebappAuthenticator { private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth"; - @Override - public void init() { - - } - @Override public boolean canHandle(Request request) { MessageBytes authorization = diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index ec2880d539..cb59559ad5 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -26,11 +26,6 @@ public class CertificateAuthenticator implements WebappAuthenticator { private static final String CERTIFICATE_AUTHENTICATOR = "CertificateAuth"; private static final String CERTIFICATE_VERIFICATION_HEADER = "certificate-verification-header"; - @Override - public void init() { - - } - @Override public boolean canHandle(Request request) { String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index d48e4d0a29..0f4cb51015 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -52,11 +52,6 @@ public class JWTAuthenticator implements WebappAuthenticator { private static final String JWT_AUTHENTICATOR = "JWT"; private static final String JWT_ASSERTION_HEADER = "X-JWT-Assertion"; - @Override - public void init() { - - } - @Override public boolean canHandle(Request request) { String authorizationHeader = request.getHeader(JWTAuthenticator.JWT_ASSERTION_HEADER); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 1b29c9b389..83838b87e1 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -52,33 +52,16 @@ public class OAuthAuthenticator implements WebappAuthenticator { private static final Log log = LogFactory.getLog(OAuthAuthenticator.class); - @Override - public void init() { - if (properties == null) { - throw new IllegalArgumentException("Required properties needed to initialize OAuthAuthenticator are " + - "not provided"); - } + public OAuthAuthenticator() { String url = properties.getProperty("TokenValidationEndpointUrl"); - if (url == null || url.isEmpty()) { - throw new IllegalArgumentException("OAuth token validation endpoint url is not provided"); - } String adminUsername = properties.getProperty("Username"); - if (adminUsername == null) { - throw new IllegalArgumentException("Username to connect to the OAuth token validation endpoint is " + - "not provided"); - } String adminPassword = properties.getProperty("Password"); - if (adminPassword == null) { - throw new IllegalArgumentException("Password to connect to the OAuth token validation endpoint is " + - "not provided"); - } boolean isRemote = Boolean.parseBoolean(properties.getProperty("IsRemote")); Properties validatorProperties = new Properties(); validatorProperties.setProperty("MaxTotalConnections", properties.getProperty("MaxTotalConnections")); - validatorProperties.setProperty("MaxConnectionsPerHost", properties.getProperty("MaxConnectionsPerHost")); - this.tokenValidator = - OAuthValidatorFactory.getNewValidator(url, adminUsername, adminPassword, isRemote, validatorProperties); + validatorProperties.setProperty("MaxConnectionsPerHost", properties.getProperty("MaxTotalConnectionsPerHost")); + this.tokenValidator = OAuthValidatorFactory.getNewValidator(url, adminUsername, adminPassword, isRemote, validatorProperties); } @Override diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java index 5090920624..7817ba10d3 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java @@ -30,8 +30,6 @@ public interface WebappAuthenticator { SUCCESS, FAILURE, CONTINUE } - void init(); - boolean canHandle(Request request); AuthenticationInfo authenticate(Request request, Response response); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java index 6a36ba2498..d1669bed88 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java @@ -18,7 +18,10 @@ */ package org.wso2.carbon.webapp.authenticator.framework.config; -import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @XmlRootElement(name = "Authenticator") @@ -52,10 +55,6 @@ public class AuthenticatorConfig { return params; } - public void setParams(List params) { - this.params = params; - } - @XmlRootElement(name = "Parameter") public static class Parameter { private String name; @@ -70,7 +69,7 @@ public class AuthenticatorConfig { this.name = name; } - @XmlValue + @XmlElement(name = "Value") public String getValue() { return value; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java index c2684f9c97..eef67ebaf7 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java @@ -80,14 +80,13 @@ public class WebappAuthenticatorFrameworkServiceComponent { for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) { WebappAuthenticator authenticator = (WebappAuthenticator) Class.forName(config.getClassName()). newInstance(); - if (config.getParams() != null && !config.getParams().isEmpty()) { + if (config.getParams() != null || !config.getParams().isEmpty()) { Properties properties = new Properties(); for (AuthenticatorConfig.Parameter param : config.getParams()) { properties.setProperty(param.getName(), param.getValue()); } authenticator.setProperties(properties); } - authenticator.init(); repository.addAuthenticator(authenticator); } AuthenticatorFrameworkDataHolder.getInstance().setWebappAuthenticatorRepository(repository); @@ -100,7 +99,7 @@ public class WebappAuthenticatorFrameworkServiceComponent { log.debug("Web Application Authenticator Framework Bundle has been started successfully"); } } catch (Throwable e) { - log.error("Error occurred while initializing the bundle", e); + log.error("Error occurred while initializing the bundle", e); } } diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml index 5099328df7..067d8cd3ce 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml @@ -3,14 +3,6 @@ OAuth org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator - - https://localhost:9443 - admin - admin - true - 10000 - 10000 - BasicAuth From b5b4e50b25767d1453b70e9c0e77c3c0397a4d35 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Sat, 19 Dec 2015 13:28:24 +0530 Subject: [PATCH 07/13] Revert "Improving performance of webapp authenticator valve implementation" This reverts commit 36462e2e4e1ede4166e128e3d89e49dd3965182c. --- .../pom.xml | 10 +- .../OAuthTokenValidationStubFactory.java | 119 ------------------ .../authenticator/BasicAuthAuthenticator.java | 17 --- .../CertificateAuthenticator.java | 17 --- .../authenticator/JWTAuthenticator.java | 17 --- .../authenticator/OAuthAuthenticator.java | 46 ++----- .../authenticator/WebappAuthenticator.java | 8 -- .../oauth/OAuth2TokenValidator.java | 1 - .../oauth/OAuthValidatorFactory.java | 29 +---- .../oauth/impl/RemoteOAuthValidator.java | 63 +++++----- .../framework/config/AuthenticatorConfig.java | 35 ------ ...uthenticatorFrameworkServiceComponent.java | 8 -- pom.xml | 12 +- 13 files changed, 49 insertions(+), 333 deletions(-) delete mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 7684fb68e9..3dad448cc6 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -105,15 +105,9 @@ org.apache.axis2.client, org.apache.commons.codec.binary, org.apache.commons.httpclient, - org.wso2.carbon.core.security, - org.apache.axis2.context, - org.apache.commons.httpclient.params, - org.apache.commons.pool, - org.apache.commons.pool.impl, - org.apache.http.client, - org.apache.http.conn, - org.apache.http.impl.client + org.wso2.carbon.core.security + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java deleted file mode 100644 index 85e22d4519..0000000000 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.webapp.authenticator.framework.Utils; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.pool.PoolableObjectFactory; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.impl.client.DefaultHttpClient; -import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; -import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthConstants; -import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -public class OAuthTokenValidationStubFactory implements PoolableObjectFactory { - - private String url; - private String basicAuthHeader; - private static final Log log = LogFactory.getLog(OAuthTokenValidationStubFactory.class); - - private HttpClient httpClient; - - public OAuthTokenValidationStubFactory(String url, String adminUsername, String adminPassword, - Properties properties) { - this.url = url; - this.basicAuthHeader = new String(Base64.encodeBase64((adminUsername + ":" + adminPassword).getBytes())); - - MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); - connectionManager.getParams().setDefaultMaxConnectionsPerHost( - Integer.parseInt(properties.getProperty("MaxConnectionsPerHost"))); - connectionManager.getParams().setMaxTotalConnections( - Integer.parseInt(properties.getProperty("MaxTotalConnections"))); - this.httpClient = new DefaultHttpClient((ClientConnectionManager) connectionManager); - } - - @Override - public Object makeObject() throws Exception { - return this.createStub(); - } - - @Override - public void destroyObject(Object o) throws Exception { - - } - - @Override - public boolean validateObject(Object o) { - return true; - } - - @Override - public void activateObject(Object o) throws Exception { - if (log.isDebugEnabled()) { - log.debug("OAuth token validate stub instance is activated"); - } - } - - @Override - public void passivateObject(Object o) throws Exception { - if (o instanceof OAuth2TokenValidationServiceStub) { - OAuth2TokenValidationServiceStub stub = (OAuth2TokenValidationServiceStub) o; - stub._getServiceClient().cleanupTransport(); - stub._getServiceClient().setOptions(null); - } - } - - private OAuth2TokenValidationServiceStub createStub() throws OAuthTokenValidationException { - OAuth2TokenValidationServiceStub stub; - try { - stub = new OAuth2TokenValidationServiceStub(url); - ServiceClient client = stub._getServiceClient(); - client.getServiceContext().getConfigurationContext().setProperty( - HTTPConstants.CACHED_HTTP_CLIENT, httpClient); - - List
headerList = new ArrayList<>(); - Header header = new Header(); - header.setName(HTTPConstants.HEADER_AUTHORIZATION); - header.setValue(OAuthConstants.AUTHORIZATION_HEADER_PREFIX_BASIC + " " + basicAuthHeader); - headerList.add(header); - - Options options = client.getOptions(); - options.setProperty(HTTPConstants.HTTP_HEADERS, headerList); - options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true"); - client.setOptions(options); - } catch (AxisFault axisFault) { - throw new OAuthTokenValidationException("Exception occurred while creating the " + - "OAuth2TokenValidationServiceStub.", axisFault); - } - return stub; - } - -} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java index 7b83a90923..902c796b55 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java @@ -27,8 +27,6 @@ import org.apache.tomcat.util.buf.MessageBytes; import org.wso2.carbon.webapp.authenticator.framework.Constants; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; -import java.util.Properties; - public class BasicAuthAuthenticator implements WebappAuthenticator { private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth"; @@ -57,21 +55,6 @@ public class BasicAuthAuthenticator implements WebappAuthenticator { return BasicAuthAuthenticator.BASIC_AUTH_AUTHENTICATOR; } - @Override - public String getProperty(String name) { - return null; - } - - @Override - public Properties getProperties() { - return null; - } - - @Override - public void setProperties(Properties properties) { - - } - private Credentials getCredentials(Request request) { Credentials credentials = null; MessageBytes authorization = diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index cb59559ad5..2dd530c16f 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -15,7 +15,6 @@ import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkData import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; import java.security.cert.X509Certificate; -import java.util.Properties; /** * This authenticator authenticates HTTP requests using certificates. @@ -94,20 +93,4 @@ public class CertificateAuthenticator implements WebappAuthenticator { public String getName() { return CERTIFICATE_AUTHENTICATOR; } - - @Override - public String getProperty(String name) { - return null; - } - - @Override - public Properties getProperties() { - return null; - } - - @Override - public void setProperties(Properties properties) { - - } - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index 0f4cb51015..16aeabc848 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -39,7 +39,6 @@ import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkData import java.security.interfaces.RSAPublicKey; import java.text.ParseException; -import java.util.Properties; import java.util.StringTokenizer; /** @@ -138,20 +137,4 @@ public class JWTAuthenticator implements WebappAuthenticator { public String getName() { return JWTAuthenticator.JWT_AUTHENTICATOR; } - - @Override - public String getProperty(String name) { - return null; - } - - @Override - public Properties getProperties() { - return null; - } - - @Override - public void setProperties(Properties properties) { - - } - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 83838b87e1..06bfe4f99d 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -24,17 +24,16 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; -import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException; -import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil; -import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; -import org.wso2.carbon.webapp.authenticator.framework.Constants; +import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; +import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import org.wso2.carbon.webapp.authenticator.framework.*; import org.wso2.carbon.webapp.authenticator.framework.Utils.Utils; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthValidatorFactory; -import java.util.Properties; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -47,23 +46,9 @@ public class OAuthAuthenticator implements WebappAuthenticator { private static final String BEARER_TOKEN_TYPE = "bearer"; private static final String RESOURCE_KEY = "resource"; - private Properties properties; - private OAuth2TokenValidator tokenValidator; private static final Log log = LogFactory.getLog(OAuthAuthenticator.class); - public OAuthAuthenticator() { - String url = properties.getProperty("TokenValidationEndpointUrl"); - String adminUsername = properties.getProperty("Username"); - String adminPassword = properties.getProperty("Password"); - boolean isRemote = Boolean.parseBoolean(properties.getProperty("IsRemote")); - - Properties validatorProperties = new Properties(); - validatorProperties.setProperty("MaxTotalConnections", properties.getProperty("MaxTotalConnections")); - validatorProperties.setProperty("MaxConnectionsPerHost", properties.getProperty("MaxTotalConnectionsPerHost")); - this.tokenValidator = OAuthValidatorFactory.getNewValidator(url, adminUsername, adminPassword, isRemote, validatorProperties); - } - @Override public boolean canHandle(Request request) { MessageBytes authorization = @@ -108,8 +93,9 @@ public class OAuthAuthenticator implements WebappAuthenticator { String bearerToken = this.getBearerToken(request); //Set the resource context param. This will be used in scope validation. String resource = requestUri + ":" + requestMethod; - - OAuthValidationResponse oAuthValidationResponse = tokenValidator.validateToken(bearerToken, resource); + //Get the appropriate OAuth validator from OAuthValidatorFactory. + OAuth2TokenValidator oAuth2TokenValidator = OAuthValidatorFactory.getValidator(); + OAuthValidationResponse oAuthValidationResponse = oAuth2TokenValidator.validateToken(bearerToken, resource); if (oAuthValidationResponse.isValid()) { String username = oAuthValidationResponse.getUserName(); @@ -141,24 +127,6 @@ public class OAuthAuthenticator implements WebappAuthenticator { return OAuthAuthenticator.OAUTH_AUTHENTICATOR; } - @Override - public String getProperty(String name) { - if (properties == null) { - return null; - } - return properties.getProperty(name); - } - - @Override - public Properties getProperties() { - return properties; - } - - @Override - public void setProperties(Properties properties) { - this.properties = properties; - } - private String getBearerToken(Request request) { MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders(). diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java index 7817ba10d3..d3493e329d 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java @@ -22,8 +22,6 @@ import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; -import java.util.Properties; - public interface WebappAuthenticator { enum Status { @@ -36,10 +34,4 @@ public interface WebappAuthenticator { String getName(); - String getProperty(String name); - - Properties getProperties(); - - void setProperties(Properties properties); - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuth2TokenValidator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuth2TokenValidator.java index 760058dbe3..50ef34081c 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuth2TokenValidator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuth2TokenValidator.java @@ -31,5 +31,4 @@ public interface OAuth2TokenValidator { * @return OAuthValidationResponse with the validated results. */ OAuthValidationResponse validateToken(String accessToken, String resource) throws OAuthTokenValidationException; - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthValidatorFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthValidatorFactory.java index 7bc293bbb3..44fefdf9bc 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthValidatorFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthValidatorFactory.java @@ -21,8 +21,6 @@ import org.wso2.carbon.core.security.AuthenticatorsConfiguration; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.impl.RemoteOAuthValidator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.impl.LocalOAuthValidator; -import java.util.Properties; - /** * The class validate the configurations and provide the most suitable implementation according to the configuration. * Factory class for OAuthValidator. @@ -34,19 +32,18 @@ public class OAuthValidatorFactory { private static final String AUTHENTICATOR_CONFIG_ADMIN_USERNAME = "adminUsername"; private static final String AUTHENTICATOR_CONFIG_ADMIN_PASSWORD = "adminPassword"; private static final String AUTHENTICATOR_CONFIG_OAUTH_AUTHENTICATOR_NAME = "OAuthAuthenticator"; - private static final String OAUTH_ENDPOINT_POSTFIX = + private static String OAUTH_ENDPOINT_POSTFIX = "/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/"; /** * This factory method checks the authenticators.xml configuration file and provides an appropriate implementation * of OAuth2TokenValidator. - * * @return OAuth2TokenValidator */ public static OAuth2TokenValidator getValidator() throws IllegalArgumentException { AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration. - getAuthenticatorConfig(AUTHENTICATOR_CONFIG_OAUTH_AUTHENTICATOR_NAME); + getAuthenticatorConfig(AUTHENTICATOR_CONFIG_OAUTH_AUTHENTICATOR_NAME); boolean isRemote; String hostUrl; String adminUserName; @@ -57,34 +54,18 @@ public class OAuthValidatorFactory { hostUrl = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_HOST_URL); adminUserName = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_USERNAME); adminPassword = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_PASSWORD); - } else { + }else{ throw new IllegalArgumentException("OAuth Authenticator configuration parameters need to be defined in " + - "Authenticators.xml."); + "Authenticators.xml."); } if (isRemote) { if (!(hostUrl == null || hostUrl.trim().isEmpty())) { hostUrl = hostUrl + OAUTH_ENDPOINT_POSTFIX; - return new RemoteOAuthValidator(hostUrl, adminUserName, adminPassword, null); + return new RemoteOAuthValidator(hostUrl, adminUserName, adminPassword); } else { throw new IllegalArgumentException("Remote server host can't be empty in authenticators.xml."); } } return new LocalOAuthValidator(); } - - public static OAuth2TokenValidator getNewValidator( - String url, String adminUsername, String adminPassword, boolean isRemote, - Properties properties) throws IllegalArgumentException { - if (isRemote) { - if (!(url == null || url.trim().isEmpty())) { - url = url + OAUTH_ENDPOINT_POSTFIX; - return new RemoteOAuthValidator(url, adminUsername, adminPassword, properties); - } else { - throw new IllegalArgumentException("Remote server host can't be empty in OAuthAuthenticator " + - "configuration."); - } - } - return new LocalOAuthValidator(); - } - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java index 58eb3a0611..1a6142f390 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java @@ -23,17 +23,12 @@ import org.apache.axis2.client.ServiceClient; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Header; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.pool.ObjectPool; -import org.apache.commons.pool.impl.GenericObjectPool; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_TokenValidationContextParam; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.carbon.webapp.authenticator.framework.Utils.OAuthTokenValidationStubFactory; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthConstants; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException; @@ -42,25 +37,30 @@ import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthV import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; -import java.util.Properties; /** * Handles the OAuth2 token validation from remote IS servers using remote OAuthValidation service-stub. */ public class RemoteOAuthValidator implements OAuth2TokenValidator { - private GenericObjectPool stubs; + private String hostURL; + private String adminUserName; + private String adminPassword; - private static final Log log = LogFactory.getLog(RemoteOAuthValidator.class); + public RemoteOAuthValidator(String hostURL, String adminUserName, String adminPassword) { + this.hostURL = hostURL; + this.adminUserName = adminUserName; + this.adminPassword = adminPassword; + } - public RemoteOAuthValidator(String hostURL, String adminUserName, String adminPassword, Properties properties) { - this.stubs = new GenericObjectPool( - new OAuthTokenValidationStubFactory(hostURL, adminUserName, adminPassword, properties)); + private String getBasicAuthCredentials() { + byte[] bytesEncoded = Base64.encodeBase64((adminUserName + ":" + adminPassword).getBytes()); + return new String(bytesEncoded); } @Override public OAuthValidationResponse validateToken(String accessToken, String resource) throws - OAuthTokenValidationException { + OAuthTokenValidationException { OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); OAuth2TokenValidationRequestDTO_OAuth2AccessToken oauthToken = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); @@ -79,25 +79,29 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator { tokenValidationContextParams[0] = resourceContextParam; validationRequest.setContext(tokenValidationContextParams); + OAuth2TokenValidationServiceStub tokenValidationService; + try { + tokenValidationService = new OAuth2TokenValidationServiceStub(hostURL); + } catch (AxisFault axisFault) { + throw new OAuthTokenValidationException("Exception occurred while obtaining the " + + "OAuth2TokenValidationServiceStub.", axisFault); + } + ServiceClient client = tokenValidationService._getServiceClient(); + Options options = client.getOptions(); + List
headerList = new ArrayList<>(); + Header header = new Header(); + header.setName(HTTPConstants.HEADER_AUTHORIZATION); + header.setValue(OAuthConstants.AUTHORIZATION_HEADER_PREFIX_BASIC + " " + getBasicAuthCredentials()); + headerList.add(header); + options.setProperty(HTTPConstants.HTTP_HEADERS, headerList); + client.setOptions(options); OAuth2TokenValidationResponseDTO tokenValidationResponse; - OAuth2TokenValidationServiceStub stub = null; try { - stub = (OAuth2TokenValidationServiceStub) stubs.borrowObject(); - tokenValidationResponse = stub. - findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); + tokenValidationResponse = tokenValidationService. + findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); } catch (RemoteException e) { - throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote " + - "IS server for OAuth2 token validation.", e); - } catch (Exception e) { - throw new OAuthTokenValidationException("Error occurred while borrowing an oauth token validation " + - "service stub from the pool", e); - } finally { - try { - stubs.returnObject(stub); - } catch (Exception e) { - log.warn("Error occurred while returning the object back to the oauth token validation service " + - " stub pool", e); - } + throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote IS server for " + + "OAuth2 token validation.", e); } boolean isValid = tokenValidationResponse.getValid(); String userName; @@ -111,7 +115,6 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator { oAuthValidationResponse.setErrorMsg(tokenValidationResponse.getErrorMsg()); return oAuthValidationResponse; } - return new OAuthValidationResponse(userName, tenantDomain, isValid); + return new OAuthValidationResponse(userName,tenantDomain,isValid); } - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java index d1669bed88..6db4b46b03 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java @@ -18,18 +18,14 @@ */ package org.wso2.carbon.webapp.authenticator.framework.config; -import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; @XmlRootElement(name = "Authenticator") public class AuthenticatorConfig { private String name; private String className; - private List params; @XmlElement(name = "Name", required = true) public String getName() { @@ -49,35 +45,4 @@ public class AuthenticatorConfig { this.className = className; } - @XmlElementWrapper(name = "Parameters", nillable = true) - @XmlElement(name = "Parameter", nillable = false) - public List getParams() { - return params; - } - - @XmlRootElement(name = "Parameter") - public static class Parameter { - private String name; - private String value; - - @XmlAttribute(name = "Name") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @XmlElement(name = "Value") - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - } - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java index eef67ebaf7..1fcb7a58c8 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java @@ -36,7 +36,6 @@ import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticator import java.util.ArrayList; import java.util.List; -import java.util.Properties; /** * @scr.component name="org.wso2.carbon.webapp.authenticator" immediate="true" @@ -80,13 +79,6 @@ public class WebappAuthenticatorFrameworkServiceComponent { for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) { WebappAuthenticator authenticator = (WebappAuthenticator) Class.forName(config.getClassName()). newInstance(); - if (config.getParams() != null || !config.getParams().isEmpty()) { - Properties properties = new Properties(); - for (AuthenticatorConfig.Parameter param : config.getParams()) { - properties.setProperty(param.getName(), param.getValue()); - } - authenticator.setProperties(properties); - } repository.addAuthenticator(authenticator); } AuthenticatorFrameworkDataHolder.getInstance().setWebappAuthenticatorRepository(repository); diff --git a/pom.xml b/pom.xml index 238e9a596d..15c69fe23d 100644 --- a/pom.xml +++ b/pom.xml @@ -1263,12 +1263,6 @@ neethi ${neethi.version} - - - commons-pool.wso2 - commons-pool - ${commons.pool.wso2.version} - @@ -1560,10 +1554,8 @@ 2.0.4 2.0.4.wso2v4 - - github-scm - - 1.5.6.wso2v1 + + github-scm From 11957f1e478f884cc1f100debb4bbc8290c0901c Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 21 Dec 2015 11:00:42 +0530 Subject: [PATCH 08/13] Pooling OAuth token validator stub initialization --- .../pom.xml | 28 +++++ .../OAuthTokenValidationStubFactory.java | 115 ++++++++++++++++-- .../framework/WebappAuthenticatorFactory.java | 3 +- .../oauth/impl/RemoteOAuthValidator.java | 67 ++++++---- .../test/WebappAuthenticatorConfigTest.java | 64 ++++++++++ .../WebappAuthenticatorFrameworkUtilTest.java | 106 ++++++++++++++++ .../etc/webapp-authenticator-config.xml | 28 +++++ .../src/test/resources/log4j.properties | 32 +++++ .../src/test/resources/testng.xml | 37 ++++++ pom.xml | 18 ++- 10 files changed, 458 insertions(+), 40 deletions(-) create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/test/WebappAuthenticatorConfigTest.java create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/test/WebappAuthenticatorFrameworkUtilTest.java create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/config/etc/webapp-authenticator-config.xml create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/log4j.properties create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 3414eea46f..84a78d27d4 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -118,6 +118,18 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + + file:src/test/resources/log4j.properties + + + src/test/resources/testng.xml + + + @@ -182,6 +194,22 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.common + + org.apache.httpcomponents.wso2 + httpclient + + + commons-httpclient.wso2 + commons-httpclient + + + org.testng + testng + + + commons-pool.wso2 + commons-pool + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java index 88ceb34aeb..95fbc86a44 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java @@ -24,15 +24,14 @@ import org.apache.axis2.client.ServiceClient; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.pool.PoolableObjectFactory; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthConstants; @@ -46,19 +45,94 @@ public class OAuthTokenValidationStubFactory implements PoolableObjectFactory { private String url; private String basicAuthHeader; - private static final Log log = LogFactory.getLog(OAuthTokenValidationStubFactory.class); - private HttpClient httpClient; + private static final Log log = LogFactory.getLog(OAuthTokenValidationStubFactory.class); + public OAuthTokenValidationStubFactory(String url, String adminUsername, String adminPassword, Properties properties) { + this.validateUrl(url); this.url = url; + + this.validateCredentials(adminUsername, adminPassword); this.basicAuthHeader = new String(Base64.encodeBase64((adminUsername + ":" + adminPassword).getBytes())); + HttpConnectionManager connectionManager = this.createConnectionManager(properties); + this.httpClient = new HttpClient(connectionManager); + } + + /** + * Creates an instance of MultiThreadedHttpConnectionManager using HttpClient 3.x APIs + * + * @param properties Properties to configure MultiThreadedHttpConnectionManager + * @return An instance of properly configured MultiThreadedHttpConnectionManager + */ + private HttpConnectionManager createConnectionManager(Properties properties) { + HttpConnectionManagerParams params = new HttpConnectionManagerParams(); + if (properties == null || properties.isEmpty()) { + throw new IllegalArgumentException("Parameters required to initialize HttpClient instances " + + "associated with OAuth token validation service stub are not provided"); + } + String maxConnectionsPerHostParam = properties.getProperty("MaxConnectionsPerHost"); + if (maxConnectionsPerHostParam == null || maxConnectionsPerHostParam.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("MaxConnectionsPerHost parameter is not explicitly defined. Therefore, the default, " + + "which is 2, will be used"); + } + } else { + params.setDefaultMaxConnectionsPerHost(Integer.parseInt(maxConnectionsPerHostParam)); + } + + String maxTotalConnectionsParam = properties.getProperty("MaxTotalConnections"); + if (maxTotalConnectionsParam == null || maxTotalConnectionsParam.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("MaxTotalConnections parameter is not explicitly defined. Therefore, the default, " + + "which is 10, will be used"); + } + } else { + params.setMaxTotalConnections(Integer.parseInt(maxTotalConnectionsParam)); + } + HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); + connectionManager.setParams(params); + return connectionManager; + } + + /** + * Creates an instance of PoolingHttpClientConnectionManager using HttpClient 4.x APIs + * + * @param properties Properties to configure PoolingHttpClientConnectionManager + * @return An instance of properly configured PoolingHttpClientConnectionManager + */ + private HttpClientConnectionManager createClientConnectionManager(Properties properties) { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - connectionManager.setDefaultMaxPerRoute(Integer.parseInt(properties.getProperty("MaxConnectionsPerHost"))); - connectionManager.setMaxTotal(Integer.parseInt(properties.getProperty("MaxTotalConnections"))); - this.httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); + if (properties != null) { + String maxConnectionsPerHostParam = properties.getProperty("MaxConnectionsPerHost"); + if (maxConnectionsPerHostParam == null || maxConnectionsPerHostParam.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("MaxConnectionsPerHost parameter is not explicitly defined. Therefore, the default, " + + "which is 2, will be used"); + } + } else { + connectionManager.setDefaultMaxPerRoute(Integer.parseInt(maxConnectionsPerHostParam)); + } + + String maxTotalConnectionsParam = properties.getProperty("MaxTotalConnections"); + if (maxTotalConnectionsParam == null || maxTotalConnectionsParam.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("MaxTotalConnections parameter is not explicitly defined. Therefore, the default, " + + "which is 10, will be used"); + } + } else { + connectionManager.setMaxTotal(Integer.parseInt(maxTotalConnectionsParam)); + } + } else { + if (log.isDebugEnabled()) { + log.debug("Properties, i.e. MaxTotalConnections/MaxConnectionsPerHost, required to tune the " + + "HttpClient used in OAuth token validation service stub instances are not provided. " + + "Therefore, the defaults, 2/10 respectively, will be used"); + } + } + return connectionManager; } @Override @@ -88,7 +162,6 @@ public class OAuthTokenValidationStubFactory implements PoolableObjectFactory { if (o instanceof OAuth2TokenValidationServiceStub) { OAuth2TokenValidationServiceStub stub = (OAuth2TokenValidationServiceStub) o; stub._getServiceClient().cleanupTransport(); - stub._getServiceClient().setOptions(null); } } @@ -111,10 +184,28 @@ public class OAuthTokenValidationStubFactory implements PoolableObjectFactory { options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true"); client.setOptions(options); } catch (AxisFault axisFault) { - throw new OAuthTokenValidationException("Exception occurred while creating the " + + throw new OAuthTokenValidationException("Error occurred while creating the " + "OAuth2TokenValidationServiceStub.", axisFault); } return stub; } + private void validateUrl(String url) { + if (url == null || url.isEmpty()) { + throw new IllegalArgumentException("Url provided as the endpoint of the OAuth token validation service " + + "is null"); + } + } + + private void validateCredentials(String adminUsername, String adminPassword) { + if (adminUsername == null || adminUsername.isEmpty()) { + throw new IllegalArgumentException("An appropriate username required to initialize OAuth token " + + "validation service stub factory hasn't been provided"); + } + if (adminPassword == null || adminPassword.isEmpty()) { + throw new IllegalArgumentException("An appropriate password required to initialize OAuth token " + + "validation service stub factory hasn't been provided"); + } + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java index 9613b18c00..c211e74e9b 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java @@ -26,7 +26,8 @@ import java.util.Map; public class WebappAuthenticatorFactory { public static WebappAuthenticator getAuthenticator(String authScheme) { - return AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticator(authScheme); + return AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository(). + getAuthenticator(authScheme); } public static WebappAuthenticator getAuthenticator(Request request) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java index 58eb3a0611..3811d64807 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java @@ -59,36 +59,21 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator { } @Override - public OAuthValidationResponse validateToken(String accessToken, String resource) throws - OAuthTokenValidationException { - OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); - OAuth2TokenValidationRequestDTO_OAuth2AccessToken oauthToken = - new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); - oauthToken.setTokenType(OAuthConstants.BEARER_TOKEN_TYPE); - oauthToken.setIdentifier(accessToken); - validationRequest.setAccessToken(oauthToken); - - //Set the resource context param. This will be used in scope validation. - OAuth2TokenValidationRequestDTO_TokenValidationContextParam resourceContextParam = new - OAuth2TokenValidationRequestDTO_TokenValidationContextParam(); - resourceContextParam.setKey(OAuthConstants.RESOURCE_KEY); - resourceContextParam.setValue(resource); - - OAuth2TokenValidationRequestDTO_TokenValidationContextParam[] tokenValidationContextParams = - new OAuth2TokenValidationRequestDTO_TokenValidationContextParam[1]; - tokenValidationContextParams[0] = resourceContextParam; - validationRequest.setContext(tokenValidationContextParams); - - OAuth2TokenValidationResponseDTO tokenValidationResponse; + public OAuthValidationResponse validateToken(String accessToken, + String resource) throws OAuthTokenValidationException { OAuth2TokenValidationServiceStub stub = null; + OAuth2TokenValidationResponseDTO validationResponse; try { + OAuth2TokenValidationRequestDTO validationRequest = this.createValidationRequest(accessToken, resource); stub = (OAuth2TokenValidationServiceStub) stubs.borrowObject(); - tokenValidationResponse = stub. + validationResponse = stub. findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); } catch (RemoteException e) { throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote " + "IS server for OAuth2 token validation.", e); } catch (Exception e) { + /* In this particular instance, generic exceptions are caught as enforced by the pooling library + used to pool stubs created to invoke OAuth token validation service */ throw new OAuthTokenValidationException("Error occurred while borrowing an oauth token validation " + "service stub from the pool", e); } finally { @@ -99,19 +84,49 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator { " stub pool", e); } } - boolean isValid = tokenValidationResponse.getValid(); + + if (validationResponse == null) { + if (log.isDebugEnabled()) { + log.debug("Response returned by the OAuth token validation service is null"); + } + return null; + } + String userName; String tenantDomain; + boolean isValid = validationResponse.getValid(); if (isValid) { userName = MultitenantUtils.getTenantAwareUsername( - tokenValidationResponse.getAuthorizedUser()); - tenantDomain = MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser()); + validationResponse.getAuthorizedUser()); + tenantDomain = MultitenantUtils.getTenantDomain(validationResponse.getAuthorizedUser()); } else { OAuthValidationResponse oAuthValidationResponse = new OAuthValidationResponse(); - oAuthValidationResponse.setErrorMsg(tokenValidationResponse.getErrorMsg()); + oAuthValidationResponse.setErrorMsg(validationResponse.getErrorMsg()); return oAuthValidationResponse; } return new OAuthValidationResponse(userName, tenantDomain, isValid); } + private OAuth2TokenValidationRequestDTO createValidationRequest(String accessToken, String resource) { + OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); + OAuth2TokenValidationRequestDTO_OAuth2AccessToken oauthToken = + new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); + oauthToken.setTokenType(OAuthConstants.BEARER_TOKEN_TYPE); + oauthToken.setIdentifier(accessToken); + validationRequest.setAccessToken(oauthToken); + + //Set the resource context param. This will be used in scope validation. + OAuth2TokenValidationRequestDTO_TokenValidationContextParam resourceContextParam = new + OAuth2TokenValidationRequestDTO_TokenValidationContextParam(); + resourceContextParam.setKey(OAuthConstants.RESOURCE_KEY); + resourceContextParam.setValue(resource); + + OAuth2TokenValidationRequestDTO_TokenValidationContextParam[] tokenValidationContextParams = + new OAuth2TokenValidationRequestDTO_TokenValidationContextParam[1]; + tokenValidationContextParams[0] = resourceContextParam; + validationRequest.setContext(tokenValidationContextParams); + + return validationRequest; + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/test/WebappAuthenticatorConfigTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/test/WebappAuthenticatorConfigTest.java new file mode 100644 index 0000000000..8ea931a8eb --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/test/WebappAuthenticatorConfigTest.java @@ -0,0 +1,64 @@ +/* + * 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.test; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.utils.ServerConstants; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkException; +import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig; +import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticatorConfig; + +import java.util.List; + +public class WebappAuthenticatorConfigTest { + + @BeforeClass + public void init() { + System.setProperty(ServerConstants.CARBON_CONFIG_DIR_PATH, "src/test/resources/config"); + } + + @Test + public void testConfigInitialization() { + try { + WebappAuthenticatorConfig.init(); + + WebappAuthenticatorConfig config = WebappAuthenticatorConfig.getInstance(); + Assert.assertNotNull(config); + + List authConfigs = config.getAuthenticators(); + Assert.assertNotNull(authConfigs); + } catch (AuthenticatorFrameworkException e) { + Assert.fail("Error occurred while testing webapp authenticator config initialization", e); + } catch (Throwable e) { + Assert.fail("Unexpected error has been encountered while testing webapp authenticator config " + + "initialization", e); + } + } + + @AfterClass + public void cleanup() { + System.setProperty(ServerConstants.CARBON_CONFIG_DIR_PATH, ""); + } + +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/test/WebappAuthenticatorFrameworkUtilTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/test/WebappAuthenticatorFrameworkUtilTest.java new file mode 100644 index 0000000000..1ad1975b08 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/test/WebappAuthenticatorFrameworkUtilTest.java @@ -0,0 +1,106 @@ +/* + * 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.test; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.pool.ObjectPool; +import org.apache.commons.pool.impl.GenericObjectPool; +import org.testng.Assert; +import org.testng.annotations.Test; +import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; +import org.wso2.carbon.webapp.authenticator.framework.Utils.OAuthTokenValidationStubFactory; + +import java.util.Properties; + +public class WebappAuthenticatorFrameworkUtilTest { + + private static final Log log = LogFactory.getLog(WebappAuthenticatorFrameworkUtilTest.class); + + private static final String TOKEN_VALIDATION_SERVICE_URL = "https://localhost:9443"; + private static final String ADMIN_USERNAME = "admin"; + private static final String ADMIN_PASSWORD = "admin"; + private static final Properties PROPERTIES = new Properties(); + + static { + PROPERTIES.setProperty("MaxTotalConnections", "100"); + PROPERTIES.setProperty("MaxConnectionsPerHost", "100"); + } + + @Test + public void testOAuthTokenValidatorStubPool() { + ObjectPool stubs = null; + OAuth2TokenValidationServiceStub stub = null; + + try { + stubs = new GenericObjectPool( + new OAuthTokenValidationStubFactory( + TOKEN_VALIDATION_SERVICE_URL, ADMIN_USERNAME, ADMIN_PASSWORD, PROPERTIES)); + + stub = (OAuth2TokenValidationServiceStub) stubs.borrowObject(); + Assert.assertNotNull(stub); + } catch (Exception e) { + String msg = "Error occurred while borrowing an oauth validator service stub instance from the pool"; + log.error(msg, e); + Assert.fail(msg, e); + } finally { + if (stubs != null) { + try { + if (stub != null) { + stubs.returnObject(stub); + } + } catch (Exception e) { + log.warn("Error occurred while returning oauth validator service stub instance to the pool", e); + } + + /* Checks if the stub instance used above has been properly returned to the pool */ + Assert.assertEquals(stubs.getNumIdle(), 1); + /* Verifies that there's no hanging connections after the operation performed above */ + Assert.assertEquals(stubs.getNumActive(), 0); + + try { + stubs.close(); + } catch (Exception e) { + log.warn("Error occurred while closing the object pool", e); + } + } + } + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testStubFactoryInitWithInvalidHttpClientProperties() { + new OAuthTokenValidationStubFactory(TOKEN_VALIDATION_SERVICE_URL, null, ADMIN_PASSWORD, PROPERTIES); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testStubFactoryInitWithInvalidUsername() { + new OAuthTokenValidationStubFactory(TOKEN_VALIDATION_SERVICE_URL, null, ADMIN_PASSWORD, PROPERTIES); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testStubFactoryInitWithInvalidPassword() { + new OAuthTokenValidationStubFactory(TOKEN_VALIDATION_SERVICE_URL, ADMIN_USERNAME, null, PROPERTIES); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testStubFactoryInitWithInvalidUrl() { + new OAuthTokenValidationStubFactory(null, ADMIN_USERNAME, ADMIN_PASSWORD, PROPERTIES); + } + +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/config/etc/webapp-authenticator-config.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/config/etc/webapp-authenticator-config.xml new file mode 100644 index 0000000000..5099328df7 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/config/etc/webapp-authenticator-config.xml @@ -0,0 +1,28 @@ + + + + OAuth + org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator + + https://localhost:9443 + admin + admin + true + 10000 + 10000 + + + + BasicAuth + org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticator + + + JWT + org.wso2.carbon.webapp.authenticator.framework.authenticator.JWTAuthenticator + + + CertificateAuth + org.wso2.carbon.webapp.authenticator.framework.authenticator.CertificateAuthenticator + + + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/log4j.properties b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/log4j.properties new file mode 100644 index 0000000000..a625c80cd5 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/log4j.properties @@ -0,0 +1,32 @@ +# +# Copyright 2009 WSO2, Inc. (http://wso2.com) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# +# This is the log4j configuration file used by WSO2 Carbon +# +# IMPORTANT : Please do not remove or change the names of any +# of the Appenders defined here. The layout pattern & log file +# can be changed using the WSO2 Carbon Management Console, and those +# settings will override the settings in this file. +# + +log4j.rootLogger=ERROR, STD_OUT + +# Redirect log messages to console +log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender +log4j.appender.STD_OUT.Target=System.out +log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout +log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml new file mode 100644 index 0000000000..8b9832e2e6 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 238e9a596d..5e9edd5c3b 100644 --- a/pom.xml +++ b/pom.xml @@ -1263,12 +1263,21 @@ neethi ${neethi.version} - commons-pool.wso2 commons-pool ${commons.pool.wso2.version} + + org.apache.httpcomponents.wso2 + httpclient + ${httpcomponents.httpclient.version} + + + commons-httpclient.wso2 + commons-httpclient + ${commons.httpclient.version} + @@ -1380,6 +1389,11 @@ build-helper-maven-plugin 1.8 + + org.apache.maven.plugins + maven-surefire-plugin + 2.18 + @@ -1564,6 +1578,8 @@ github-scm 1.5.6.wso2v1 + 4.2.3.wso2v1 + 3.1.0.wso2v2 From 0cdc139a0b8203efee18f96b54f264e8b31da461 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 21 Dec 2015 11:57:50 +0530 Subject: [PATCH 09/13] Adding updated webapp authenticator config --- .../oauth/impl/RemoteOAuthValidator.java | 29 ++++++++++++------- .../conf/webapp-authenticator-config.xml | 8 +++++ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java index 5175899397..7700941382 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java @@ -43,27 +43,33 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator { private static final Log log = LogFactory.getLog(RemoteOAuthValidator.class); public RemoteOAuthValidator(String hostURL, String adminUserName, String adminPassword, Properties properties) { - this.stubs = new GenericObjectPool(new OAuthTokenValidationStubFactory(hostURL, adminUserName, adminPassword, properties)); + this.stubs = + new GenericObjectPool(new OAuthTokenValidationStubFactory( + hostURL, adminUserName, adminPassword, properties)); } - public OAuthValidationResponse validateToken(String accessToken, String resource) throws OAuthTokenValidationException { + public OAuthValidationResponse validateToken(String accessToken, + String resource) throws OAuthTokenValidationException { OAuth2TokenValidationServiceStub stub = null; OAuth2TokenValidationResponseDTO validationResponse; try { OAuth2TokenValidationRequestDTO validationRequest = createValidationRequest(accessToken, resource); stub = (OAuth2TokenValidationServiceStub) this.stubs.borrowObject(); - validationResponse = stub.findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); + validationResponse = + stub.findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); } catch (RemoteException e) { - throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote IS server for OAuth2 token validation.", e); + throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote " + + "IS server for OAuth2 token validation.", e); } catch (Exception e) { - throw new OAuthTokenValidationException("Error occurred while borrowing an oauth token validation service stub from the pool", e); + throw new OAuthTokenValidationException("Error occurred while borrowing an oauth token validation " + + "service stub from the pool", e); } finally { try { this.stubs.returnObject(stub); } catch (Exception e) { - log.warn("Error occurred while returning the object back to the oauth token validation service stub pool", e); + log.warn("Error occurred while returning the object back to the oauth token validation service " + + "stub pool", e); } - } if (validationResponse == null) { @@ -89,18 +95,21 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator { private OAuth2TokenValidationRequestDTO createValidationRequest(String accessToken, String resource) { OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); - OAuth2TokenValidationRequestDTO_OAuth2AccessToken oauthToken = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); + OAuth2TokenValidationRequestDTO_OAuth2AccessToken oauthToken = + new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); oauthToken.setTokenType("bearer"); oauthToken.setIdentifier(accessToken); validationRequest.setAccessToken(oauthToken); - OAuth2TokenValidationRequestDTO_TokenValidationContextParam resourceContextParam = new OAuth2TokenValidationRequestDTO_TokenValidationContextParam(); + OAuth2TokenValidationRequestDTO_TokenValidationContextParam resourceContextParam = + new OAuth2TokenValidationRequestDTO_TokenValidationContextParam(); resourceContextParam.setKey("resource"); resourceContextParam.setValue(resource); - OAuth2TokenValidationRequestDTO_TokenValidationContextParam[] tokenValidationContextParams = new OAuth2TokenValidationRequestDTO_TokenValidationContextParam[1]; + OAuth2TokenValidationRequestDTO_TokenValidationContextParam[] tokenValidationContextParams = + new OAuth2TokenValidationRequestDTO_TokenValidationContextParam[1]; tokenValidationContextParams[0] = resourceContextParam; validationRequest.setContext(tokenValidationContextParams); diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml index 067d8cd3ce..5507b059e1 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml @@ -3,6 +3,14 @@ OAuth org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator + + true + https://localhost:9443 + admin + admin + 100 + 100 + BasicAuth From 67e1bfb012ff51b514f59953e6d1585255af391f Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 21 Dec 2015 12:23:59 +0530 Subject: [PATCH 10/13] Making attribute names schema compliant and code cleanup --- .../framework/config/AuthenticatorConfig.java | 9 +++++---- ...WebappAuthenticatorFrameworkServiceComponent.java | 3 ++- .../resources/conf/webapp-authenticator-config.xml | 12 ++++++------ 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java index 0fed4f50e2..a5aab6319f 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/AuthenticatorConfig.java @@ -46,8 +46,8 @@ public class AuthenticatorConfig { this.className = className; } - @XmlElementWrapper(name="Parameters", nillable=true) - @XmlElement(name="Parameter", nillable=false) + @XmlElementWrapper(name = "Parameters", nillable = true) + @XmlElement(name = "Parameter", nillable = false) public List getParams() { return this.params; } @@ -55,12 +55,13 @@ public class AuthenticatorConfig { public void setParams(List params) { this.params = params; } - @XmlRootElement(name="Parameter") + + @XmlRootElement(name = "Parameter") public static class Parameter { private String name; private String value; - @XmlAttribute(name="Name") + @XmlAttribute(name = "Name") public String getName() { return this.name; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java index 926a6eed51..c81ae13f4b 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java @@ -78,7 +78,8 @@ public class WebappAuthenticatorFrameworkServiceComponent { WebappAuthenticatorConfig.init(); WebappAuthenticatorRepository repository = new WebappAuthenticatorRepository(); for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) { - WebappAuthenticator authenticator = (WebappAuthenticator)Class.forName(config.getClassName()).newInstance(); + WebappAuthenticator authenticator = + (WebappAuthenticator) Class.forName(config.getClassName()).newInstance(); if ((config.getParams() != null) && (!config.getParams().isEmpty())) { Properties properties = new Properties(); diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml index 5507b059e1..a9e0c9d832 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml @@ -4,12 +4,12 @@ OAuth org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator - true - https://localhost:9443 - admin - admin - 100 - 100 + true + https://localhost:9443 + admin + admin + 100 + 100 From a61fe6171a54bd9d583b56109b85b2e12ea2e4e0 Mon Sep 17 00:00:00 2001 From: harshanl Date: Mon, 21 Dec 2015 14:22:09 +0530 Subject: [PATCH 11/13] Refactored pagination code --- .../device/mgt/common/PaginationRequest.java | 15 ++-- .../carbon/device/mgt/core/dao/DeviceDAO.java | 37 ++++----- .../core/dao/impl/AbstractDeviceDAOImpl.java | 18 ++-- .../dao/impl/device/GenericDeviceDAOImpl.java | 41 +++++---- .../dao/impl/device/OracleDeviceDAOImpl.java | 83 +++++++++---------- .../impl/device/PostgreSQLDeviceDAOImpl.java | 81 +++++++++--------- .../impl/device/SQLServerDeviceDAOImpl.java | 83 +++++++++---------- .../DeviceManagementProviderService.java | 20 ++--- .../DeviceManagementProviderServiceImpl.java | 33 ++++---- 9 files changed, 202 insertions(+), 209 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java index ae813f50a8..9934bcd61c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java @@ -27,10 +27,15 @@ public class PaginationRequest { private int rowCount; private String owner; private String status; - private String type; + private String deviceType; private String deviceName; private String ownership; + public PaginationRequest(int start, int rowCount) { + this.startIndex = start; + this.rowCount = rowCount; + } + public int getStartIndex() { return startIndex; } @@ -63,12 +68,12 @@ public class PaginationRequest { this.status = status; } - public String getType() { - return type; + public String getDeviceType() { + return deviceType; } - public void setType(String type) { - this.type = type; + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; } public String getDeviceName() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 6b204b008d..d154e8ae91 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -38,7 +38,7 @@ public interface DeviceDAO { * @return returns the device count of given type. * @throws DeviceManagementDAOException */ - int getDeviceCount(String type, int tenantId) throws DeviceManagementDAOException; + int getDeviceCountByType(String type, int tenantId) throws DeviceManagementDAOException; /** * This method is used to get the device count by user. @@ -68,7 +68,7 @@ public interface DeviceDAO { * @return returns the device count of given status. * @throws DeviceManagementDAOException */ - int getDeviceCount(EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException; + int getDeviceCountByStatus(String status, int tenantId) throws DeviceManagementDAOException; /** * This method is used to get the device count by ownership. @@ -78,7 +78,7 @@ public interface DeviceDAO { * @return returns the device count of given ownership. * @throws DeviceManagementDAOException */ - int getDeviceCountByOwnership(EnrolmentInfo.OwnerShip ownerShip, int tenantId) throws DeviceManagementDAOException; + int getDeviceCountByOwnership(String ownerShip, int tenantId) throws DeviceManagementDAOException; /** * This method is used to add a device. @@ -174,13 +174,12 @@ public interface DeviceDAO { /** * This method is used to retrieve the devices of a given tenant and type as a paginated result. * - * @param type device type. - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination and search. * @param tenantId tenant id. * @return returns paginated list of devices of provided type. * @throws DeviceManagementDAOException */ - List getDevices(String type, PaginationRequest request, int tenantId) throws DeviceManagementDAOException; + List getDevicesByType(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; /** * This method is used to retrieve all the devices of a given tenant and device type. @@ -203,15 +202,14 @@ public interface DeviceDAO { List getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException; /** - * This method is used to retrieve devices of a given user. + * This method is used to retrieve devices of a given user as a paginated result. * - * @param username user name. - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination and search data. * @param tenantId tenant id. * @return returns paginated list of devices in which owner matches (search) with given username. * @throws DeviceManagementDAOException */ - List getDevicesOfUser(String username, PaginationRequest request, int tenantId) throws DeviceManagementDAOException; + List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; /** * This method is used to retrieve the device count of a given tenant. @@ -251,15 +249,14 @@ public interface DeviceDAO { List getDevicesByName(String deviceName, int tenantId) throws DeviceManagementDAOException; /** - * This method is used to retrieve devices of a given device name. + * This method is used to retrieve devices of a given device name as a paginated result. * - * @param deviceName device name. - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination and device search info. * @param tenantId tenant id. * @return returns paginated list of devices which name matches (search) given device-name. * @throws DeviceManagementDAOException */ - List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + List getDevicesByName(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; /** @@ -320,27 +317,25 @@ public interface DeviceDAO { List getDevicesByStatus(EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException; /** - * This method is used to retrieve devices of a given ownership. + * This method is used to retrieve devices of a given ownership as a paginated result. * - * @param ownerShip Ownership of devices. - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination and device search. * @param tenantId tenant id. * @return returns list of devices of given ownership. * @throws DeviceManagementDAOException */ - List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, int tenantId) + List getDevicesByOwnership(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; /** - * This method is used to retrieve devices of a given enrollment status. + * This method is used to retrieve devices of a given enrollment status as a paginated result * - * @param status enrollment status. * @param request PaginationRequest object holding the data for pagination * @param tenantId tenant id. * @return returns paginated list of devices of given status. * @throws DeviceManagementDAOException */ - List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, int tenantId) + List getDevicesByStatus(PaginationRequest request, 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/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index c1e4718df1..a41b2c8054 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -368,7 +368,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - String deviceType = request.getType(); + String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; String deviceName = request.getDeviceName(); boolean isDeviceNameProvided = false; @@ -415,7 +415,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { stmt.setInt(1, tenantId); int paramIdx = 2; if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getType()); + stmt.setString(paramIdx++, request.getDeviceType()); } if (isDeviceNameProvided) { stmt.setString(paramIdx++, request.getDeviceName() + "%"); @@ -444,7 +444,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } @Override - public int getDeviceCount(String type, int tenantId) throws DeviceManagementDAOException { + public int getDeviceCountByType(String type, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; @@ -478,11 +478,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT COUNT(e1.DEVICE_ID) AS DEVICE_COUNT FROM DM_DEVICE d, (SELECT e.DEVICE_ID " + - "FROM DM_ENROLMENT e WHERE e.TENANT_ID = ? AND e.OWNER LIKE ?) " + + "FROM DM_ENROLMENT e WHERE e.TENANT_ID = ? AND e.OWNER = ?) " + "e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID AND t.ID = d.DEVICE_TYPE_ID"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, username + "%"); + stmt.setString(2, username); ResultSet rs = stmt.executeQuery(); if (rs.next()) { @@ -526,7 +526,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } @Override - public int getDeviceCountByOwnership(EnrolmentInfo.OwnerShip ownerShip, int tenantId) throws DeviceManagementDAOException { + public int getDeviceCountByOwnership(String ownerShip, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; int deviceCount = 0; @@ -537,7 +537,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "DM_DEVICE_TYPE t WHERE d.ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, ownerShip.toString()); + stmt.setString(2, ownerShip); stmt.setInt(3, tenantId); ResultSet rs = stmt.executeQuery(); @@ -554,7 +554,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } @Override - public int getDeviceCount(Status status, int tenantId) throws DeviceManagementDAOException { + public int getDeviceCountByStatus(String status, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; int deviceCount = 0; @@ -565,7 +565,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "DM_DEVICE_TYPE t WHERE d.ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, status.toString()); + stmt.setString(2, status); stmt.setInt(3, tenantId); ResultSet rs = stmt.executeQuery(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 134ccb8dff..e009fd6343 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -19,7 +19,6 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; @@ -45,7 +44,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { PreparedStatement stmt = null; ResultSet rs = null; List devices = null; - String deviceType = request.getType(); + String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; String deviceName = request.getDeviceName(); boolean isDeviceNameProvided = false; @@ -98,7 +97,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setInt(1, tenantId); int paramIdx = 2; if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getType()); + stmt.setString(paramIdx++, request.getDeviceType()); } if (isDeviceNameProvided) { stmt.setString(paramIdx++, request.getDeviceName() + "%"); @@ -131,7 +130,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevices(String type, PaginationRequest request, int tenantId) + public List getDevicesByType(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -146,7 +145,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, type); + stmt.setString(1, request.getDeviceType()); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); @@ -158,7 +157,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + type + "'", e); + throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + request.getDeviceType() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -166,7 +165,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesOfUser(String username, PaginationRequest request, int tenantId) + public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -177,11 +176,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND e.OWNER LIKE ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + "AND t.ID = d.DEVICE_TYPE_ID LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, username + "%"); + stmt.setString(2, request.getOwner()); stmt.setInt(3, request.getStartIndex()); stmt.setInt(4, request.getRowCount()); ResultSet rs = stmt.executeQuery(); @@ -192,7 +191,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + - username + "'", e); + request.getOwner() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -200,7 +199,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + public List getDevicesByName(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -214,7 +213,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceName + "%"); + stmt.setString(1, request.getDeviceName() + "%"); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); @@ -227,7 +226,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + - "'" + deviceName + "'", e); + "'" + request.getDeviceName() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -235,8 +234,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, - int tenantId) throws DeviceManagementDAOException { + public List getDevicesByOwnership(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); @@ -250,7 +249,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, ownerShip.toString()); + stmt.setString(2, request.getOwnership()); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); stmt.setInt(5, request.getRowCount()); @@ -262,7 +261,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + - "'" + ownerShip + "'", e); + "'" + request.getOwnership() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -270,8 +269,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, - int tenantId) throws DeviceManagementDAOException { + public List getDevicesByStatus(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); @@ -285,7 +284,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, status.toString()); + stmt.setString(2, request.getStatus()); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); stmt.setInt(5, request.getRowCount()); @@ -297,7 +296,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + - "'" + status + "'", e); + "'" + request.getStatus() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index c75162ae4a..c5612c22c0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -19,7 +19,6 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; @@ -46,7 +45,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { PreparedStatement stmt = null; ResultSet rs = null; List devices = null; - String deviceType = request.getType(); + String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; String deviceName = request.getDeviceName(); boolean isDeviceNameProvided = false; @@ -99,7 +98,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setInt(1, tenantId); int paramIdx = 2; if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getType()); + stmt.setString(paramIdx++, request.getDeviceType()); } if (isDeviceNameProvided) { stmt.setString(paramIdx++, request.getDeviceName() + "%"); @@ -132,7 +131,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevices(String type, PaginationRequest request, int tenantId) + public List getDevicesByType(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -147,7 +146,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); - stmt.setString(1, type); + stmt.setString(1, request.getDeviceType()); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); @@ -159,7 +158,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + type + "'", e); + throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + request.getDeviceType() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -167,7 +166,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesOfUser(String username, PaginationRequest request, int tenantId) + public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -178,11 +177,11 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND e.OWNER LIKE ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + "AND t.ID = d.DEVICE_TYPE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, username + "%"); + stmt.setString(2, request.getOwner()); stmt.setInt(3, request.getStartIndex()); stmt.setInt(4, request.getRowCount()); ResultSet rs = stmt.executeQuery(); @@ -193,7 +192,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + - username + "'", e); + request.getOwner() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -201,23 +200,22 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, - int tenantId) throws DeviceManagementDAOException { + public List getDevicesByName(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + - "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? ROWS" + - " FETCH NEXT ? ROWS ONLY"; + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, status.toString()); + stmt.setString(1, request.getDeviceName() + "%"); + stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); stmt.setInt(5, request.getRowCount()); @@ -228,8 +226,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + - "'" + status + "'", e); + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + + "'" + request.getDeviceName() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -237,22 +235,23 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + public List getDevicesByOwnership(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + - "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + - "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? " + + "ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceName + "%"); - stmt.setInt(2, tenantId); + stmt.setInt(1, tenantId); + stmt.setString(2, request.getOwnership()); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); stmt.setInt(5, request.getRowCount()); @@ -263,8 +262,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + - "'" + deviceName + "'", e); + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + + "'" + request.getOwnership() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -272,8 +271,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, - int tenantId) throws DeviceManagementDAOException { + public List getDevicesByStatus(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); @@ -283,12 +282,12 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? " + - "ROWS FETCH NEXT ? ROWS ONLY"; + "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? ROWS" + + " FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, ownerShip.toString()); + stmt.setString(2, request.getStatus()); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); stmt.setInt(5, request.getRowCount()); @@ -299,8 +298,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + - "'" + ownerShip + "'", e); + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + + "'" + request.getStatus() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index ce22de94f9..00ed10661b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -19,7 +19,6 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; @@ -45,7 +44,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { PreparedStatement stmt = null; ResultSet rs = null; List devices = null; - String deviceType = request.getType(); + String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; String deviceName = request.getDeviceName(); boolean isDeviceNameProvided = false; @@ -98,7 +97,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setInt(1, tenantId); int paramIdx = 2; if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getType()); + stmt.setString(paramIdx++, request.getDeviceType()); } if (isDeviceNameProvided) { stmt.setString(paramIdx++, request.getDeviceName() + "%"); @@ -113,8 +112,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { if (isStatusProvided) { stmt.setString(paramIdx++, request.getStatus()); } - stmt.setInt(paramIdx, request.getRowCount()); - stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + stmt.setInt(paramIdx, request.getStartIndex()); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -131,7 +130,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevices(String type, PaginationRequest request, int tenantId) + public List getDevicesByType(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -146,7 +145,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, type); + stmt.setString(1, request.getDeviceType()); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); stmt.setInt(4, request.getRowCount()); @@ -158,7 +157,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + type + "'", e); + throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + request.getDeviceType() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -166,7 +165,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesOfUser(String username, PaginationRequest request, int tenantId) + public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -177,11 +176,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND e.OWNER LIKE ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + "AND t.ID = d.DEVICE_TYPE_ID LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, username + "%"); + stmt.setString(2, request.getOwner()); stmt.setInt(3, request.getRowCount()); stmt.setInt(4, request.getStartIndex()); ResultSet rs = stmt.executeQuery(); @@ -192,7 +191,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + - username + "'", e); + request.getOwner() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -200,22 +199,22 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, - int tenantId) throws DeviceManagementDAOException { + public List getDevicesByName(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + - "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?"; + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, status.toString()); + stmt.setString(1, request.getDeviceName() + "%"); + stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); stmt.setInt(4, request.getRowCount()); stmt.setInt(5, request.getStartIndex()); @@ -226,8 +225,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + - "'" + status + "'", e); + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + + "'" + request.getDeviceName() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -235,22 +234,22 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + public List getDevicesByOwnership(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + - "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + - "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceName + "%"); - stmt.setInt(2, tenantId); + stmt.setInt(1, tenantId); + stmt.setString(2, request.getOwnership()); stmt.setInt(3, tenantId); stmt.setInt(4, request.getRowCount()); stmt.setInt(5, request.getStartIndex()); @@ -261,8 +260,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + - "'" + deviceName + "'", e); + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + + "'" + request.getOwnership() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -270,8 +269,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, - int tenantId) throws DeviceManagementDAOException { + public List getDevicesByStatus(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); @@ -281,11 +280,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, ownerShip.toString()); + stmt.setString(2, request.getStatus()); stmt.setInt(3, tenantId); stmt.setInt(4, request.getRowCount()); stmt.setInt(5, request.getStartIndex()); @@ -296,8 +295,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + - "'" + ownerShip + "'", e); + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + + "'" + request.getStatus() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 393712fb5a..e3ecf07f22 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -19,7 +19,6 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; @@ -45,7 +44,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { PreparedStatement stmt = null; ResultSet rs = null; List devices = null; - String deviceType = request.getType(); + String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; String deviceName = request.getDeviceName(); boolean isDeviceNameProvided = false; @@ -98,7 +97,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setInt(1, tenantId); int paramIdx = 2; if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getType()); + stmt.setString(paramIdx++, request.getDeviceType()); } if (isDeviceNameProvided) { stmt.setString(paramIdx++, request.getDeviceName() + "%"); @@ -131,7 +130,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevices(String type, PaginationRequest request, int tenantId) + public List getDevicesByType(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -146,7 +145,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); - stmt.setString(1, type); + stmt.setString(1, request.getDeviceType()); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); @@ -158,7 +157,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + type + "'", e); + throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + request.getDeviceType() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -166,7 +165,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesOfUser(String username, PaginationRequest request, int tenantId) + public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -177,11 +176,11 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND e.OWNER LIKE ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + "AND t.ID = d.DEVICE_TYPE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, username + "%"); + stmt.setString(2, request.getOwner()); stmt.setInt(3, request.getStartIndex()); stmt.setInt(4, request.getRowCount()); ResultSet rs = stmt.executeQuery(); @@ -192,7 +191,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + - username + "'", e); + request.getOwner() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -200,23 +199,22 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request, - int tenantId) throws DeviceManagementDAOException { + public List getDevicesByName(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + - "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? ROWS" + - " FETCH NEXT ? ROWS ONLY"; + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, status.toString()); + stmt.setString(1, request.getDeviceName() + "%"); + stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); stmt.setInt(5, request.getRowCount()); @@ -227,8 +225,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + - "'" + status + "'", e); + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + + "'" + request.getDeviceName() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -236,22 +234,23 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByName(String deviceName, PaginationRequest request, int tenantId) + public List getDevicesByOwnership(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + - "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + - "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? " + + "ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceName + "%"); - stmt.setInt(2, tenantId); + stmt.setInt(1, tenantId); + stmt.setString(2, request.getOwnership()); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); stmt.setInt(5, request.getRowCount()); @@ -262,8 +261,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + - "'" + deviceName + "'", e); + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + + "'" + request.getOwnership() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -271,8 +270,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request, - int tenantId) throws DeviceManagementDAOException { + public List getDevicesByStatus(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; List devices = new ArrayList<>(); @@ -282,12 +281,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? " + - "ROWS FETCH NEXT ? ROWS ONLY"; + "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? ROWS" + + " FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setString(2, ownerShip.toString()); + stmt.setString(2, request.getStatus()); stmt.setInt(3, tenantId); stmt.setInt(4, request.getStartIndex()); stmt.setInt(5, request.getRowCount()); @@ -298,8 +297,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { devices.add(device); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + - "'" + ownerShip + "'", e); + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to status " + + "'" + request.getStatus() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 8c1a3cb7f3..7538844755 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -42,13 +42,12 @@ public interface DeviceManagementProviderService extends OperationManager { /** * Method to retrieve all the devices with pagination support. * - * @param deviceType Device platform * @param request PaginationRequest object holding the data for pagination * @return PaginationResult - Result including the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the * devices. */ - PaginationResult getAllDevices(String deviceType, PaginationRequest request) throws DeviceManagementException; + PaginationResult getDevicesByType(PaginationRequest request) throws DeviceManagementException; /** * Method to retrieve all the devices with pagination support. @@ -79,25 +78,22 @@ public interface DeviceManagementProviderService extends OperationManager { /** * Method to get the list of devices owned by an user with paging information. * - * @param userName Username of the user - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination * @return List of devices owned by a particular user along with the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the * device list */ - PaginationResult getDevicesOfUser(String userName, PaginationRequest request) throws DeviceManagementException; + PaginationResult getDevicesOfUser(PaginationRequest request) throws DeviceManagementException; /** * Method to get the list of devices filtered by the ownership with paging information. * - * @param ownerShip Ownership type of devices - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination * @return List of devices owned by a particular user along with the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the * device list */ - PaginationResult getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, PaginationRequest request) - throws DeviceManagementException; + PaginationResult getDevicesByOwnership(PaginationRequest request) throws DeviceManagementException; /** * Method to get the list of devices owned by an user. @@ -140,13 +136,12 @@ public interface DeviceManagementProviderService extends OperationManager { /** * This method is used to retrieve list of devices that matches with the given device name with paging information. * - * @param deviceName name of the device * @param request PaginationRequest object holding the data for pagination * @return List of devices in given status along with the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the * device list */ - PaginationResult getDevicesByName(String deviceName, PaginationRequest request) throws DeviceManagementException; + PaginationResult getDevicesByName(PaginationRequest request) throws DeviceManagementException; void updateDeviceEnrolmentInfo(Device device, EnrolmentInfo.Status active) throws DeviceManagementException; @@ -162,13 +157,12 @@ public interface DeviceManagementProviderService extends OperationManager { /** * This method is used to retrieve list of devices based on the device status with paging information. * - * @param status Device status * @param request PaginationRequest object holding the data for pagination * @return List of devices in given status along with the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the * device list */ - PaginationResult getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request) throws DeviceManagementException; + PaginationResult getDevicesByStatus(PaginationRequest request) throws DeviceManagementException; License getLicense(String deviceType, String languageCode) throws DeviceManagementException; 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 16a1fa105e..80a1ae57d5 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 @@ -21,7 +21,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.*; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; @@ -394,19 +393,20 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public PaginationResult getAllDevices(String deviceType, PaginationRequest request) throws DeviceManagementException { + public PaginationResult getDevicesByType(PaginationRequest request) throws DeviceManagementException { PaginationResult paginationResult = new PaginationResult(); List devices = new ArrayList<>(); List allDevices = new ArrayList<>(); int count = 0; int tenantId = this.getTenantId(); + String deviceType = request.getDeviceType(); try { DeviceManagementDAOFactory.openConnection(); - allDevices = deviceDAO.getDevices(deviceType, request, tenantId); - count = deviceDAO.getDeviceCount(deviceType, tenantId); + allDevices = deviceDAO.getDevices(request, tenantId); + count = deviceDAO.getDeviceCountByType(deviceType, tenantId); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while retrieving device list pertaining to " + - "the current tenant", e); + "the current tenant of type " + deviceType, e); } catch (SQLException e) { throw new DeviceManagementException("Error occurred while opening a connection to the data source", e); } finally { @@ -962,16 +962,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public PaginationResult getDevicesOfUser(String username, PaginationRequest request) + public PaginationResult getDevicesOfUser(PaginationRequest request) throws DeviceManagementException { PaginationResult result = new PaginationResult(); int deviceCount = 0; int tenantId = this.getTenantId(); + String username = request.getOwner(); List devices = new ArrayList<>(); List userDevices = new ArrayList<>(); try { DeviceManagementDAOFactory.openConnection(); - userDevices = deviceDAO.getDevicesOfUser(username, request, tenantId); + userDevices = deviceDAO.getDevicesOfUser(request, tenantId); deviceCount = deviceDAO.getDeviceCountByUser(username, tenantId); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while retrieving the list of devices that " + @@ -1007,17 +1008,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public PaginationResult getDevicesByOwnership(EnrolmentInfo.OwnerShip ownerShip, - PaginationRequest request) + public PaginationResult getDevicesByOwnership(PaginationRequest request) throws DeviceManagementException { PaginationResult result = new PaginationResult(); List devices = new ArrayList<>(); List allDevices; int deviceCount = 0; int tenantId = this.getTenantId(); + String ownerShip = request.getOwnership(); try { DeviceManagementDAOFactory.openConnection(); - allDevices = deviceDAO.getDevicesByOwnership(ownerShip, request, tenantId); + allDevices = deviceDAO.getDevicesByOwnership(request, tenantId); deviceCount = deviceDAO.getDeviceCountByOwnership(ownerShip, tenantId); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException( @@ -1121,15 +1122,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public PaginationResult getDevicesByName(String deviceName, PaginationRequest request) + public PaginationResult getDevicesByName(PaginationRequest request) throws DeviceManagementException { PaginationResult result = new PaginationResult(); int tenantId = this.getTenantId(); List devices = new ArrayList<>(); List allDevices = new ArrayList<>(); + String deviceName = request.getDeviceName(); try { DeviceManagementDAOFactory.openConnection(); - allDevices = deviceDAO.getDevicesByName(deviceName, request, tenantId); + allDevices = deviceDAO.getDevicesByName(request, tenantId); int deviceCount = deviceDAO.getDeviceCountByName(deviceName, tenantId); result.setRecordsTotal(deviceCount); result.setRecordsFiltered(deviceCount); @@ -1221,16 +1223,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public PaginationResult getDevicesByStatus(EnrolmentInfo.Status status, PaginationRequest request) + public PaginationResult getDevicesByStatus(PaginationRequest request) throws DeviceManagementException { PaginationResult result = new PaginationResult(); List devices = new ArrayList<>(); List allDevices = new ArrayList<>(); int tenantId = this.getTenantId(); + String status = request.getStatus(); try { DeviceManagementDAOFactory.openConnection(); - allDevices = deviceDAO.getDevicesByStatus(status, request, tenantId); - int deviceCount = deviceDAO.getDeviceCount(status, tenantId); + allDevices = deviceDAO.getDevicesByStatus(request, tenantId); + int deviceCount = deviceDAO.getDeviceCountByStatus(status, tenantId); result.setRecordsTotal(deviceCount); result.setRecordsFiltered(deviceCount); } catch (DeviceManagementDAOException e) { From 42a8df75e695f61388416fbd2a8a832bf9bb6701 Mon Sep 17 00:00:00 2001 From: harshanl Date: Mon, 21 Dec 2015 15:01:18 +0530 Subject: [PATCH 12/13] Changed default oauth validator type to local --- .../src/main/resources/conf/webapp-authenticator-config.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml index a9e0c9d832..0f3c278b34 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf/webapp-authenticator-config.xml @@ -4,7 +4,7 @@ OAuth org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator - true + false https://localhost:9443 admin admin From 261af0f6eb4594bb6d0525f1af8b3b0a2c291fe3 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Mon, 21 Dec 2015 15:42:17 +0530 Subject: [PATCH 13/13] Changing the identity version to 5.0.7 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 37865f8aa5..5c04545007 100644 --- a/pom.xml +++ b/pom.xml @@ -1519,7 +1519,7 @@ 4.6.0 - 5.0.5 + 5.0.7 4.5.0