diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml index dd66b2ab02..2f8d129a4f 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml @@ -83,6 +83,7 @@ javax.xml.bind, org.wso2.carbon.utils.*, org.wso2.carbon.device.mgt.common.*, + io.swagger.annotations.*;resolution:=optional, org.wso2.carbon.device.mgt.core.*, org.bouncycastle.pkcs.jcajce @@ -166,6 +167,12 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.common + + + io.swagger + swagger-annotations + provided + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CertificateResponse.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CertificateResponse.java index 5ffb8270f3..9d0504e2dc 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CertificateResponse.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dto/CertificateResponse.java @@ -18,19 +18,42 @@ package org.wso2.carbon.certificate.mgt.core.dto; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.math.BigInteger; +@ApiModel(value = "CertificateResponse", description = "This class carries all information related to certificates") public class CertificateResponse { + @ApiModelProperty(name = "certificate", value = "The certificate in bytes", required = true) byte[] certificate; + + @ApiModelProperty(name = "serialNumber", value = "It is the unique ID that is used to identify a certificate", required = true) String serialNumber; + + @ApiModelProperty(name = "tenantId", value = "The ID of the tenant who adds the certificate", required = true) int tenantId; + + @ApiModelProperty(name = "commonName", value = "In mutual SSL the common name refers to the serial number of the Android device.", required = true) String commonName; + + @ApiModelProperty(name = "notAfter", value = "The expiration date of the certificate that is inherent to the certificate", required = true) long notAfter; + + @ApiModelProperty(name = "notBefore", value = "The date from when the certificate is valid", required = true) long notBefore; + + @ApiModelProperty(name = "certificateserial", value = "The serial number of the certificate", required = true) BigInteger certificateserial; + + @ApiModelProperty(name = "issuer", value = "The identity of the authority that signs the SSL certificate", required = true) String issuer; + + @ApiModelProperty(name = "subject", value = "The identity of the certificate", required = true) String subject; + + @ApiModelProperty(name = "certificateVersion", value = "The version of the certificate", required = true) int certificateVersion; public long getNotAfter() { diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index d1882b3096..f8cc47cbf4 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -39,13 +39,19 @@ import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.openssl.PEMWriter; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.util.Store; -import org.jscep.message.*; +import org.jscep.message.PkcsPkiEnvelopeDecoder; +import org.jscep.message.PkiMessageDecoder; +import org.jscep.message.PkiMessage; +import org.jscep.message.CertRep; +import org.jscep.message.PkcsPkiEnvelopeEncoder; +import org.jscep.message.PkiMessageEncoder; +import org.jscep.message.MessageEncodingException; +import org.jscep.message.MessageDecodingException; import org.jscep.transaction.FailInfo; import org.jscep.transaction.Nonce; import org.jscep.transaction.TransactionId; @@ -65,7 +71,6 @@ import org.wso2.carbon.device.mgt.common.TransactionManagementException; import javax.security.auth.x500.X500Principal; import javax.xml.bind.DatatypeConverter; import java.io.*; -import java.math.BigInteger; import java.security.*; import java.security.cert.Certificate; import java.security.cert.*; @@ -276,7 +281,7 @@ public class CertificateGenerator { public boolean verifySignature(String headerSignature) throws KeystoreException { Certificate certificate = extractCertificateFromSignature(headerSignature); - return (certificate != null); + return (certificate != null); } public CertificateResponse verifyPEMSignature(X509Certificate requestCertificate) throws KeystoreException { @@ -288,9 +293,22 @@ public class CertificateGenerator { return lookUpCertificate; } + public CertificateResponse verifyCertificateDN(String distinguishedName) throws KeystoreException { + CertificateResponse lookUpCertificate = null; + KeyStoreReader keyStoreReader = new KeyStoreReader(); + if (distinguishedName != null && !distinguishedName.isEmpty()) { + String[] dnSplits = distinguishedName.split("/CN="); + if (dnSplits != null) { + String commonNameExtracted = dnSplits[dnSplits.length-1]; + lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted); + } + } + return lookUpCertificate; + } + public static String getCommonName(X509Certificate requestCertificate) { String distinguishedName = requestCertificate.getSubjectDN().getName(); - if(distinguishedName != null && !distinguishedName.isEmpty()) { + if (distinguishedName != null && !distinguishedName.isEmpty()) { String[] dnSplits = distinguishedName.split(","); for (String dnSplit : dnSplits) { if (dnSplit.contains("CN=")) { @@ -350,12 +368,12 @@ public class CertificateGenerator { X509Certificate reqCert = (X509Certificate) certificateFactory. generateCertificate(byteArrayInputStream); - if(reqCert != null && reqCert.getSerialNumber() != null) { + if (reqCert != null && reqCert.getSerialNumber() != null) { Certificate lookUpCertificate = keyStoreReader.getCertificateByAlias( reqCert.getSerialNumber().toString()); if (lookUpCertificate != null && (lookUpCertificate instanceof X509Certificate)) { - return (X509Certificate)lookUpCertificate; + return (X509Certificate) lookUpCertificate; } } @@ -378,8 +396,8 @@ public class CertificateGenerator { } public X509Certificate generateCertificateFromCSR(PrivateKey privateKey, - PKCS10CertificationRequest request, - String issueSubject) + PKCS10CertificationRequest request, + String issueSubject) throws KeystoreException { CommonUtil commonUtil = new CommonUtil(); @@ -411,10 +429,10 @@ public class CertificateGenerator { certificateBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); - if(attributes != null) { + if (attributes != null) { ASN1Encodable extractedValue = getChallengePassword(attributes); - if(extractedValue != null) { + if (extractedValue != null) { certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, true, extractedValue); } @@ -453,7 +471,7 @@ public class CertificateGenerator { for (Attribute attribute : attributes) { if (PKCSObjectIdentifiers.pkcs_9_at_challengePassword.equals(attribute.getAttrType())) { - if(attribute.getAttrValues() != null && attribute.getAttrValues().size() > 0) { + if (attribute.getAttrValues() != null && attribute.getAttrValues().size() > 0) { return attribute.getAttrValues().getObjectAt(0); } } @@ -610,13 +628,12 @@ public class CertificateGenerator { log.error(errorMsg, e); CertificateManagementDAOFactory.rollbackTransaction(); throw new KeystoreException(errorMsg, e); - }finally { + } finally { CertificateManagementDAOFactory.closeConnection(); } } - public String extractChallengeToken(X509Certificate certificate) { byte[] challengePassword = certificate.getExtensionValue( diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java index c91f0f34d6..d294dbc224 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java @@ -56,6 +56,8 @@ public interface CertificateManagementService { public CertificateResponse verifyPEMSignature(X509Certificate requestCertificate) throws KeystoreException; + public CertificateResponse verifySubjectDN(String requestDN) throws KeystoreException; + public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException; String extractChallengeToken(X509Certificate certificate); diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java index 7157d08e6b..89fd9b4827 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -108,6 +108,10 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe return certificateGenerator.verifyPEMSignature(requestCertificate); } + @Override public CertificateResponse verifySubjectDN(String requestDN) throws KeystoreException { + return certificateGenerator.verifyCertificateDN(requestDN); + } + public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException { return certificateGenerator.extractCertificateFromSignature(headerSignature); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/AbstractGadgetDataServiceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/AbstractGadgetDataServiceDAO.java index 964eb02dd8..d41ba45a62 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/AbstractGadgetDataServiceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/AbstractGadgetDataServiceDAO.java @@ -485,7 +485,8 @@ public abstract class AbstractGadgetDataServiceDAO implements GadgetDataServiceD try { con = this.getConnection(); String sql; - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?"; + sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + + "DEVICES_VIEW_1 WHERE TENANT_ID = ?"; // appending filters to support advanced filtering options // [1] appending filter columns, if exist if (filters != null && filters.size() > 0) { @@ -514,6 +515,7 @@ public abstract class AbstractGadgetDataServiceDAO implements GadgetDataServiceD while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); @@ -543,8 +545,8 @@ public abstract class AbstractGadgetDataServiceDAO implements GadgetDataServiceD try { con = this.getConnection(); String sql; - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " + - "WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; + sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + + "DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; // appending filters to support advanced filtering options // [1] appending filter columns, if exist if (filters != null && filters.size() > 0) { @@ -574,6 +576,7 @@ public abstract class AbstractGadgetDataServiceDAO implements GadgetDataServiceD while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/bean/DetailedDeviceEntry.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/bean/DetailedDeviceEntry.java index c8885b6833..307a202ba3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/bean/DetailedDeviceEntry.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/bean/DetailedDeviceEntry.java @@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean; public class DetailedDeviceEntry { private int deviceId; + private String deviceIdentification; private String platform; private String ownershipType; private String connectivityStatus; @@ -34,6 +35,15 @@ public class DetailedDeviceEntry { this.deviceId = deviceId; } + @SuppressWarnings("unused") + public String getDeviceIdentification() { + return deviceIdentification; + } + + public void setDeviceIdentification(String deviceIdentification) { + this.deviceIdentification = deviceIdentification; + } + @SuppressWarnings("unused") public String getPlatform() { return platform; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GenericGadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GenericGadgetDataServiceDAOImpl.java index 3126d7736a..feb8b7024a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GenericGadgetDataServiceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GenericGadgetDataServiceDAOImpl.java @@ -127,8 +127,8 @@ public class GenericGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDA advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 " + - "WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; + sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + + "DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist stmt.setInt(1, tenantId); @@ -155,6 +155,7 @@ public class GenericGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDA while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); @@ -217,8 +218,8 @@ public class GenericGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDA advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " + - "WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + + sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + + "DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist @@ -247,6 +248,7 @@ public class GenericGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDA while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/MSSQLGadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/MSSQLGadgetDataServiceDAOImpl.java index 4e5bef4d45..b1a725e2bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/MSSQLGadgetDataServiceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/MSSQLGadgetDataServiceDAOImpl.java @@ -128,8 +128,8 @@ public class MSSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 " + - "WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC " + + sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + + "DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC " + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist @@ -157,6 +157,7 @@ public class MSSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); @@ -219,8 +220,8 @@ public class MSSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " + - "WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + + sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + + "DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist @@ -249,6 +250,7 @@ public class MSSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/OracleGadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/OracleGadgetDataServiceDAOImpl.java index a433bca813..a84b906f34 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/OracleGadgetDataServiceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/OracleGadgetDataServiceDAOImpl.java @@ -78,7 +78,7 @@ public class OracleGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO } // fetching total records count sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " + - "(SELECT DISTINCT FEATURE_CODE FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?) NON_COMPLIANT_FEATURE_CODE"; + "(SELECT DISTINCT FEATURE_CODE FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?) NON_COMPLIANT_FEATURE_CODE"; stmt = con.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -128,8 +128,8 @@ public class OracleGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } - sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT DEVICE_ID, PLATFORM, OWNERSHIP, " + - "CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering + + sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, " + + "OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC) rs) WHERE offset >= ? AND ROWNUM <= ?"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist @@ -157,6 +157,7 @@ public class OracleGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); @@ -219,8 +220,8 @@ public class OracleGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } - sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT DEVICE_ID, PLATFORM, OWNERSHIP, " + - "CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + + sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, " + + "OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC) rs) WHERE offset >= ? AND ROWNUM <= ?"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist @@ -249,6 +250,7 @@ public class OracleGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/PostgreSQLGadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/PostgreSQLGadgetDataServiceDAOImpl.java index d28a5e5b50..26986df2fe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/PostgreSQLGadgetDataServiceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/PostgreSQLGadgetDataServiceDAOImpl.java @@ -127,8 +127,8 @@ public class PostgreSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServic advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 " + - "WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? LIMIT ?"; + sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + + "DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? LIMIT ?"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist stmt.setInt(1, tenantId); @@ -155,6 +155,7 @@ public class PostgreSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServic while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); @@ -217,8 +218,8 @@ public class PostgreSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServic advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " + - "WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + + sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + + "DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? LIMIT ?"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist @@ -247,6 +248,7 @@ public class PostgreSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServic while (rs.next()) { filteredDeviceWithDetails = new DetailedDeviceEntry(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); + filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java index bcf51ebdae..04f9030760 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java @@ -83,7 +83,7 @@ public class DeviceDataPublisher { * */ public DataPublisher getDataPublisher() throws DataPublisherConfigurationException { - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); //Get LoadBalancingDataPublisher which has been registered for the tenant. DataPublisher dataPublisher = getDataPublisher(tenantDomain); //If a LoadBalancingDataPublisher had not been registered for the tenant. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml index 07ef52fde5..0d53ffbc05 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml @@ -207,6 +207,24 @@ io.swagger swagger-annotations + + + io.swagger + swagger-core + + + org.slf4j + slf4j-api + + + + + io.swagger + swagger-jaxrs + + + javax.servlet + servlet-api provided diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/ApiOriginFilter.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/ApiOriginFilter.java new file mode 100644 index 0000000000..9ba3b5b97b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/ApiOriginFilter.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.jaxrs; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public class ApiOriginFilter implements Filter { + + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + public void destroy() { + //do nothing + } + + public void init(FilterConfig filterConfig) throws ServletException { + //do nothing + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Authentication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Authentication.java deleted file mode 100644 index 2eec7f26bf..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Authentication.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.jaxrs.api; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.ws.rs.Consumes; -import javax.ws.rs.Produces; - -/** - * Authentication related REST-API implementation. - */ -@Produces({ "application/json", "application/xml" }) -@Consumes({ "application/json", "application/xml" }) -public class Authentication { - - private static Log log = LogFactory.getLog(Authentication.class); -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Certificate.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Certificate.java index 8b221bf24d..c7f1e4ff04 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Certificate.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Certificate.java @@ -18,43 +18,26 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; +import io.swagger.annotations.*; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; -import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; -import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; -import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate; -import org.wso2.carbon.device.mgt.jaxrs.exception.Message; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.List; /** * All the certificate related tasks such as saving certificates, can be done through this endpoint. */ +@Api(value = "Certificate", description = "Certificate related tasks such as saving certificates, " + + "can be done through this API") @SuppressWarnings("NonJaxWsWebServices") -@Produces({"application/json", "application/xml"}) +@Path("/certificates") +@Produces({ "application/json", "application/xml" }) @Consumes({ "application/json", "application/xml" }) -public class Certificate { - - private static Log log = LogFactory.getLog(Operation.class); +public interface Certificate { /** * Save a list of certificates and relevant information in the database. @@ -65,30 +48,20 @@ public class Certificate { */ @POST @Path("saveCertificate") - public Response saveCertificate(@HeaderParam("Accept") String acceptHeader, - EnrollmentCertificate[] enrollmentCertificates) { - MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); - CertificateManagementService certificateService; - List certificates = new ArrayList<>(); - org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate; - certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - try { - for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) { - certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); - certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); - certificate.setSerial(enrollmentCertificate.getSerial()); - certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem())); - certificates.add(certificate); - } - certificateService.saveCertificate(certificates); - return Response.status(Response.Status.CREATED).entity("Added successfully."). - type(responseMediaType).build(); - } catch (KeystoreException e) { - String msg = "Error occurred while converting PEM file to X509Certificate."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "POST", + value = "Adding an SSL Certificate", + notes = "Add a new SSL certificate to the client end database") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Added successfully"), + @ApiResponse(code = 500, message = "Error occurred while saving the certificate") + }) + Response saveCertificate(@HeaderParam("Accept") String acceptHeader, + @ApiParam(name = "enrollmentCertificates", value = "certificate with serial, " + + "pem and tenant id", required = true) EnrollmentCertificate[] + enrollmentCertificates); /** * Get a certificate when the serial number is given. @@ -98,31 +71,22 @@ public class Certificate { */ @GET @Path("{serialNumber}") - public Response getCertificate(@HeaderParam("Accept") String acceptHeader, - @PathParam("serialNumber") String serialNumber) { - MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); - Message message = new Message(); - - if (serialNumber == null || serialNumber.isEmpty()) { - message.setErrorMessage("Invalid serial number"); - message.setDiscription("Serial number is missing or invalid."); - return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); - } - - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - CertificateResponse certificateResponse; - try { - certificateResponse = certificateService.getCertificateBySerial(serialNumber); - if(certificateResponse != null) { - certificateResponse.setCertificate(null); //avoid sending byte array in response. - } - return Response.status(Response.Status.OK).entity(certificateResponse).type(responseMediaType).build(); - } catch (KeystoreException e) { - String msg = "Error occurred while converting PEM file to X509Certificate"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting Details of an SSL Certificate", + notes = "Get the client side SSL certificate details", + response = CertificateResponse.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK", response = CertificateResponse.class), + @ApiResponse(code = 400, message = "Notification status updated successfully"), + @ApiResponse(code = 500, message = "Error occurred while converting PEM file to X509Certificate") + }) + Response getCertificate(@HeaderParam("Accept") String acceptHeader, + @ApiParam(name = "serialNumber", value = "Provide the serial number of the " + + "certificate that you wish to get the details of", required = true) + @PathParam("serialNumber") String serialNumber); /** * Get all certificates in a paginated manner. @@ -134,61 +98,46 @@ public class Certificate { */ @GET @Path("paginate") - public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader, - @QueryParam("start") int startIndex, - @QueryParam("length") int length) - throws MDMAPIException { - MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); - Message message = new Message(); - - if (startIndex < 0) { - message.setErrorMessage("Invalid start index."); - message.setDiscription("Start index cannot be less that 0."); - return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); - } else if (length <= 0) { - message.setErrorMessage("Invalid length value."); - message.setDiscription("Length should be a positive integer."); - return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); - } - - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - PaginationRequest paginationRequest = new PaginationRequest(startIndex, length); - try { - PaginationResult certificates = certificateService.getAllCertificates(paginationRequest); - return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build(); - } catch (CertificateManagementDAOException e) { - String msg = "Error occurred while fetching all certificates."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting the Certificate Details in a Paginated Manner", + notes = "You will have many certificates used for mutual SSL. In a situation where you wish to " + + "view all the certificate details, it is not feasible to show all the details on one " + + "page therefore the details are paginated", + response = PaginationResult.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK", response = PaginationResult.class), + @ApiResponse(code = 400, message = "Invalid start index"), + @ApiResponse(code = 400, message = "Invalid length value"), + @ApiResponse(code = 500, message = "Error occurred while fetching all certificates") + }) + Response getAllCertificates(@HeaderParam("Accept") String acceptHeader, + @ApiParam(name = "start", + value = "Provide the starting pagination index as the value", required = true) + @QueryParam("start") int startIndex, + @ApiParam(name = "length", value = "Provide how many certificate details you" + + " require from the starting pagination index as the value", + required = true) @QueryParam("length") int length) throws MDMAPIException; @DELETE @Path("{serialNumber}") - public Response removeCertificate(@HeaderParam("Accept") String acceptHeader, - @PathParam("serialNumber") String serialNumber) throws MDMAPIException { - MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); - Message message = new Message(); + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "DELETE", + value = "Deleting an SSL Certificate", + notes = "Delete an SSL certificate that's on the client end", + response = boolean.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK"), + @ApiResponse(code = 400, message = "Invalid start index"), + @ApiResponse(code = 500, message = "Error when deleting the certificate" + ) }) + Response removeCertificate(@HeaderParam("Accept") String acceptHeader, + @ApiParam(name = "serialNumber", value = "Provide the serial number of the " + + "certificate that you wish to delete", required = true) + @PathParam("serialNumber") String serialNumber) throws MDMAPIException; - if (serialNumber == null || serialNumber.isEmpty()) { - message.setErrorMessage("Invalid serial number"); - message.setDiscription("Serial number is missing or invalid."); - return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); - } - - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - boolean deleted; - try { - deleted = certificateService.removeCertificate(serialNumber); - if(deleted){ - return Response.status(Response.Status.OK).entity(deleted).type(responseMediaType).build(); - } else { - return Response.status(Response.Status.GONE).entity(deleted).type(responseMediaType).build(); - } - } catch (CertificateManagementDAOException e) { - String msg = "Error occurred while converting PEM file to X509Certificate"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); - } - } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Configuration.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Configuration.java index 80ad97ee6c..5ae44a5162 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Configuration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Configuration.java @@ -18,96 +18,67 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; -import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import io.swagger.annotations.*; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAppConstants; -import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; -import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Produces; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.List; /** * General Tenant Configuration REST-API implementation. * All end points support JSON, XMl with content negotiation. */ - +@Path("/configuration") +@Api(value = "Configuration", description = "General Tenant Configuration management capabilities are exposed " + + "through this API") @SuppressWarnings("NonJaxWsWebServices") -@Produces({"application/json", "application/xml"}) +@Produces({ "application/json", "application/xml" }) @Consumes({ "application/json", "application/xml" }) -public class Configuration { +public interface Configuration { - private static Log log = LogFactory.getLog(Configuration.class); + @POST + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "POST", + value = "Configuring general platform settings", + notes = "Configure the general platform settings using this REST API") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Tenant configuration saved successfully"), + @ApiResponse(code = 500, message = "Error occurred while saving the tenant configuration") + }) + Response saveTenantConfiguration(@ApiParam(name = "configuration", value = "The required properties to " + + "update the platform configurations the as the value", + required = true) TenantConfiguration configuration); - @POST - public Response saveTenantConfiguration(TenantConfiguration configuration) { - ResponsePayload responseMsg = new ResponsePayload(); - try { - DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, - MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); - //Schedule the task service - DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration)); - responseMsg.setMessageFromServer("Tenant configuration saved successfully."); - responseMsg.setStatusCode(HttpStatus.SC_CREATED); - return Response.status(Response.Status.CREATED).entity(responseMsg).build(); - } catch (ConfigurationManagementException e) { - String msg = "Error occurred while saving the tenant configuration."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @GET + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting General Platform Configurations", + notes = "Get the general platform level configuration details using this REST API", + response = TenantConfiguration.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK"), + @ApiResponse(code = 500, message = "Error occurred while retrieving the tenant configuration") + }) + Response getConfiguration(); - @GET - public Response getConfiguration() { - String msg; - try { - TenantConfiguration tenantConfiguration = DeviceMgtAPIUtils.getTenantConfigurationManagementService(). - getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); - ConfigurationEntry configurationEntry = new ConfigurationEntry(); - configurationEntry.setContentType("text"); - configurationEntry.setName("notifierFrequency"); - configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency()); - List configList = tenantConfiguration.getConfiguration(); - if (configList == null) { - configList = new ArrayList<>(); - } - configList.add(configurationEntry); - tenantConfiguration.setConfiguration(configList); - return Response.status(Response.Status.OK).entity(tenantConfiguration).build(); - } catch (ConfigurationManagementException e) { - msg = "Error occurred while retrieving the tenant configuration."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } - - @PUT - public Response updateConfiguration(TenantConfiguration configuration) { - ResponsePayload responseMsg = new ResponsePayload(); - try { - DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, - MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); - //Schedule the task service - DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration)); - responseMsg.setMessageFromServer("Tenant configuration updated successfully."); - responseMsg.setStatusCode(HttpStatus.SC_CREATED); - return Response.status(Response.Status.CREATED).entity(responseMsg).build(); - } catch (ConfigurationManagementException e) { - String msg = "Error occurred while updating the tenant configuration."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @PUT + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "PUT", + value = "Updating General Platform Configurations", + notes = "Update the notification frequency using this REST API") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Tenant configuration updated successfully"), + @ApiResponse(code = 500, message = "Error occurred while updating the tenant configuration") + }) + Response updateConfiguration(@ApiParam(name = "configuration", value = "The required properties to update" + + " the platform configurations the as the value", + required = true) TenantConfiguration configuration); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Device.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Device.java index f70ab278a5..569df1cac1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Device.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Device.java @@ -18,36 +18,21 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementAdminService; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import io.swagger.annotations.*; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dto.DeviceType; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.List; /** - * Device related operations + * Device related operations such as get all the available devices, etc. */ +@Path("/devices") +@Api(value = "Device", description = "Device related operations such as get all the available devices, etc.") @SuppressWarnings("NonJaxWsWebServices") -public class Device { - private static Log log = LogFactory.getLog(Device.class); +public interface Device { /** * Get all devices. We have to use accept all the necessary query parameters sent by datatable. @@ -56,49 +41,42 @@ public class Device { * @return Device List */ @GET - public Response getAllDevices(@QueryParam("type") String type, @QueryParam("user") String user, - @QueryParam("role") String role, @QueryParam("status") EnrolmentInfo.Status status, - @QueryParam("start") int startIdx, @QueryParam("length") int length, - @QueryParam("device-name") String deviceName, - @QueryParam("ownership") EnrolmentInfo.OwnerShip ownership) { - try { - DeviceManagementProviderService service = DeviceMgtAPIUtils.getDeviceManagementService(); - //Length > 0 means this is a pagination request. - if (length > 0) { - PaginationRequest paginationRequest = new PaginationRequest(startIdx, length); - paginationRequest.setDeviceName(deviceName); - paginationRequest.setOwner(user); - if (ownership != null) { - paginationRequest.setOwnership(ownership.toString()); - } - if (status != null) { - paginationRequest.setStatus(status.toString()); - } - paginationRequest.setDeviceType(type); - return Response.status(Response.Status.OK).entity(service.getAllDevices(paginationRequest)).build(); - } - - List allDevices; - if ((type != null) && !type.isEmpty()) { - allDevices = service.getAllDevices(type); - } else if ((user != null) && !user.isEmpty()) { - allDevices = service.getDevicesOfUser(user); - } else if ((role != null) && !role.isEmpty()) { - allDevices = service.getAllDevicesOfRole(role); - } else if (status != null) { - allDevices = service.getDevicesByStatus(status); - } else if (deviceName != null) { - allDevices = service.getDevicesByName(deviceName); - } else { - allDevices = service.getAllDevices(); - } - return Response.status(Response.Status.OK).entity(allDevices).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the device list."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @Path("devices") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Returns device list", + notes = "Returns the set of devices that matches a given device type, user, role, " + + "enrollment status, ownership type", + response = org.wso2.carbon.device.mgt.common.Device.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "List of Devices"), + @ApiResponse(code = 500, message = "Error occurred while fetching the device list") + }) + Response getAllDevices(@ApiParam(name = "type", value = "Provide the device type, such as ios, android or" + + " windows", required = true) @QueryParam("type") String type, + @ApiParam(name = "user", value = "Get the details of the devices registered to a " + + "user by providing the user name", required = true) @QueryParam("user") + String user, + @ApiParam(name = "role", value = "Get the details of the devices registered to a " + + "specific role by providing the role name", required = true) + @QueryParam("role") String role, + @ApiParam(name = "status", value = "Provide the device status details, such as " + + "active or inactive", required = true) @QueryParam("status") + EnrolmentInfo.Status status, + @ApiParam(name = "start", value = "Provide the starting pagination index", + required = true) @QueryParam("start") int startIdx, + @ApiParam(name = "length", value = "Provide how many device details you require " + + "from the starting pagination index", required = true) + @QueryParam("length") int length, + @ApiParam(name = "device-name", value = "Provide the name of a registered device " + + "and receive the specified device details", required = true) + @QueryParam("device-name") String deviceName, + @ApiParam(name = "ownership", value = "Provide the device ownership type and " + + "receive the specific device details", required = true) + @QueryParam("ownership") EnrolmentInfo.OwnerShip ownership); /** * Fetch device details for a given device type and device Id. @@ -107,32 +85,8 @@ public class Device { */ @GET @Path("view") - @Produces({MediaType.APPLICATION_JSON}) - public Response getDevice(@QueryParam("type") String type, - @QueryParam("id") String id) { - DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id); - DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); - org.wso2.carbon.device.mgt.common.Device device; - try { - device = deviceManagementProviderService.getDevice(deviceIdentifier); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the device information."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - if (device == null) { - responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND); - responsePayload.setMessageFromServer("Requested device by type: " + - type + " and id: " + id + " does not exist."); - return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build(); - } else { - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Sending Requested device by type: " + type + " and id: " + id + "."); - responsePayload.setResponseContent(device); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } - } + @Produces({ MediaType.APPLICATION_JSON }) + Response getDevice(@QueryParam("type") String type, @QueryParam("id") String id); /** * Fetch device details of a given user. @@ -142,20 +96,7 @@ public class Device { */ @GET @Path("user/{user}") - public Response getDevice(@PathParam("user") String user) { - List devices; - try { - devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(user); - if (devices == null) { - return Response.status(Response.Status.NOT_FOUND).build(); - } - return Response.status(Response.Status.OK).entity(devices).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the devices list of given user."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + Response getDeviceOfUser(@PathParam("user") String user); /** * Fetch device count of a given user. @@ -165,16 +106,7 @@ public class Device { */ @GET @Path("user/{user}/count") - public Response getDeviceCount(@PathParam("user") String user) { - try { - Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(user); - return Response.status(Response.Status.OK).entity(count).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the devices list of given user."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + Response getDeviceCountOfUser(@PathParam("user") String user); /** * Get current device count @@ -183,16 +115,16 @@ public class Device { */ @GET @Path("count") - public Response getDeviceCount() { - try { - Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(); - return Response.status(Response.Status.OK).entity(count).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the device count."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + httpMethod = "GET", + value = "Getting the Device Count", + notes = "Get the number of devices that are registered with WSO2 EMM.", + response = int.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Device count"), + @ApiResponse(code = 500, message = "Error occurred while fetching the device count") + }) + Response getDeviceCount(); /** * Get the list of devices that matches with the given name. @@ -203,37 +135,40 @@ public class Device { */ @GET @Path("name/{name}/{tenantDomain}") - public Response getDevicesByName(@PathParam("name") String deviceName, - @PathParam("tenantDomain") String tenantDomain) { - List devices; - try { - devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(deviceName); - return Response.status(Response.Status.OK).entity(devices).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the devices list of device name."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + httpMethod = "GET", + value = "Get the device details of a specific device via the REST API", + notes = "Get the device details of a specific device", + response = DeviceType.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "List of devices"), + @ApiResponse(code = 500, message = "Error occurred while fetching the devices list of device name") + }) + Response getDevicesByName(@ApiParam(name = "name", value = "The name of the device or windows", + required = true) @PathParam("name") String deviceName, + @ApiParam(name = "tenantDomain", value = "Tenant domain name. The default " + + "tenant domain of WSO2 EMM is carbon.super", required = true) + @PathParam("tenantDomain") String tenantDomain); - /** - * Get the list of available device types. - * - * @return list of device types. - */ - @GET - @Path("types") - public Response getDeviceTypes() { - List deviceTypes; - try { - deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes(); - return Response.status(Response.Status.OK).entity(deviceTypes).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the list of device types."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + /** + * Get the list of available device types. + * + * @return list of device types. + */ + @GET + @Path("types") + @ApiOperation( + httpMethod = "GET", + value = "Getting Details of the Devices Supported via WSO2 EMM", + notes = "You are able to register Android, iOS and Windows devices with WSO2 EMM. This API will " + + "retrieve the device type details that can register with the EMM", + response = DeviceType.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "List of devices based on the type"), + @ApiResponse(code = 500, message = "Error occurred while fetching the list of device types") }) + Response getDeviceTypes(); /** * Update device. @@ -242,24 +177,8 @@ public class Device { */ @PUT @Path("type/{type}/id/{deviceId}") - public Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId, - org.wso2.carbon.device.mgt.common.Device updatedDevice) { - try { - DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setType(deviceType); - deviceIdentifier.setId(deviceId); - org.wso2.carbon.device.mgt.common.Device device = deviceManagementService.getDevice(deviceIdentifier); - device.setName(updatedDevice.getName()); - device.setDescription(updatedDevice.getDescription()); - Boolean response = deviceManagementService.modifyEnrollment(device); - return Response.status(Response.Status.OK).entity(response).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the list of device types."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId, + org.wso2.carbon.device.mgt.common.Device updatedDevice); /** * disenroll device. @@ -268,18 +187,6 @@ public class Device { */ @DELETE @Path("type/{type}/id/{deviceId}") - public Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId) { - try { - DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setType(deviceType); - deviceIdentifier.setId(deviceId); - Boolean response = deviceManagementService.disenrollDevice(deviceIdentifier); - return Response.status(Response.Status.OK).entity(response).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the list of device types."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId); + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java index 5bfe8e0b0f..0d20230610 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java @@ -16,65 +16,63 @@ * under the License. */ - package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import io.swagger.annotations.*; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +/** + * Device information related operations. + */ +@Path("/information") +@Api(value = "DeviceInformation", description = "Device information related operations can be found here.") @SuppressWarnings("NonJaxWsWebServices") -public class DeviceInformation { - - private static Log log = LogFactory.getLog(DeviceInformation.class); +public interface DeviceInformation { @GET @Path("{type}/{id}") - public Response getDeviceInfo(@PathParam("type") String type, @PathParam("id") String id) { - DeviceInformationManager informationManager; - DeviceInfo deviceInfo; - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(id); - deviceIdentifier.setType(type); - informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); - deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); - } catch (DeviceDetailsMgtException e) { - String msg = "Error occurred while getting the device information."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(deviceInfo).build(); - } - + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get device information", + notes = "This will return device information such as CPU usage, memory usage etc.", + response = DeviceInfo.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = ""), + @ApiResponse(code = 400, message = ""), + @ApiResponse(code = 400, message = ""), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + Response getDeviceInfo(@ApiParam(name = "type", value = "Provide the device type, such as ios, android " + + "or windows", required = true) @PathParam("type") String type, + @ApiParam(name = "id", value = "Provide the device identifier", required = true) + @PathParam("id") String id); @GET @Path("location/{type}/{id}") - public Response getDeviceLocation(@PathParam("type") String type, @PathParam("id") String id) { - DeviceInformationManager informationManager; - DeviceLocation deviceLocation; - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(id); - deviceIdentifier.setType(type); - informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); - deviceLocation = informationManager.getDeviceLocation(deviceIdentifier); - } catch (DeviceDetailsMgtException e) { - String msg = "Error occurred while getting the device location."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(deviceLocation).build(); - } -} + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get the device location", + notes = "This will return the device location including latitude and longitude as well the " + + "physical address", + response = DeviceLocation.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = ""), + @ApiResponse(code = 400, message = ""), + @ApiResponse(code = 400, message = ""), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + Response getDeviceLocation(@ApiParam(name = "type", value = "Provide the device type, such as ios, " + + "android or windows", required = true) @PathParam("type") String type, + @ApiParam(name = "id", value = "Provide the device identifier", + required = true) @PathParam("id") String id); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java index 0319ae349f..7941ac81c8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java @@ -18,12 +18,12 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; -import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; import javax.ws.rs.Consumes; @@ -33,77 +33,87 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.List; /** * DeviceNotification management REST-API implementation. * All end points support JSON, XMl with content negotiation. */ +@Api(value = "DeviceNotification", description = "Device notification related operations can be found here.") @SuppressWarnings("NonJaxWsWebServices") +@Path("/notifications") @Produces({"application/json", "application/xml"}) -@Consumes({ "application/json", "application/xml" }) -public class DeviceNotification { +@Consumes({"application/json", "application/xml"}) +public interface DeviceNotification { - private static Log log = LogFactory.getLog(Configuration.class); + @GET + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting all Device Notification Details", + notes = "Get the details of all notifications that were pushed to the device in WSO2 EMM using " + + "this REST API", + response = Notification.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "List of Notifications", response = Notification.class, + responseContainer = "List"), + @ApiResponse(code = 500, message = "Error occurred while retrieving the notification list") + }) + Response getNotifications(); - @GET - public Response getNotifications() { - String msg; - try { - List notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications(); - return Response.status(Response.Status.OK).entity(notifications).build(); - } catch (NotificationManagementException e) { - msg = "Error occurred while retrieving the notification list."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @GET + @Path("{status}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting the Device Notifications Filtered by the Status", + notes = "Get the details of all the unread notifications or the details of all the read " + + "notifications using this REST API", + response = Notification.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "List of Notifications", response = Notification.class, + responseContainer = "List"), + @ApiResponse(code = 500, message = "Error occurred while retrieving the notification list") + }) + Response getNotificationsByStatus(@ApiParam(name = "status", value = "Provide the notification status as" + + " the value for {status}", required = true) + @PathParam("status") Notification.Status status); - @GET - @Path("{status}") - public Response getNotificationsByStatus(@PathParam("status") Notification.Status status) { - String msg; - try { - List notifications = DeviceMgtAPIUtils.getNotificationManagementService().getNotificationsByStatus(status); - return Response.status(Response.Status.OK).entity(notifications).build(); - } catch (NotificationManagementException e) { - msg = "Error occurred while retrieving the notification list."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @PUT + @Path("{id}/{status}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "PUT", + value = "Updating the Device Notification Status", + notes = "When a user has read the the device notification the device notification status must " + + "change from NEW to CHECKED. Update the device notification status using this REST API") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Notification status updated successfully"), + @ApiResponse(code = 500, message = "Error occurred while updating notification status") + }) + Response updateNotificationStatus(@ApiParam(name = "id", value = "Provide the ID of the notification" + + " you wish you update", required = true) @PathParam("id") int id, + @ApiParam(name = "status", value = "Provide the notification status as" + + " the value", required = true) @PathParam("status") + Notification.Status status); - @PUT - @Path("{id}/{status}") - public Response updateNotificationStatus(@PathParam("id") int id, - @PathParam("status") Notification.Status status) { - ResponsePayload responseMsg = new ResponsePayload(); - try { - DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status); - responseMsg.setMessageFromServer("Notification status updated successfully."); - responseMsg.setStatusCode(HttpStatus.SC_ACCEPTED); - return Response.status(Response.Status.ACCEPTED).entity(responseMsg).build(); - } catch (NotificationManagementException e) { - String msg = "Error occurred while updating notification status."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } - - @POST - public Response addNotification(Notification notification) { - ResponsePayload responseMsg = new ResponsePayload(); - try { - DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification); - responseMsg.setMessageFromServer("Notification has added successfully."); - responseMsg.setStatusCode(HttpStatus.SC_CREATED); - return Response.status(Response.Status.CREATED).entity(responseMsg).build(); - } catch (NotificationManagementException e) { - String msg = "Error occurred while updating notification status."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @POST + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "POST", + value = "Sending a Device Notification", + notes = "Notify users on device operation failures and other information using this REST API") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "NNotification has added successfully"), + @ApiResponse(code = 500, message = "Error occurred while updating notification status") + }) + Response addNotification(Notification notification); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceSearch.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceSearch.java index f3fdf8c065..38ea427db5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceSearch.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceSearch.java @@ -16,40 +16,37 @@ * under the License. */ - package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import io.swagger.annotations.*; import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; import org.wso2.carbon.device.mgt.common.search.SearchContext; -import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; -import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.List; +/** + * Device search related operations such as getting device information. + */ +@Path("/search") +@Api(value = "DeviceSearch", description = "Device searching related operations can be found here.") @SuppressWarnings("NonJaxWsWebServices") -public class DeviceSearch { - - private static Log log = LogFactory.getLog(DeviceSearch.class); +public interface DeviceSearch { @GET - public Response getDeviceInfo(SearchContext searchContext) { - SearchManagerService searchManagerService; - List devices; - try { - searchManagerService = DeviceMgtAPIUtils.getSearchManagerService(); - devices = searchManagerService.search(searchContext); - - } catch (SearchMgtException e) { - String msg = "Error occurred while searching the device information."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(devices).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Advanced Search for Devices via the Console", + notes = "Carry out an advanced search via the EMM console", + response = DeviceWrapper.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK", response = DeviceWrapper.class, responseContainer = "List"), + @ApiResponse(code = 500, message = "Error occurred while searching the device information") + }) + Response getFilteredDeviceInfo(@ApiParam(name = "enrollmentCertificates", value = "List of search conditions", + required = true) SearchContext searchContext); } - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Feature.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Feature.java index 667d6f683a..5d85d40d4e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Feature.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Feature.java @@ -18,28 +18,26 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import io.swagger.annotations.*; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.List; /** * Features */ + +@Api(value = "Feature", description = "Feature management related operations can be found here.") @SuppressWarnings("NonJaxWsWebServices") +@Path("/features") @Produces({"application/json", "application/xml"}) @Consumes({"application/json", "application/xml"}) -public class Feature { - private static Log log = LogFactory.getLog(Feature.class); +public interface Feature { /** * Get all features for Mobile Device Type @@ -48,18 +46,20 @@ public class Feature { */ @GET @Path("/{type}") - public Response getFeatures(@PathParam("type") String type) { - List features; - DeviceManagementProviderService dmService; - try { - dmService = DeviceMgtAPIUtils.getDeviceManagementService(); - features = dmService.getFeatureManager(type).getFeatures(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving the list of features"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(features).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Get Feature Details of a Device", + notes = "WSO2 EMM features enable you to carry out many operations on a given device platform. " + + "Using this REST API you can get the features that can be carried out on a preferred device type," + + " such as iOS, Android or Windows.", + response = org.wso2.carbon.device.mgt.common.Feature.class, + responseContainer = "List") + @ApiResponses(value = { @ApiResponse(code = 200, message = "List of Features"), + @ApiResponse(code = 500, message = "Error occurred while retrieving the list of features" + + ".") }) + Response getFeatures(@ApiParam(name = "type", value = "Provide the device type, such as ios, android or windows", + required = true) @PathParam("type") String type); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java index 36e1723ba8..cc8ce89039 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java @@ -18,19 +18,9 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; +import io.swagger.annotations.Api; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; -import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -43,471 +33,144 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; -import java.util.Date; import java.util.List; +/** + * + */ +@Api(value = "Group") @SuppressWarnings("NonJaxWsWebServices") -public class Group { - - private static Log log = LogFactory.getLog(Group.class); +public interface Group { @POST @Consumes("application/json") - public Response createGroup(DeviceGroup group) { - String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - if (group == null) { - return Response.status(Response.Status.BAD_REQUEST).build(); - } - group.setOwner(owner); - group.setDateOfCreation(new Date().getTime()); - group.setDateOfLastUpdate(new Date().getTime()); - try { - GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService(); - groupManagementService.createGroup(group, DeviceGroupConstants.Roles.DEFAULT_ADMIN_ROLE, DeviceGroupConstants.Permissions.DEFAULT_ADMIN_PERMISSIONS); - groupManagementService.addGroupSharingRole(owner, group.getName(), owner, - DeviceGroupConstants.Roles.DEFAULT_OPERATOR_ROLE, - DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS); - groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_STATS_MONITOR_ROLE, - DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS); - groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_POLICIES, - DeviceGroupConstants.Permissions.DEFAULT_VIEW_POLICIES_PERMISSIONS); - groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_MANAGE_POLICIES, - DeviceGroupConstants.Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS); - groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_EVENTS, - DeviceGroupConstants.Permissions.DEFAULT_VIEW_EVENTS_PERMISSIONS); - return Response.status(Response.Status.CREATED).build(); - } catch (GroupAlreadyEixistException e) { - return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build(); - } catch (GroupManagementException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response createGroup(DeviceGroup group); @Path("/owner/{owner}/name/{groupName}") @PUT @Consumes("application/json") @Produces("application/json") - public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, - DeviceGroup deviceGroup) { - try { - DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupName, owner); - return Response.status(Response.Status.OK).build(); - } catch (GroupManagementException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + DeviceGroup deviceGroup); @Path("/owner/{owner}/name/{groupName}") @DELETE - public Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { - try { - DeviceMgtAPIUtils.getGroupManagementProviderService().deleteGroup(groupName, owner); - return Response.status(Response.Status.OK).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner); @GET @Produces("application/json") - public Response getGroups(@QueryParam("start") int startIndex, @QueryParam("length") int length) { - try { - PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService() - .getGroups(startIndex, length); - if (paginationResult.getRecordsTotal() > 0) { - return Response.status(Response.Status.OK).entity(paginationResult).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getGroups(@QueryParam("start") int startIndex, @PathParam("length") int length); @Path("/all") @GET @Produces("application/json") - public Response getAllGroups() { - try { - GroupManagementProviderService groupManagementProviderService = DeviceMgtAPIUtils - .getGroupManagementProviderService(); - PaginationResult paginationResult = groupManagementProviderService - .getGroups(0, groupManagementProviderService.getGroupCount()); - if (paginationResult.getRecordsTotal() > 0) { - return Response.status(Response.Status.OK).entity(paginationResult.getData()).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getAllGroups(); @Path("/user/{user}") @GET @Produces("application/json") - public Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex, - @QueryParam("length") int length) { - try { - PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService() - .getGroups(userName, startIndex, length); - if (paginationResult.getRecordsTotal() > 0) { - return Response.status(Response.Status.OK).entity(paginationResult).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex, + @QueryParam("length") int length); @Path("/user/{user}/all") @GET @Produces("application/json") - public Response getGroups(@PathParam("user") String userName) { - try { - List deviceGroups = DeviceMgtAPIUtils.getGroupManagementProviderService() - .getGroups(userName); - if (deviceGroups.size() > 0) { - return Response.status(Response.Status.OK).entity(deviceGroups).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getGroups(@PathParam("user") String userName); @Path("/owner/{owner}/name/{groupName}") @GET @Produces("application/json") - public Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { - try { - DeviceGroup deviceGroup = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroup(groupName, owner); - if (deviceGroup != null) { - return Response.status(Response.Status.OK).entity(deviceGroup).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner); @Path("/user/{user}/search") @GET @Produces("application/json") - public Response findGroups(@QueryParam("groupName") String groupName, - @PathParam("user") String user) { - try { - List groups = DeviceMgtAPIUtils.getGroupManagementProviderService() - .findInGroups(groupName, user); - DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()]; - groups.toArray(deviceGroups); - return Response.status(Response.Status.OK).entity(deviceGroups).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response findGroups(@QueryParam("groupName") String groupName, @PathParam("user") String user); @Path("/user/{user}/all") @GET @Produces("application/json") - public Response getGroups(@PathParam("user") String userName, - @QueryParam("permission") String permission) { - try { - GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService(); - List groups; - if (permission != null) { - groups = groupManagementService.getGroups(userName, permission); - } else { - groups = groupManagementService.getGroups(userName); - } - DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()]; - groups.toArray(deviceGroups); - return Response.status(Response.Status.OK).entity(deviceGroups).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getGroups(@PathParam("user") String userName, @QueryParam("permission") String permission); @Path("/count") @GET @Produces("application/json") - public Response getAllGroupCount() { - try { - int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(); - return Response.status(Response.Status.OK).entity(count).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getAllGroupCount(); @Path("/user/{user}/count") @GET @Produces("application/json") - public Response getGroupCount(@PathParam("user") String userName) { - try { - int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(userName); - return Response.status(Response.Status.OK).entity(count).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getGroupCount(@PathParam("user") String userName); @Path("/owner/{owner}/name/{groupName}/share") @PUT @Produces("application/json") - public Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, - @FormParam("shareUser") String shareUser, - @FormParam("roleName") String sharingRole) { - - try { - boolean isShared = DeviceMgtAPIUtils.getGroupManagementProviderService().shareGroup( - shareUser, groupName, owner, sharingRole); - if (isShared) { - return Response.status(Response.Status.OK).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build(); - } - } catch (UserDoesNotExistException e) { - return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @FormParam("shareUser") String shareUser, @FormParam("roleName") String sharingRole); @Path("/owner/{owner}/name/{groupName}/unshare") @PUT @Produces("application/json") - public Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, - @FormParam("unShareUser") String unShareUser, - @FormParam("roleName") String sharingRole) { - try { - boolean isUnShared = DeviceMgtAPIUtils.getGroupManagementProviderService().unshareGroup( - unShareUser, groupName, owner, sharingRole); - if (isUnShared) { - return Response.status(Response.Status.OK).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build(); - } - } catch (UserDoesNotExistException e) { - return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @FormParam("unShareUser") String unShareUser, + @FormParam("roleName") String sharingRole); @Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions") @PUT @Produces("application/json") - public Response addSharing(@QueryParam("shareUser") String shareUser, @PathParam("groupName") String groupName, - @PathParam("owner") String owner, - @PathParam("roleName") String roleName, String[] permissions) { - - try { - boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addGroupSharingRole( - shareUser, groupName, owner, roleName, permissions); - if (isAdded) { - return Response.status(Response.Status.OK).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response addSharing(@QueryParam("shareUser") String shareUser, @PathParam("groupName") String groupName, + @PathParam("owner") String owner, @PathParam("roleName") String roleName, + @FormParam("permissions") String[] permissions); @DELETE @Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions") @Produces("application/json") - public Response removeSharing(@QueryParam("userName") String userName, @PathParam("groupName") String groupName, - @PathParam("owner") String owner, - @PathParam("roleName") String roleName) { - try { - boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeGroupSharingRole( - groupName, owner, roleName); - if (isRemoved) { - return Response.status(Response.Status.OK).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response removeSharing(@QueryParam("userName") String userName, @PathParam("groupName") String groupName, + @PathParam("owner") String owner, @PathParam("roleName") String roleName); @GET @Path("/owner/{owner}/name/{groupName}/share/roles") @Produces("application/json") - public Response getRoles(@PathParam("groupName") String groupName, - @PathParam("owner") String owner, @QueryParam("userName") String userName) { - try { - List roles; - if (userName != null && !userName.isEmpty()) { - roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(userName, groupName, owner); - } else { - roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner); - } - String[] rolesArray = new String[roles.size()]; - roles.toArray(rolesArray); - return Response.status(Response.Status.OK).entity(rolesArray).build(); - } catch (UserDoesNotExistException e) { - return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @QueryParam("userName") String userName); @PUT @Path("/owner/{owner}/name/{groupName}/user/{userName}/share/roles") @Produces("application/json") - public Response setRoles(@PathParam("groupName") String groupName, - @PathParam("owner") String owner, @PathParam("userName") String userName, - List selectedRoles) { - try { - List allRoles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner); - for (String role : allRoles) { - if (selectedRoles.contains(role)) { - DeviceMgtAPIUtils.getGroupManagementProviderService() - .shareGroup(userName, groupName, owner, role); - } else { - DeviceMgtAPIUtils.getGroupManagementProviderService() - .unshareGroup(userName, groupName, owner, role); - } - } - return Response.status(Response.Status.OK).build(); - } catch (UserDoesNotExistException e) { - return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response setRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @PathParam("userName") String userName, List selectedRoles); @GET @Path("/owner/{owner}/name/{groupName}/users") @Produces("application/json") - public Response getUsers(@PathParam("groupName") String groupName, - @PathParam("owner") String owner) { - try { - List users = DeviceMgtAPIUtils.getGroupManagementProviderService().getUsers( - groupName, owner); - GroupUser[] usersArray = new GroupUser[users.size()]; - users.toArray(usersArray); - return Response.status(Response.Status.OK).entity(usersArray).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getUsers(@PathParam("groupName") String groupName, @PathParam("owner") String owner); @GET @Path("/owner/{owner}/name/{groupName}/devices") @Produces("application/json") - public Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner, - @QueryParam("start") int startIdx, @QueryParam("length") int length) { - try { - PaginationResult paginationResult = DeviceMgtAPIUtils - .getGroupManagementProviderService().getDevices(groupName, owner, startIdx, length); - if (paginationResult.getRecordsTotal() > 0) { - return Response.status(Response.Status.OK).entity(paginationResult).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @QueryParam("start") int startIdx, @QueryParam("length") int length); @GET @Path("/owner/{owner}/name/{groupName}/devices/count") @Produces("application/json") - public Response getDeviceCount(@PathParam("groupName") String groupName, - @PathParam("owner") String owner) { - try { - int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getDeviceCount(groupName, owner); - return Response.status(Response.Status.OK).entity(count).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response getDeviceCount(@PathParam("groupName") String groupName, @PathParam("owner") String owner); @POST @Path("/owner/{owner}/name/{groupName}/devices") @Produces("application/json") - public Response addDevice(@PathParam("groupName") String groupName, - @PathParam("owner") String owner, DeviceIdentifier deviceIdentifier) { - try { - boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice( - deviceIdentifier, groupName, owner); - if (isAdded) { - return Response.status(Response.Status.OK).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response addDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + DeviceIdentifier deviceIdentifier); @DELETE @Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}") @Produces("application/json") - public Response removeDevice(@PathParam("groupName") String groupName, - @PathParam("owner") String owner, @PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType) { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); - boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeDevice( - deviceIdentifier, groupName, owner); - if (isRemoved) { - return Response.status(Response.Status.OK).build(); - } else { - return Response.status(Response.Status.NOT_FOUND).build(); - } - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } + Response removeDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @PathParam("deviceId") String deviceId, @PathParam("deviceType") String deviceType); @GET @Path("/owner/{owner}/name/{groupName}/users/{userName}/permissions") @Produces("application/json") - public Response getPermissions(@PathParam("userName") String userName, - @PathParam("groupName") String groupName, - @PathParam("owner") String owner) { - try { - String[] permissions = DeviceMgtAPIUtils.getGroupManagementProviderService() - .getPermissions(userName, groupName, owner); - return Response.status(Response.Status.OK).entity(permissions).build(); - } catch (UserDoesNotExistException e) { - return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); - } catch (GroupManagementException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); - } - } - + Response getPermissions(@PathParam("userName") String userName, @PathParam("groupName") String groupName, + @PathParam("owner") String owner); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/License.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/License.java index 73e78ceb83..f8884e818c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/License.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/License.java @@ -18,28 +18,19 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import io.swagger.annotations.Api; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * This class represents license related operations. */ +@Api(value = "License") +@Path("/license") @SuppressWarnings("NonJaxWsWebServices") -public class License { - - private static Log log = LogFactory.getLog(License.class); +public interface License { /** * This method returns the license text related to a given device type and language code. @@ -49,29 +40,10 @@ public class License { * @return Returns the license text */ @GET - @Path ("{deviceType}/{languageCode}") - @Produces ({MediaType.APPLICATION_JSON}) - public Response getLicense(@PathParam ("deviceType") String deviceType, - @PathParam("languageCode") String languageCode) { - - org.wso2.carbon.device.mgt.common.license.mgt.License license; - ResponsePayload responsePayload; - try { - license = DeviceMgtAPIUtils.getDeviceManagementService().getLicense(deviceType, languageCode); - if (license == null) { - return Response.status(HttpStatus.SC_NOT_FOUND).build(); - } - responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK). - messageFromServer("License for '" + deviceType + "' was retrieved successfully"). - responseContent(license.getText()). - build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving the license configured for '" + deviceType + "' device type"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @Path("{deviceType}/{languageCode}") + @Produces({ MediaType.APPLICATION_JSON }) + Response getLicense(@PathParam("deviceType") String deviceType, + @PathParam("languageCode") String languageCode); /** * This method is used to add license to a specific device type. @@ -81,21 +53,7 @@ public class License { * @return Returns the acknowledgement for the action */ @POST - @Path ("{deviceType}") - public Response addLicense(@PathParam ("deviceType") String deviceType, - org.wso2.carbon.device.mgt.common.license.mgt.License license) { - - ResponsePayload responsePayload; - try { - DeviceMgtAPIUtils.getDeviceManagementService().addLicense(deviceType, license); - responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK). - messageFromServer("License added successfully for '" + deviceType + "' device type"). - build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while adding license for '" + deviceType + "' device type"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @Path("{deviceType}") + Response addLicense(@PathParam("deviceType") String deviceType, + org.wso2.carbon.device.mgt.common.license.mgt.License license); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Operation.java index 8ff77412bb..baefe95816 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Operation.java @@ -18,203 +18,152 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import io.swagger.annotations.*; +import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; import org.wso2.carbon.device.mgt.jaxrs.api.context.DeviceOperationContext; -import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMIOSOperationUtil; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; -import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.common.Platform; -import org.wso2.carbon.device.mgt.common.app.mgt.Application; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAndroidOperationUtil; -import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.List; /** - * Operation related REST-API implementation. + * */ -@SuppressWarnings("NonJaxWsWebServices") -@Produces({"application/json", "application/xml"}) -@Consumes({"application/json", "application/xml"}) -public class Operation { - - private static Log log = LogFactory.getLog(Operation.class); +@Path("/operations") +@Api(value = "Operation", description = "Operation management related operations can be found here.") +public interface Operation { /* @deprecated */ @GET - public Response getAllOperations() { - List operations; - DeviceManagementProviderService dmService; - try { - dmService = DeviceMgtAPIUtils.getDeviceManagementService(); - operations = dmService.getOperations(null); - } catch (OperationManagementException e) { - String msg = "Error occurred while fetching the operations for the device."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(operations).build(); - } + Response getAllOperations(); @GET @Path("paginate/{type}/{id}") - public Response getDeviceOperations( - @PathParam("type") String type, @PathParam("id") String id, @QueryParam("start") int startIdx, - @QueryParam("length") int length, @QueryParam("search") String search) { - PaginationResult operations; - DeviceManagementProviderService dmService; - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - PaginationRequest paginationRequest = new PaginationRequest(startIdx, length); - try { - deviceIdentifier.setType(type); - deviceIdentifier.setId(id); - dmService = DeviceMgtAPIUtils.getDeviceManagementService(); - operations = dmService.getOperations(deviceIdentifier, paginationRequest); - } catch (OperationManagementException e) { - String msg = "Error occurred while fetching the operations for the device."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(operations).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting Paginated Details for Operations on a Device.", + notes = "You will carry out many operations on a device. In a situation where you wish to view the all" + + " the operations carried out on a device it is not feasible to show all the details on one page" + + " therefore the details are paginated." + + " Example: You carry out 21 operations via a given device. When you wish to see the operations " + + "carried out, the details of the 21 operations will be broken down into 3 pages with 10 operation" + + " details per page.", + response = org.wso2.carbon.device.mgt.common.operation.mgt.Operation.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "List of Operations on a device."), + @ApiResponse(code = 500, message = "Error occurred while fetching the operations for the " + + "device.")}) + Response getDeviceOperations(@ApiParam(name = "type", value = "Define the device type as the value for {type}. " + + "Example: ios, android or windows.", + required = true) @PathParam("type") String type, + @ApiParam(name = "id", value = "Define the device ID", + required = true) @PathParam("id") String id, + @ApiParam(name = "start", value = "Provide the starting pagination index. Example 10", + required = true) @QueryParam("start") int startIdx, + @ApiParam(name = "length", value = "Provide how many device details you require from" + + " the starting pagination index. For example if " + + "you require the device details from the 10th " + + "pagination index to the 15th, " + + "you must define 10 as the value for start and 5 " + + "as the value for length.", + required = true) @QueryParam("length") int length, + @QueryParam("search") String search); @GET @Path("{type}/{id}") - public Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id) { - List operations; - DeviceManagementProviderService dmService; - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - try { - deviceIdentifier.setType(type); - deviceIdentifier.setId(id); - dmService = DeviceMgtAPIUtils.getDeviceManagementService(); - operations = dmService.getOperations(deviceIdentifier); - } catch (OperationManagementException e) { - String msg = "Error occurred while fetching the operations for the device."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(operations).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting Device Operation Details.", + responseContainer = "List", + notes = "Get the details of operations carried out on a selected device.", + response = org.wso2.carbon.device.mgt.common.operation.mgt.Operation.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "List of Operations on a device."), + @ApiResponse(code = 500, message = "Error occurred while fetching the operations for the " + + "device.")}) + Response getAllDeviceOperations(@ApiParam(name = "type", value = "Define the device type as the value for {type}. " + + "Example: ios, android or windows.", + required = true) @PathParam("type") String type, + @ApiParam(name = "id", value = "Define the device ID", + required = true) @PathParam("id") String id); /* @deprecated */ @POST - public Response addOperation(DeviceOperationContext operationContext) { - DeviceManagementProviderService dmService; - ResponsePayload responseMsg = new ResponsePayload(); - try { - dmService = DeviceMgtAPIUtils.getDeviceManagementService(); - int operationId = dmService.addOperation(operationContext.getOperation(), operationContext.getDevices()); - if (operationId > 0) { - responseMsg.setStatusCode(HttpStatus.SC_CREATED); - responseMsg.setMessageFromServer("Operation has added successfully."); - } - return Response.status(Response.Status.CREATED).entity(responseMsg).build(); - } catch (OperationManagementException e) { - String msg = "Error occurred while saving the operation"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + Response addOperation(DeviceOperationContext operationContext); @GET @Path("{type}/{id}/apps") - public Response getInstalledApps(@PathParam("type") String type, @PathParam("id") String id) { - List applications; - ApplicationManagementProviderService appManagerConnector; - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - try { - deviceIdentifier.setType(type); - deviceIdentifier.setId(id); - appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); - applications = appManagerConnector.getApplicationListForDevice(deviceIdentifier); - } catch (ApplicationManagementException e) { - String msg = "Error occurred while fetching the apps of the device."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.CREATED).entity(applications).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "GET", + value = "Getting Installed Application Details of a Device.", + responseContainer = "List", + notes = "Get the list of applications that a device has subscribed.", + response = Application.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "List of installed application details of a device.", response = Application.class, responseContainer = "List"), + @ApiResponse(code = 500, message = "Error occurred while fetching the apps of the device" + + ".")}) + Response getInstalledApps(@ApiParam(name = "type", value = "Define the device type as the value for {type}. " + + "Example: ios, android or windows.", + required = true) @PathParam("type") String type, + @ApiParam(name = "id", value = "Define the device ID", + required = true) @PathParam("id") String id); @POST @Path("installApp/{tenantDomain}") - public Response installApplication(ApplicationWrapper applicationWrapper, - @PathParam("tenantDomain") String tenantDomain) { - ResponsePayload responseMsg = new ResponsePayload(); - ApplicationManager appManagerConnector; - org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; - try { - appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); - MobileApp mobileApp = applicationWrapper.getApplication(); - - if (applicationWrapper.getDeviceIdentifiers() != null) { - for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { - if (deviceIdentifier.getType().equals(Platform.android.toString())) { - operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp); - } else if (deviceIdentifier.getType().equals(Platform.ios.toString())) { - operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp); - } - } - appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); - } - responseMsg.setStatusCode(HttpStatus.SC_CREATED); - responseMsg.setMessageFromServer("Application installation request has been sent to the device."); - return Response.status(Response.Status.CREATED).entity(responseMsg).build(); - } catch (ApplicationManagementException | MDMAPIException e) { - String msg = "Error occurred while saving the operation"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "POST", + value = "Installing an Application on a Device.", + notes = "Install a selected application on a device.") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Operation was successfully added to the queue."), + @ApiResponse(code = 500, message = "Error occurred while saving the operation.")}) + Response installApplication(@ApiParam(name = "applicationWrapper", value = "Details about the application and the" + + " users and roles it should be " + + "installed on.", + required = true) ApplicationWrapper applicationWrapper, + @ApiParam(name = "tenantDomain", value = "Provide the tenant domain as the value for " + + "{tenantDomain}. The default tenant domain " + + "of WSO2 EMM is carbon.super.", + required = true) @PathParam("tenantDomain") String tenantDomain); @POST @Path("uninstallApp/{tenantDomain}") - public Response uninstallApplication(ApplicationWrapper applicationWrapper, - @PathParam("tenantDomain") String tenantDomain) { - ResponsePayload responseMsg = new ResponsePayload(); - ApplicationManager appManagerConnector; - org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; - try { - appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); - MobileApp mobileApp = applicationWrapper.getApplication(); + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "POST", + value = "Uninstalling an Application from a Device.", + notes = "Uninstall a selected application from a device.") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Operation was successfully added to the queue."), + @ApiResponse(code = 500, message = "Error occurred while saving the operation.")}) + Response uninstallApplication(@ApiParam(name = "applicationWrapper", value = "Details about the application and" + + " the users and roles it should be " + + "uninstalled.", + required = true) ApplicationWrapper applicationWrapper, + @ApiParam(name = "tenantDomain", value = "Provide the tenant domain as the value for " + + "{tenantDomain}. The default tenant domain " + + "of WSO2 EMM is carbon.super.", + required = true) @PathParam("tenantDomain") String tenantDomain); - if (applicationWrapper.getDeviceIdentifiers() != null) { - for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { - if (deviceIdentifier.getType().equals(Platform.android.toString())) { - operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp); - } else if (deviceIdentifier.getType().equals(Platform.ios.toString())) { - operation = MDMIOSOperationUtil.createAppUninstallOperation(mobileApp); - } - } - appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); - } - responseMsg.setStatusCode(HttpStatus.SC_CREATED); - responseMsg.setMessageFromServer("Application removal request has been sent to the device."); - return Response.status(Response.Status.CREATED).entity(responseMsg).build(); - } catch (ApplicationManagementException | MDMAPIException e) { - String msg = "Error occurred while saving the operation"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } -} \ No newline at end of file + + @GET + @Path("activity/{id}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "POST", + value = "Retrieving the operation details.", + notes = "This will return the operation details including the responses from the devices") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Activity details provided successfully.."), + @ApiResponse(code = 500, message = "Error occurred while fetching the activity for the supplied id.")}) + Response getActivity(@ApiParam(name = "id", value = "Provide activity id {id} as ACTIVITY_(number)", + required = true) @PathParam("id") String id) + throws MDMAPIException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Policy.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Policy.java index a0d789b00f..7189cff0e4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Policy.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Policy.java @@ -18,413 +18,242 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import io.swagger.annotations.*; import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper; -import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; -import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; -import org.wso2.carbon.policy.mgt.common.PolicyManagementException; -import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; -import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; -import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; -import org.wso2.carbon.policy.mgt.core.PolicyManagerService; -import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; +import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.ArrayList; import java.util.List; -@SuppressWarnings("NonJaxWsWebServices") -public class Policy { - private static Log log = LogFactory.getLog(Policy.class); +@Path("/policies") +@Api(value = "Policy", description = "Policy management related operations can be found here.") +public interface Policy { @POST @Path("inactive-policy") - public Response addPolicy(PolicyWrapper policyWrapper) { - - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - ResponsePayload responseMsg = new ResponsePayload(); - org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); - policy.setPolicyName(policyWrapper.getPolicyName()); - policy.setProfileId(policyWrapper.getProfileId()); - policy.setDescription(policyWrapper.getDescription()); - policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); - policy.setOwnershipType(policyWrapper.getOwnershipType()); - policy.setRoles(policyWrapper.getRoles()); - policy.setUsers(policyWrapper.getUsers()); - policy.setTenantId(policyWrapper.getTenantId()); - policy.setCompliance(policyWrapper.getCompliance()); - - return addPolicy(policyManagementService, responseMsg, policy); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Adding a Policy.", + notes = "Add a policy using this REST API command. When adding a policy you will have the option of " + + "saving the policy or saving and publishing the policy. Using the REST API command given below " + + "you are able to save a created Policy and this policy will be in the inactive state") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Created the policy."), + @ApiResponse(code = 500, message = "Policy Management related error occurred when " + + "adding the policy")}) + Response addPolicy(@ApiParam(name = "policyWrapper", value = "Policy details related to the operation.", + required = true) PolicyWrapper policyWrapper); @POST @Path("active-policy") - public Response addActivePolicy(PolicyWrapper policyWrapper) { - - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - ResponsePayload responseMsg = new ResponsePayload(); - org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); - policy.setPolicyName(policyWrapper.getPolicyName()); - policy.setProfileId(policyWrapper.getProfileId()); - policy.setDescription(policyWrapper.getDescription()); - policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); - policy.setOwnershipType(policyWrapper.getOwnershipType()); - policy.setRoles(policyWrapper.getRoles()); - policy.setUsers(policyWrapper.getUsers()); - policy.setTenantId(policyWrapper.getTenantId()); - policy.setCompliance(policyWrapper.getCompliance()); - policy.setActive(true); - - return addPolicy(policyManagementService, responseMsg, policy); - } - - private Response addPolicy(PolicyManagerService policyManagementService, ResponsePayload responseMsg, - org.wso2.carbon.policy.mgt.common.Policy policy) { - try { - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - pap.addPolicy(policy); - responseMsg.setStatusCode(HttpStatus.SC_CREATED); - responseMsg.setMessageFromServer("Policy has been added successfully."); - return Response.status(Response.Status.CREATED).entity(responseMsg).build(); - } catch (PolicyManagementException e) { - String msg = "Policy Management related exception"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Adding an Active Policy.", + notes = "Add a policy that is in the active state using the REST API command. When adding a policy you " + + "will have the option of saving the policy or saving and publishing the policy. Using the REST " + + "API command given below you are able to save and publish a created policy and this policy will " + + "be in the active state.") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Created the policy."), + @ApiResponse(code = 500, message = "Policy Management related error occurred when " + + "adding the policy")}) + Response addActivePolicy(@ApiParam(name = "policyWrapper", value = "Policy details related to the operation.", + required = true) PolicyWrapper policyWrapper); @GET @Produces({MediaType.APPLICATION_JSON}) - public Response getAllPolicies() { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - List policies; - try { - PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); - policies = policyAdministratorPoint.getPolicies(); - } catch (PolicyManagementException e) { - String msg = "Policy Management related exception"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Sending all retrieved device policies."); - responsePayload.setResponseContent(policies); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of Policies.", + responseContainer = "List", + notes = "Retrieve the details of all the policies that you have created in WSO2 EMM.", + response = org.wso2.carbon.policy.mgt.common.Policy.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Fetched all policies.", + response = org.wso2.carbon.policy.mgt.common.Policy.class, responseContainer = "List"), + @ApiResponse(code = 500, message = "Policy Management related error occurred when " + + "fetching the policies.")}) + Response getAllPolicies(); @GET @Produces({MediaType.APPLICATION_JSON}) @Path("{id}") - public Response getPolicy(@PathParam("id") int policyId) { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - final org.wso2.carbon.policy.mgt.common.Policy policy; - try { - PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); - policy = policyAdministratorPoint.getPolicy(policyId); - } catch (PolicyManagementException e) { - String msg = "Policy Management related exception"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - if (policy == null){ - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND); - responsePayload.setMessageFromServer("Policy for ID " + policyId + " not found."); - return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Sending all retrieved device policies."); - responsePayload.setResponseContent(policy); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of a Policy.", + notes = "Retrieve the details of a selected policy in WSO2 EMM.", + response = org.wso2.carbon.policy.mgt.common.Policy.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Fetched policy details."), + @ApiResponse(code = 500, message = "Policy Management related error occurred when " + + "fetching the policies.")}) + Response getPolicy(@ApiParam(name = "id", value = "Policy ID value to identify a policy uniquely.", + required = true) @PathParam("id") int policyId); @GET @Path("count") - public Response getPolicyCount() { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - try { - PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); - Integer count = policyAdministratorPoint.getPolicyCount(); - return Response.status(Response.Status.OK).entity(count).build(); - } catch (PolicyManagementException e) { - String msg = "Policy Management related exception"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting the Policy Count.", + notes = "Get the number of policies that are created in WSO2 EMM.", + response = int.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Fetched the policy count."), + @ApiResponse(code = 500, message = "Error while Fetching the policy count.")}) + Response getPolicyCount(); @PUT @Path("{id}") - public Response updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId) { - - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - ResponsePayload responseMsg = new ResponsePayload(); - org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); - policy.setPolicyName(policyWrapper.getPolicyName()); - policy.setId(policyId); - policy.setProfileId(policyWrapper.getProfileId()); - policy.setDescription(policyWrapper.getDescription()); - policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); - policy.setOwnershipType(policyWrapper.getOwnershipType()); - policy.setRoles(policyWrapper.getRoles()); - policy.setUsers(policyWrapper.getUsers()); - policy.setTenantId(policyWrapper.getTenantId()); - policy.setCompliance(policyWrapper.getCompliance()); - - try { - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - pap.updatePolicy(policy); - responseMsg.setStatusCode(HttpStatus.SC_CREATED); - responseMsg.setMessageFromServer("Policy has been updated successfully."); - return Response.status(Response.Status.CREATED).entity(responseMsg).build(); - } catch (PolicyManagementException e) { - String msg = "Policy Management related exception in policy update."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Updating a Policy.", + notes = "If you wish to make changes to an existing policy, you can do so by updating the policy using " + + "this API") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy has been updated successfully."), + @ApiResponse(code = 500, message = "Policy Management related exception in policy " + + "update")}) + Response updatePolicy(@ApiParam(name = "policyWrapper", value = "Policy details related to the operation.", + required = true) PolicyWrapper policyWrapper, + @ApiParam(name = "id", value = "Policy ID value to identify a policy uniquely.", + required = true) @PathParam("id") int policyId); @PUT @Path("priorities") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response updatePolicyPriorities(List priorityUpdatedPolicies) { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - List policiesToUpdate = - new ArrayList<>(priorityUpdatedPolicies.size()); - int i; - for (i = 0; i < priorityUpdatedPolicies.size(); i++) { - org.wso2.carbon.policy.mgt.common.Policy policyObj = new org.wso2.carbon.policy.mgt.common.Policy(); - policyObj.setId(priorityUpdatedPolicies.get(i).getId()); - policyObj.setPriorityId(priorityUpdatedPolicies.get(i).getPriority()); - policiesToUpdate.add(policyObj); - } - boolean policiesUpdated; - try { - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - policiesUpdated = pap.updatePolicyPriorities(policiesToUpdate); - } catch (PolicyManagementException e) { - String msg = "Exception in updating policy priorities."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - if (policiesUpdated) { - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Policy Priorities successfully updated."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } else { - responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); - responsePayload.setMessageFromServer("Policy priorities did not update. Bad Request."); - return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Updating the Policy Priority.", + notes = "If you wish to make changes to the existing policy priority order, " + + "you can do so by updating the priority order using this API") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy Priorities successfully updated."), + @ApiResponse(code = 400, message = "Policy priorities did not update."), + @ApiResponse(code = 500, message = "Error in updating policy priorities.")}) + Response updatePolicyPriorities(@ApiParam(name = "priorityUpdatedPolicies", + value = "List of policy update details..", + required = true) List priorityUpdatedPolicies); @POST @Path("bulk-remove") @Consumes("application/json") @Produces("application/json") - public Response bulkRemovePolicy(List policyIds) { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - boolean policyDeleted = true; - try { - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - for(int i : policyIds) { - org.wso2.carbon.policy.mgt.common.Policy policy = pap.getPolicy(i); - if(!pap.deletePolicy(policy)){ - policyDeleted = false; - } - } - } catch (PolicyManagementException e) { - String msg = "Exception in deleting policies."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - if (policyDeleted) { - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Policies have been successfully deleted."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } else { - responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); - responsePayload.setMessageFromServer("Policy does not exist."); - return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Removing Multiple Policies.", + notes = "In situations where you need to delete more than one policy you can do so using this API.") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policies have been successfully deleted."), + @ApiResponse(code = 400, message = "Policy does not exist."), + @ApiResponse(code = 500, message = "Error in deleting policies.")}) + Response bulkRemovePolicy(@ApiParam(name = "policyIds", value = "Policy ID list to be deleted.", + required = true) List policyIds); @PUT @Produces("application/json") @Path("activate") - public Response activatePolicy(List policyIds) { - try { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - for(int i : policyIds) { - pap.activatePolicy(i); - } - } catch (PolicyManagementException e) { - String msg = "Exception in activating policies."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Selected policies have been successfully activated."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Activating Policies.", + notes = "Using the REST API command you are able to publish a policy in order to bring a policy that is " + + "in the inactive state to the active state.") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policies have been successfully activated."), + @ApiResponse(code = 500, message = "Error in activating policies.")}) + Response activatePolicy(@ApiParam(name = "policyIds", value = "Policy ID list to be activated.", + required = true) List policyIds); @PUT @Produces("application/json") @Path("inactivate") - public Response inactivatePolicy(List policyIds) throws MDMAPIException { - - try { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - for(int i : policyIds) { - pap.inactivatePolicy(i); - } - } catch (PolicyManagementException e) { - String msg = "Exception in inactivating policies."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Selected policies have been successfully inactivated."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Deactivating Policies.", + notes = "Using the REST API command you are able to unpublish a policy in order to bring a policy that " + + "is in the active state to the inactive state.") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policies have been successfully deactivated."), + @ApiResponse(code = 500, message = "Error in deactivating policies.")}) + Response inactivatePolicy(@ApiParam(name = "policyIds", value = "Policy ID list to be deactivated.", + required = true) List policyIds) throws MDMAPIException; @PUT @Produces("application/json") @Path("apply-changes") - public Response applyChanges() { - - try { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - pap.publishChanges(); - - - } catch (PolicyManagementException e) { - String msg = "Exception in applying changes."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Changes have been successfully updated."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Applying Changes on Policies.", + notes = "Policies in the active state will be applied to new device that register with WSO2 EMM based on" + + " the policy enforcement criteria . In a situation where you need to make changes to existing" + + " policies (removing, activating, deactivating and updating) or add new policies, the existing" + + " devices will not receive these changes immediately. Once all the required changes are made" + + " you need to apply the changes to push the policy changes to the existing devices.") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Changes have been successfully updated."), + @ApiResponse(code = 500, message = "Error in updating policies.")}) + Response applyChanges(); @GET @Path("start-task/{milliseconds}") - public Response startTaskService(@PathParam("milliseconds") int monitoringFrequency) { - - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - try { - TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); - taskScheduleService.startTask(monitoringFrequency); - - - } catch (PolicyMonitoringTaskException e) { - String msg = "Policy Management related exception."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Policy monitoring service started successfully."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Starting Policy Monitoring.", + notes = "WSO2 EMM monitors the devices to identify any devices that have not complied to an enforced " + + "policy. The policy monitoring task begins at the point WSO2 EMM has a a published policy. " + + "It will monitor the device based on the policy monitoring frequency that you define in " + + "milliseconds.Using this REST API to start the policy monitoring task is optional as " + + "WSO2 EMM uses an OSGI call to start the monitoring task") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy monitoring service started successfully."), + @ApiResponse(code = 500, message = "Policy Management related exception when starting " + + "monitoring service.")}) + Response startTaskService(@ApiParam(name = "milliseconds", value = "Policy monitoring frequency in milliseconds.", + required = true) @PathParam("milliseconds") int monitoringFrequency); @GET @Path("update-task/{milliseconds}") - public Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency) { - - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - try { - TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); - taskScheduleService.updateTask(monitoringFrequency); - - } catch (PolicyMonitoringTaskException e) { - String msg = "Policy Management related exception."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Policy monitoring service updated successfully."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency); @GET @Path("stop-task") - public Response stopTaskService() { - - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - try { - TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); - taskScheduleService.stopTask(); - - } catch (PolicyMonitoringTaskException e) { - String msg = "Policy Management related exception."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Policy monitoring service stopped successfully."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + Response stopTaskService(); @GET @Path("{type}/{id}") - public Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id) { - try { - DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id); - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - ComplianceData complianceData = policyManagementService.getDeviceCompliance(deviceIdentifier); - return Response.status(Response.Status.OK).entity(complianceData).build(); - } catch (PolicyComplianceException e) { - String msg = "Error occurred while getting the compliance data."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id); - @GET - @Path("{type}/{id}/active-policy") - public Response getDeviceActivePolicy(@PathParam("type") String type, - @PathParam("id") String id) { - try { - DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id); - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - org.wso2.carbon.policy.mgt.common.Policy policy = policyManagementService - .getAppliedPolicyToDevice(deviceIdentifier); - return Response.status(Response.Status.OK).entity(policy).build(); - } catch (PolicyManagementException e) { - String msg = "Error occurred while getting the current policy."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @GET + @Path("{type}/{id}/active-policy") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Policy Enforced Details of a Device.", + notes = "When a device registers with WSO2 EMM a policy is enforced on the device. Initially the EMM " + + "filters the policies based on the Platform (device type), filters based on the device ownership" + + " type , filters based on the user role or name and finally the policy is enforced on the device.", + response = org.wso2.carbon.policy.mgt.common.Policy.class) + @ApiResponses(value = {@ApiResponse(code = 200, message = "Fetched current policy."), + @ApiResponse(code = 500, message = "Error occurred while getting the current policy.")}) + Response getDeviceActivePolicy(@ApiParam(name = "type", value = "Define the device type as the value for {type}." + + " Example: ios, android, windows..", + required = true) @PathParam("type") String type, + @ApiParam(name = "id", value = "Define the device ID as the value for {id}.", + required = true) @PathParam("id") String id); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Profile.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Profile.java index c9e0748be0..7762048499 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Profile.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Profile.java @@ -18,13 +18,7 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; -import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; -import org.wso2.carbon.policy.mgt.common.PolicyManagementException; -import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import io.swagger.annotations.Api; import javax.ws.rs.DELETE; import javax.ws.rs.POST; @@ -32,55 +26,23 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; +/** + * These end points provide profile related operations. + */ +@Api(value = "Profile") +@Path("/profiles") @SuppressWarnings("NonJaxWsWebServices") -public class Profile { - private static Log log = LogFactory.getLog(Profile.class); +public interface Profile { - @POST - public Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile) { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - try { - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - profile = pap.addProfile(profile); - return Response.status(Response.Status.OK).entity(profile).build(); - } catch (PolicyManagementException e) { - String msg = "Policy Management related exception"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } - @POST - @Path("{id}") - public Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile, - @PathParam("id") String profileId) { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - ResponsePayload responseMsg = new ResponsePayload(); - try { - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - pap.updateProfile(profile); - responseMsg.setMessageFromServer("Profile has been updated successfully."); - return Response.status(Response.Status.OK).entity(responseMsg).build(); - } catch (PolicyManagementException e) { - String msg = "Policy Management related exception"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } - @DELETE - @Path("{id}") - public Response deleteProfile(@PathParam("id") int profileId) { - PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - ResponsePayload responseMsg = new ResponsePayload(); - try { - PolicyAdministratorPoint pap = policyManagementService.getPAP(); - org.wso2.carbon.policy.mgt.common.Profile profile = pap.getProfile(profileId); - pap.deleteProfile(profile); - responseMsg.setMessageFromServer("Profile has been deleted successfully."); - return Response.status(Response.Status.OK).entity(responseMsg).build(); - } catch (PolicyManagementException e) { - String msg = "Policy Management related exception"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @POST + Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile); + + @POST + @Path("{id}") + Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile, + @PathParam("id") String profileId); + + @DELETE + @Path("{id}") + Response deleteProfile(@PathParam("id") int profileId); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Role.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Role.java index c46f13bdb0..a9cc10cf83 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Role.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Role.java @@ -18,423 +18,184 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import io.swagger.annotations.*; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; -import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; -import org.wso2.carbon.user.api.AuthorizationManager; -import org.wso2.carbon.user.api.Permission; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.api.UserStoreManager; -import org.wso2.carbon.user.core.common.AbstractUserStoreManager; -import org.wso2.carbon.user.mgt.UserRealmProxy; import org.wso2.carbon.user.mgt.common.UIPermissionNode; -import org.wso2.carbon.user.mgt.common.UserAdminException; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -@SuppressWarnings("NonJaxWsWebServices") -public class Role { +@Path("/roles") +@Api(value = "Role", description = "Role management related operations can be found here.") +public interface Role { - private static Log log = LogFactory.getLog(Role.class); - - /** - * Get user roles (except all internal roles) from system. - * - * @return A list of users - */ @GET - @Produces({MediaType.APPLICATION_JSON}) - public Response getRoles() { - List filteredRoles; - try { - filteredRoles = getRolesFromUserStore(); - } catch (MDMAPIException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("All user roles were successfully retrieved."); - responsePayload.setResponseContent(filteredRoles); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @Produces({ MediaType.APPLICATION_JSON}) + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting the List of Roles.", + responseContainer = "List", + notes = "If you wish to get the details of all the roles in WSO2 EMM, you can do so using this REST API.", + response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "List of available roles"), + @ApiResponse(code = 500, message = "Error occurred while fetching the role list.") }) + Response getAllRoles(); - /** - * Get user roles by user store(except all internal roles) from system. - * - * @return A list of users - */ @GET @Path("{userStore}") @Produces({MediaType.APPLICATION_JSON}) - public Response getRoles(@PathParam("userStore") String userStore) { - String[] roles; - try { - AbstractUserStoreManager abstractUserStoreManager = - (AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager(); - if (log.isDebugEnabled()) { - log.debug("Getting the list of user roles"); - } - roles = abstractUserStoreManager.getRoleNames(userStore + "/*", -1, false, true, true); + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting the List of Roles in a User Store.", + responseContainer = "List", + notes = "If you wish to get the details of all the roles in WSO2 EMM, you can do so using this REST API.", + response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "List of available roles"), + @ApiResponse(code = 500, message = "Error occurred while fetching the role list.") }) + Response getRolesOfUserStore(@ApiParam(name = "userStore", value = "Provide the name of the UserStore you wish to get the" + + " details from ", + required = true) @PathParam("userStore") String userStore); - } catch (UserStoreException | MDMAPIException e) { - String msg = "Error occurred while retrieving the list of user roles."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - // removing all internal roles and roles created for Service-providers - List filteredRoles = new ArrayList<>(); - for (String role : roles) { - if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { - filteredRoles.add(role); - } - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("All user roles were successfully retrieved."); - responsePayload.setResponseContent(filteredRoles); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } - - /** - * Get user roles by providing a filtering criteria(except all internal roles & system roles) from system. - * - * @return A list of users - */ @GET @Path("search") @Produces({MediaType.APPLICATION_JSON}) - public Response getMatchingRoles(@QueryParam("filter") String filter) { - String[] roles; - try { - AbstractUserStoreManager abstractUserStoreManager = - (AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager(); - if (log.isDebugEnabled()) { - log.debug("Getting the list of user roles using filter : " + filter); - } - roles = abstractUserStoreManager.getRoleNames("*" + filter + "*", -1, true, true, true); + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Searching for Roles via the Role Name.", + responseContainer = "List", + notes = "You will have many roles created within WSO2 EMM. As the admin you will need to confirm if a " + + "given role exists in the EMM. In such situation you can search for the role by giving a " + + "character or a few characters of the role name. The search will give you a list of roles that" + + " have the name in the exact order of the characters you provided.", + response = String.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "List of matching roles"), + @ApiResponse(code = 500, message = "Error occurred while fetching the matching role list" + + ".") }) + Response getMatchingRoles(@ApiParam(name = "filter", value = "Provide a character or a few characters in the" + + " role name.", + required = true) @QueryParam("filter") String filter); - } catch (UserStoreException | MDMAPIException e) { - String msg = "Error occurred while retrieving the list of user roles using the filter : " + filter; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - // removing all internal roles and roles created for Service-providers - List filteredRoles = new ArrayList<>(); - for (String role : roles) { - if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { - filteredRoles.add(role); - } - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("All matching user roles were successfully retrieved."); - responsePayload.setResponseContent(filteredRoles); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } - - /** - * Get role permissions. - * - * @return list of permissions - */ @GET @Path("permissions") @Produces({MediaType.APPLICATION_JSON}) - public Response getPermissions(@QueryParam("rolename") String roleName) { - try { - final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); - org.wso2.carbon.user.core.UserRealm userRealmCore = null; - final UIPermissionNode rolePermissions; - if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { - userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; - } - final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); - rolePermissions = getUIPermissionNode(roleName, userRealmProxy); - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("All permissions retrieved"); - responsePayload.setResponseContent(rolePermissions); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } catch (UserAdminException | MDMAPIException e) { - String msg = "Error occurred while retrieving the user role"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Permission Details of a Role.", + notes = "In an organization an individual is associated a with set of responsibilities based on their " + + "role. In WSO2 EMM you are able to configure permissions based on the responsibilities carried " + + "out by a role. Therefore if you wish to retrieve the permission details of a role, you can do " + + "so using this REST API.", + response = UIPermissionNode.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Permission details of a role"), + @ApiResponse(code = 500, message = "Error occurred while fetching the permission " + + "details of a role.") }) + Response getPermissions(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to get the " + + "permission details.", + required = true) @QueryParam("rolename") String roleName); - /** - * Get user role of the system - * - * @return user role - */ @GET @Path("role") @Produces({MediaType.APPLICATION_JSON}) - public Response getRole(@QueryParam("rolename") String roleName) { - RoleWrapper roleWrapper = new RoleWrapper(); - try { - final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); - org.wso2.carbon.user.core.UserRealm userRealmCore = null; - if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { - userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of a Role.", + notes = "If you wish to get the details of a role in WSO2 EMM, you can do so using this REST API.", + response = RoleWrapper.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Details of a role."), + @ApiResponse(code = 500, message = "Error occurred while retrieving the user role.") }) + Response getRole(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to get the " + + "details.", + required = true) @QueryParam("rolename") String roleName); - final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); - if (log.isDebugEnabled()) { - log.debug("Getting the list of user roles"); - } - if (userStoreManager.isExistingRole(roleName)) { - roleWrapper.setRoleName(roleName); - roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName)); - // Get the permission nodes and hand picking only device management and login perms - final UIPermissionNode rolePermissions = getUIPermissionNode(roleName, userRealmProxy); - ArrayList permList = new ArrayList<>(); - iteratePermissions(rolePermissions, permList); - roleWrapper.setPermissionList(rolePermissions); - String[] permListAr = new String[permList.size()]; - roleWrapper.setPermissions(permList.toArray(permListAr)); - } - } catch (UserStoreException | UserAdminException | MDMAPIException e) { - String msg = "Error occurred while retrieving the user role"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("All user roles were successfully retrieved."); - responsePayload.setResponseContent(roleWrapper); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } - - private UIPermissionNode getUIPermissionNode(String roleName, UserRealmProxy userRealmProxy) - throws UserAdminException { - final UIPermissionNode rolePermissions = - userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); - UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2]; - - for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) { - if (permissionNode.getResourcePath().equals("/permission/admin")) { - for (UIPermissionNode node : permissionNode.getNodeList()) { - if (node.getResourcePath().equals("/permission/admin/device-mgt")) { - deviceMgtPermissions[0] = node; - } else if (node.getResourcePath().equals("/permission/admin/login")) { - deviceMgtPermissions[1] = node; - } - } - } - } - rolePermissions.setNodeList(deviceMgtPermissions); - return rolePermissions; - } - - /** - * API is used to persist a new Role - * - * @param roleWrapper for role - * @return response - */ @POST @Produces({MediaType.APPLICATION_JSON}) - public Response addRole(RoleWrapper roleWrapper) { - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (log.isDebugEnabled()) { - log.debug("Persisting the role to user store"); - } - Permission[] permissions = null; - if (roleWrapper.getPermissions() != null && roleWrapper.getPermissions().length > 0) { - permissions = new Permission[roleWrapper.getPermissions().length]; + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Adding a Role.", + notes = "You are able to add a new role to WSO2 EMM using the REST API.") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Added the role."), + @ApiResponse(code = 500, message = "Error occurred while adding the user role.") }) + Response addRole(@ApiParam(name = "roleWrapper", value = "Role and permission details.", + required = true) RoleWrapper roleWrapper); - for (int i = 0; i < permissions.length; i++) { - String permission = roleWrapper.getPermissions()[i]; - permissions[i] = new Permission(permission, CarbonConstants.UI_PERMISSION_ACTION); - } - } - userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions); - } catch (UserStoreException | MDMAPIException e) { - String msg = e.getMessage(); - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).build(); - } - - /** - * API is used to update a role Role - * - * @param roleWrapper for role - * @return response - */ @PUT @Produces({MediaType.APPLICATION_JSON}) - public Response updateRole(@QueryParam("rolename") String roleName, RoleWrapper roleWrapper) { - String newRoleName = roleWrapper.getRoleName(); - try { - final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager(); - if (log.isDebugEnabled()) { - log.debug("Updating the role to user store"); - } - if (newRoleName != null && !roleName.equals(newRoleName)) { - userStoreManager.updateRoleName(roleName, newRoleName); - } - if (roleWrapper.getUsers() != null) { - SetReferenceTransformer transformer = new SetReferenceTransformer<>(); - transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)), - Arrays.asList(roleWrapper.getUsers())); - final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer - .getObjectsToAdd().size()]); - final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer - .getObjectsToRemove().size()]); - userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd); - } - if (roleWrapper.getPermissions() != null) { - // Delete all authorizations for the current role before authorizing the permission tree - authorizationManager.clearRoleAuthorization(roleName); - if (roleWrapper.getPermissions().length > 0) { - for (int i = 0; i < roleWrapper.getPermissions().length; i++) { - String permission = roleWrapper.getPermissions()[i]; - authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION); - } - } - } - } catch (UserStoreException | MDMAPIException e) { - String msg = e.getMessage(); - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Updating a Role.", + notes = "There will be situations where you will need to update the role details, such as the permissions" + + " or the role name. In such situation you can update the role details.") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Updated the role."), + @ApiResponse(code = 500, message = "Error occurred while updating the user role details" + + ".") }) + Response updateRole(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to update.", + required = true) @QueryParam("rolename") String roleName, + @ApiParam(name = "roleWrapper", value = "Role and permission details.", + required = true) RoleWrapper roleWrapper); - /** - * API is used to delete a role and authorizations - * - * @param roleName to delete - * @return response - */ @DELETE @Produces({MediaType.APPLICATION_JSON}) - public Response deleteRole(@QueryParam("rolename") String roleName) { - try { - final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager(); - if (log.isDebugEnabled()) { - log.debug("Deleting the role in user store"); - } - userStoreManager.deleteRole(roleName); - // Delete all authorizations for the current role before deleting - authorizationManager.clearRoleAuthorization(roleName); - } catch (UserStoreException | MDMAPIException e) { - String msg = "Error occurred while deleting the role: " + roleName; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).build(); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "Deleting a Role.", + notes = "In a situation when your Organization identifies that a specific role is no longer required you " + + "will need to remove the role details from WSO2 EMM.") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Deleted the role."), + @ApiResponse(code = 500, message = "Error occurred while deleting the user role details" + + ".") }) + Response deleteRole(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to delete.", + required = true) @QueryParam("rolename") String roleName); - /** - * API is used to update users of a role - * - * @param roleName to update - * @param userList of the users - * @return response - */ @PUT @Path("users") @Produces({MediaType.APPLICATION_JSON}) - public Response updateUsers(@QueryParam("rolename") String roleName, List userList) { - try { - final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (log.isDebugEnabled()) { - log.debug("Updating the users of a role"); - } - SetReferenceTransformer transformer = new SetReferenceTransformer<>(); - transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(roleName)), - userList); - final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer - .getObjectsToAdd().size()]); - final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer - .getObjectsToRemove().size()]); + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Adding Users to a Role.", + notes = "Defining the users to a role at the point of creating a new role is optional, " + + "therefore you are able to update the users that belong to a given role after you have created " + + "a role using this REST API." + + "Example: Your Organization hires 30 new engineers. Updating the role details for each user can " + + "be cumbersome, therefore you can define all the new employees that belong to the engineering " + + "role using this API.") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Added Users to a Role."), + @ApiResponse(code = 500, message = "Error occurred while saving the users of the role.") }) + Response updateUsers(@ApiParam(name = "rolename", value = "Provide the name of the role you wish to update.", + required = true) @QueryParam("rolename") String roleName, + @ApiParam(name = "userList", value = "Provide the names of the users you will to update.", + required = true) List userList); - userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd); - } catch (UserStoreException | MDMAPIException e) { - String msg = "Error occurred while saving the users of the role: " + roleName; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).build(); - } - - private ArrayList iteratePermissions(UIPermissionNode uiPermissionNode, ArrayList list) { - for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) { - list.add(permissionNode.getResourcePath()); - if (permissionNode.getNodeList() != null && permissionNode.getNodeList().length > 0) { - iteratePermissions(permissionNode, list); - } - } - return list; - } - - /** - * This method is used to retrieve the role count of the system. - * - * @return returns the count. - */ @GET @Path("count") - public Response getRoleCount() { - try { - List filteredRoles = getRolesFromUserStore(); - Integer count = filteredRoles.size(); - return Response.status(Response.Status.OK).entity(count).build(); - } catch (MDMAPIException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting the Role Count.", + response = int.class, + notes = "Get the number of roles in WSO2 EMM.") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieved the role count."), + @ApiResponse(code = 500, message = "Error occurred while retrieving the role count.") }) + Response getRoleCount(); - private List getRolesFromUserStore() throws MDMAPIException { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - String[] roles; - try { - if (log.isDebugEnabled()) { - log.debug("Getting the list of user roles"); - } - roles = userStoreManager.getRoleNames(); - - } catch (UserStoreException e) { - String msg = "Error occurred while retrieving the list of user roles."; - throw new MDMAPIException(msg, e); - } - // removing all internal roles and roles created for Service-providers - List filteredRoles = new ArrayList<>(); - for (String role : roles) { - if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { - filteredRoles.add(role); - } - } - return filteredRoles; - } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/User.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/User.java index a64fae9cf3..7ac2eeab7f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/User.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/User.java @@ -18,740 +18,286 @@ package org.wso2.carbon.device.mgt.jaxrs.api; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import io.swagger.annotations.*; +import org.apache.axis2.databinding.types.soapencoding.Integer; import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; -import org.wso2.carbon.device.mgt.jaxrs.util.Constants; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; -import org.wso2.carbon.device.mgt.jaxrs.api.util.CredentialManagementResponseBuilder; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; -import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.api.UserStoreManager; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Random; -import java.util.TreeSet; /** - * This class represents the JAX-RS services of User related functionality. + * This represents the JAX-RS services of User related functionality. */ -@SuppressWarnings("NonJaxWsWebServices") -public class User { +@Path("/users") +@Api(value = "User", description = "User management related operations can be found here.") +public interface User { - private static final String ROLE_EVERYONE = "Internal/everyone"; - private static Log log = LogFactory.getLog(User.class); - - /** - * Method to add user to emm-user-store. - * - * @param userWrapper Wrapper object representing input json payload - * @return {Response} Status of the request wrapped inside Response object - */ @POST - @Consumes({MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response addUser(UserWrapper userWrapper) { - ResponsePayload responsePayload = new ResponsePayload(); - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(userWrapper.getUsername())) { - // if user already exists - if (log.isDebugEnabled()) { - log.debug("User by username: " + userWrapper.getUsername() + - " already exists. Therefore, request made to add user was refused."); - } - // returning response with bad request state - responsePayload.setStatusCode(HttpStatus.SC_CONFLICT); - responsePayload. - setMessageFromServer("User by username: " + userWrapper.getUsername() + - " already exists. Therefore, request made to add user was refused."); - return Response.status(Response.Status.CONFLICT).entity(responsePayload).build(); - } else { - String initialUserPassword = generateInitialUserPassword(); - Map defaultUserClaims = - buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(), - userWrapper.getEmailAddress()); - // calling addUser method of carbon user api - userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword, - userWrapper.getRoles(), defaultUserClaims, null); - // invite newly added user to enroll device - inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword); - // Outputting debug message upon successful addition of user - if (log.isDebugEnabled()) { - log.debug("User by username: " + userWrapper.getUsername() + " was successfully added."); - } - // returning response with success state - responsePayload.setStatusCode(HttpStatus.SC_CREATED); - responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() + - " was successfully added."); - return Response.status(Response.Status.CREATED).entity(responsePayload).build(); - } - } catch (UserStoreException | MDMAPIException e) { - String msg = "Exception in trying to add user by username: " + userWrapper.getUsername(); - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Adding a User via the REST API", + notes = "Adds a new user to WSO2 EMM using this REST API") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Created"), + @ApiResponse(code = 500, message = "Exception in trying to add user by username: 'username'") + }) + Response addUser(@ApiParam(name = "userWrapper", value = "Includes the required properties to add a user" + + " as the value", required = true) UserWrapper userWrapper); - /** - * Method to get user information from emm-user-store. - * - * @param username User-name of the user - * @return {Response} Status of the request wrapped inside Response object. - */ @GET @Path("view") @Produces({MediaType.APPLICATION_JSON}) - public Response getUser(@QueryParam("username") String username) { - ResponsePayload responsePayload = new ResponsePayload(); - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(username)) { - UserWrapper user = new UserWrapper(); - user.setUsername(username); - user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); - user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); - user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); - // Outputting debug message upon successful retrieval of user - if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " was found."); - } - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("User information was retrieved successfully."); - responsePayload.setResponseContent(user); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } else { - // Outputting debug message upon trying to remove non-existing user - if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " does not exist."); - } - // returning response with bad request state - responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); - responsePayload.setMessageFromServer( - "User by username: " + username + " does not exist."); - return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); - } - } catch (UserStoreException | MDMAPIException e) { - String msg = "Exception in trying to retrieve user by username: " + username; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of a User", + notes = "If you wish to get the details of a specific user that is registered with WSO2 EMM," + + " you can do so using the REST API", + response = UserWrapper.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "User information was retrieved successfully"), + @ApiResponse(code = 400, message = "User by username: 'username' does not exist"), + @ApiResponse(code = 500, message = "Exception in trying to retrieve user by username: 'username'") + }) + Response getUser(@ApiParam(name = "username", value = "Provide the name of the user you wish to get the" + + " details of as the value", required = true) + @QueryParam("username") String username); - /** - * Update user in user store - * - * @param userWrapper Wrapper object representing input json payload - * @return {Response} Status of the request wrapped inside Response object. - */ @PUT @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) { - ResponsePayload responsePayload = new ResponsePayload(); - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(userWrapper.getUsername())) { - Map defaultUserClaims = - buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(), - userWrapper.getEmailAddress()); - if (StringUtils.isNotEmpty(userWrapper.getPassword())) { - // Decoding Base64 encoded password - byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword()); - userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(), - new String(decodedBytes, "UTF-8")); - log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed"); - } - List listofFilteredRoles = getFilteredRoles(userStoreManager, userWrapper.getUsername()); - final String[] existingRoles = listofFilteredRoles.toArray(new String[listofFilteredRoles.size()]); + @ApiOperation( + consumes = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + produces = MediaType.APPLICATION_JSON + ", " + MediaType.APPLICATION_XML, + httpMethod = "PUT", + value = "Updating Details of a User", + notes = "There will be situations where you will want to update the user details. In such " + + "situation you can update the user details using this REST API") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "User by username: 'username' was successfully updated"), + @ApiResponse(code = 409, message = "User by username: 'username' doesn't exists. Therefore, " + + "request made to update user was refused"), + @ApiResponse(code = 500, message = "Exception in trying to update user by username: 'username'") + }) + Response updateUser(@ApiParam(name = "userWrapper", value = "Provide the name of the user you wish to get" + + " the details of as the value", required = true) UserWrapper userWrapper, + @ApiParam(name = "username", value = "Provide the name of the user you wish to get " + + "the details of as the value", required = true) + @QueryParam("username") String username); - /* - Use the Set theory to find the roles to delete and roles to add - The difference of roles in existingRolesSet and newRolesSet needed to be deleted - new roles to add = newRolesSet - The intersection of roles in existingRolesSet and newRolesSet - */ - final TreeSet existingRolesSet = new TreeSet<>(); - Collections.addAll(existingRolesSet, existingRoles); - final TreeSet newRolesSet = new TreeSet<>(); - Collections.addAll(newRolesSet, userWrapper.getRoles()); - existingRolesSet.removeAll(newRolesSet); - // Now we have the roles to delete - String[] rolesToDelete = existingRolesSet.toArray(new String[existingRolesSet.size()]); - List roles = new ArrayList<>(Arrays.asList(rolesToDelete)); - roles.remove(ROLE_EVERYONE); - rolesToDelete = new String[0]; - // Clearing and re-initializing the set - existingRolesSet.clear(); - Collections.addAll(existingRolesSet, existingRoles); - newRolesSet.removeAll(existingRolesSet); - // Now we have the roles to add - String[] rolesToAdd = newRolesSet.toArray(new String[newRolesSet.size()]); - userStoreManager.updateRoleListOfUser(userWrapper.getUsername(), rolesToDelete, rolesToAdd); - userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null); - // Outputting debug message upon successful addition of user - if (log.isDebugEnabled()) { - log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated."); - } - // returning response with success state - responsePayload.setStatusCode(HttpStatus.SC_CREATED); - responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() + - " was successfully updated."); - return Response.status(Response.Status.CREATED).entity(responsePayload).build(); - } else { - if (log.isDebugEnabled()) { - log.debug("User by username: " + userWrapper.getUsername() + - " doesn't exists. Therefore, request made to update user was refused."); - } - // returning response with bad request state - responsePayload.setStatusCode(HttpStatus.SC_CONFLICT); - responsePayload. - setMessageFromServer("User by username: " + userWrapper.getUsername() + - " doesn't exists. Therefore, request made to update user was refused."); - return Response.status(Response.Status.CONFLICT).entity(responsePayload).build(); - } - } catch (UserStoreException | UnsupportedEncodingException | MDMAPIException e) { - String msg = "Exception in trying to update user by username: " + userWrapper.getUsername(); - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } - - /** - * Private method to be used by addUser() to - * generate an initial user password for a user. - * This will be the password used by a user for his initial login to the system. - * - * @return {string} Initial User Password - */ - private String generateInitialUserPassword() { - int passwordLength = 6; - //defining the pool of characters to be used for initial password generation - String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz"; - String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - String numericCharset = "0123456789"; - Random randomGenerator = new Random(); - String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset; - int totalCharsetLength = totalCharset.length(); - StringBuilder initialUserPassword = new StringBuilder(); - for (int i = 0; i < passwordLength; i++) { - initialUserPassword - .append(totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength))); - } - if (log.isDebugEnabled()) { - log.debug("Initial user password is created for new user: " + initialUserPassword); - } - return initialUserPassword.toString(); - } - - /** - * Method to build default user claims. - * - * @param firstname First name of the user - * @param lastname Last name of the user - * @param emailAddress Email address of the user - * @return {Object} Default user claims to be provided - */ - private Map buildDefaultUserClaims(String firstname, String lastname, String emailAddress) { - Map defaultUserClaims = new HashMap<>(); - defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstname); - defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastname); - defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress); - if (log.isDebugEnabled()) { - log.debug("Default claim map is created for new user: " + defaultUserClaims.toString()); - } - return defaultUserClaims; - } - - /** - * Method to remove user from emm-user-store. - * - * @param username Username of the user - * @return {Response} Status of the request wrapped inside Response object. - */ @DELETE @Produces({MediaType.APPLICATION_JSON}) - public Response removeUser(@QueryParam("username") String username) { - ResponsePayload responsePayload = new ResponsePayload(); - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(username)) { - // if user already exists, trying to remove user - userStoreManager.deleteUser(username); - // Outputting debug message upon successful removal of user - if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " was successfully removed."); - } - // returning response with success state - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer( - "User by username: " + username + " was successfully removed."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } else { - // Outputting debug message upon trying to remove non-existing user - if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " does not exist for removal."); - } - // returning response with bad request state - responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); - responsePayload.setMessageFromServer( - "User by username: " + username + " does not exist for removal."); - return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); - } - } catch (UserStoreException | MDMAPIException e) { - String msg = "Exception in trying to remove user by username: " + username; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "Deleting a User", + notes = "In a situation where an employee leaves the organization you will need to remove the" + + " user details from WSO2 EMM. In such situations you can use this REST API " + + "to remove a user") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "User by username: 'username' was successfully removed"), + @ApiResponse(code = 400, message = "User by username: 'username' does not exist for removal"), + @ApiResponse(code = 500, message = "Exception in trying to remove user by username: 'username'") + }) + Response removeUser(@ApiParam(name = "username", value = "Provide the name of the user you wish to delete" + + " as the value for {username}", required = true) + @QueryParam("username") String username); - /** - * get all the roles except for the internal/xxx and application/xxx - * - * @param userStoreManager User Store Manager associated with the currently logged in user - * @param username Username of the currently logged in user - * @return the list of filtered roles - */ - private List getFilteredRoles(UserStoreManager userStoreManager, String username) { - String[] roleListOfUser = new String[0]; - try { - roleListOfUser = userStoreManager.getRoleListOfUser(username); - } catch (UserStoreException e) { - e.printStackTrace(); - } - List filteredRoles = new ArrayList<>(); - for (String role : roleListOfUser) { - if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) { - filteredRoles.add(role); - } - } - return filteredRoles; - } - - /** - * Get user's roles by username - * - * @param username Username of the user - * @return {Response} Status of the request wrapped inside Response object. - */ @GET @Path("roles") @Produces({MediaType.APPLICATION_JSON}) - public Response getRoles(@QueryParam("username") String username) { - ResponsePayload responsePayload = new ResponsePayload(); - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(username)) { - responsePayload.setResponseContent(Collections.singletonList(getFilteredRoles(userStoreManager, username))); - // Outputting debug message upon successful removal of user - if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " was successfully removed."); - } - // returning response with success state - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer( - "User roles obtained for user " + username); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } else { - // Outputting debug message upon trying to remove non-existing user - if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " does not exist for role retrieval."); - } - // returning response with bad request state - responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); - responsePayload.setMessageFromServer( - "User by username: " + username + " does not exist for role retrieval."); - return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); - } - } catch (UserStoreException | MDMAPIException e) { - String msg = "Exception in trying to retrieve roles for user by username: " + username; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting the Role Details of a User", + notes = "A user can be assigned to one or more role in WSO2 EMM. Using this REST API you are " + + "able to get the role/roles a user is assigned to", + response = String.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "User roles obtained for user : 'username'"), + @ApiResponse(code = 400, message = "User by username: 'username' does not exist for role retrieval"), + @ApiResponse(code = 500, message = "Exception in trying to retrieve roles for user by username: 'username'") + }) + Response getRolesOfUser(@ApiParam(name = "username", value = "Provide the user name of the user you wish to get" + + " the role details", required = true) @QueryParam("username") String username); - /** - * Get the list of all users with all user-related info. - * - * @return A list of users - */ @GET @Produces({MediaType.APPLICATION_JSON}) - public Response getAllUsers() { - if (log.isDebugEnabled()) { - log.debug("Getting the list of users with all user-related information"); - } - List userList; - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - String[] users = userStoreManager.listUsers("*", -1); - userList = new ArrayList<>(users.length); - UserWrapper user; - for (String username : users) { - user = new UserWrapper(); - user.setUsername(username); - user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); - user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); - user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); - userList.add(user); - } - } catch (UserStoreException | MDMAPIException e) { - String msg = "Error occurred while retrieving the list of users"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - int count; - count = userList.size(); - responsePayload.setMessageFromServer("All users were successfully retrieved. " + - "Obtained user count: " + count); - responsePayload.setResponseContent(userList); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of Users", + notes = "If you wish to get the details of all the user registered with WSO2 EMM, you can do so " + + "using the REST API", + response = UserWrapper.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "All users were successfully retrieved"), + @ApiResponse(code = 500, message = "Error occurred while retrieving the list of users") + }) + Response getAllUsers(); - /** - * Get the list of all users with all user-related info. - * - * @return A list of users - */ @GET @Path("{filter}") @Produces({MediaType.APPLICATION_JSON}) - public Response getMatchingUsers(@PathParam("filter") String filter) { - if (log.isDebugEnabled()) { - log.debug("Getting the list of users with all user-related information using the filter : " + filter); - } - List userList; - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - String[] users = userStoreManager.listUsers(filter + "*", -1); - userList = new ArrayList<>(users.length); - UserWrapper user; - for (String username : users) { - user = new UserWrapper(); - user.setUsername(username); - user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); - user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); - user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); - userList.add(user); - } - } catch (UserStoreException | MDMAPIException e) { - String msg = "Error occurred while retrieving the list of users using the filter : " + filter; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - int count; - count = userList.size(); - responsePayload.setMessageFromServer("All users were successfully retrieved. " + - "Obtained user count: " + count); - responsePayload.setResponseContent(userList); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + Response getMatchingUsers(@PathParam("filter") String filter); - /** - * Get the list of user names in the system. - * - * @return A list of user names. - */ @GET @Path("view-users") - public Response getAllUsersByUsername(@QueryParam("username") String userName) { - if (log.isDebugEnabled()) { - log.debug("Getting the list of users by name"); - } - List userList; - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - String[] users = userStoreManager.listUsers("*" + userName + "*", -1); - userList = new ArrayList<>(users.length); - UserWrapper user; - for (String username : users) { - user = new UserWrapper(); - user.setUsername(username); - user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); - user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); - user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); - userList.add(user); - } - } catch (UserStoreException | MDMAPIException e) { - String msg = "Error occurred while retrieving the list of users"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - int count; - count = userList.size(); - responsePayload.setMessageFromServer("All users by username were successfully retrieved. " + - "Obtained user count: " + count); - responsePayload.setResponseContent(userList); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting User Details by Searching via the User Name", + notes = "You will have 100+ users registered with WSO2 EMM. If you wish to retrieve the user " + + "details of a specific user, and you only remember part of the user's username, " + + "you are able to retrieve the user details by giving a character or a few characters " + + "in the username", + response = String.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "All users by username were successfully retrieved. Obtained" + + " user count: 'count'"), + @ApiResponse(code = 500, message = "Error occurred while retrieving the list of users") + }) + Response getAllUsersByUsername(@ApiParam(name = "username", value = "Provide any user detail of the user" + + " as the value for {username} to retrieve the user details, such " + + "as email address, first name or last name", required = true) + @QueryParam("username") String userName); - /** - * Get the list of user names in the system. - * - * @return A list of user names. - */ @GET @Path("users-by-username") - public Response getAllUserNamesByUsername(@QueryParam("username") String userName) { - if (log.isDebugEnabled()) { - log.debug("Getting the list of users by name"); - } - List userList; - try { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - String[] users = userStoreManager.listUsers("*" + userName + "*", -1); - userList = new ArrayList<>(users.length); - Collections.addAll(userList, users); - } catch (UserStoreException | MDMAPIException e) { - String msg = "Error occurred while retrieving the list of users"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - int count; - count = userList.size(); - responsePayload.setMessageFromServer("All users by username were successfully retrieved. " + - "Obtained user count: " + count); - responsePayload.setResponseContent(userList); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Searching for a User Name", + notes = "You will have 100+ users registered with WSO2 EMM. Therefore if you are unsure of the " + + "user name of a user and need to retrieve the details of a specific user, you can " + + "search for that user by giving a character or a few characters in the username. " + + "You will be given a list of users having the user name with the exact order of the " + + "characters you provided", + response = String.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "All users by username were successfully retrieved. Obtained" + + " user count: 'count'"), + @ApiResponse(code = 500, message = "Error occurred while retrieving the list of users") + }) + Response getAllUserNamesByUsername(@ApiParam(name = "username", value = "Provide a character or a few " + + "character in the user name as the value for {username}", + required = true) @QueryParam("username") String userName); - /** - * Gets a claim-value from user-store. - * - * @param username Username of the user - * @param claimUri required ClaimUri - * @return claim value - */ - private String getClaimValue(String username, String claimUri) throws MDMAPIException { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - try { - return userStoreManager.getUserClaimValue(username, claimUri, null); - } catch (UserStoreException e) { - throw new MDMAPIException("Error occurred while retrieving value assigned to the claim '" + - claimUri + "'", e); - } - } - - /** - * Method used to send an invitation email to a new user to enroll a device. - * - * @param username Username of the user - */ - private void inviteNewlyAddedUserToEnrollDevice(String username, String password) throws MDMAPIException { - if (log.isDebugEnabled()) { - log.debug("Sending invitation mail to user by username: " + username); - } - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) { - tenantDomain = ""; - } - if (!username.contains("/")) { - username = "/" + username; - } - String[] usernameBits = username.split("/"); - DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); - - Properties props = new Properties(); - props.setProperty("username", usernameBits[1]); - props.setProperty("domain-name", tenantDomain); - props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); - props.setProperty("password", password); - - String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS); - - EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); - try { - deviceManagementProviderService.sendRegistrationEmail(metaInfo); - } catch (DeviceManagementException e) { - String msg = "Error occurred while sending registration email to user '" + username + "'"; - log.error(msg, e); - throw new MDMAPIException(msg, e); - } - } - - /** - * Method used to send an invitation email to a existing user to enroll a device. - * - * @param usernames Username list of the users to be invited - */ @POST @Path("email-invitation") @Produces({MediaType.APPLICATION_JSON}) - public Response inviteExistingUsersToEnrollDevice(List usernames) { - if (log.isDebugEnabled()) { - log.debug("Sending enrollment invitation mail to existing user."); - } - DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); - try { - for (String username : usernames) { - String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS); + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Sending Enrollment Invitations to Users", + notes = "Send the users a mail inviting them to download the EMM mobile application on their " + + "devices using this REST API") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Email invitation was successfully sent to user"), + @ApiResponse(code = 500, message = "Error occurred while retrieving the list of users") + }) + Response inviteExistingUsersToEnrollDevice(@ApiParam(name = "usernames", value = "List of the users to be" + + " invited as the ", required = true) + List usernames); - Properties props = new Properties(); - props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); - props.setProperty("username", username); - - EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); - deviceManagementProviderService.sendEnrolmentInvitation(metaInfo); - } - } catch (DeviceManagementException | MDMAPIException e) { - String msg = "Error occurred while inviting user to enrol their device"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - ResponsePayload responsePayload = new ResponsePayload(); - responsePayload.setStatusCode(HttpStatus.SC_OK); - responsePayload.setMessageFromServer("Email invitation was successfully sent to user."); - return Response.status(Response.Status.OK).entity(responsePayload).build(); - } - - /** - * Get a list of devices based on the username. - * - * @param username Username of the device owner - * @return A list of devices - */ @GET @Produces({MediaType.APPLICATION_JSON}) @Path("devices") - public Response getAllDeviceOfUser(@QueryParam("username") String username, @QueryParam("start") int startIdx, - @QueryParam("length") int length) { - DeviceManagementProviderService dmService; - try { - dmService = DeviceMgtAPIUtils.getDeviceManagementService(); - if (length > 0) { - PaginationRequest request = new PaginationRequest(startIdx, length); - request.setOwner(username); - return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(request)).build(); - } - return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(username)).build(); - } catch (DeviceManagementException e) { - String msg = "Device management error"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Device Details of a User", + notes = "If you wish to get the details of the devices enrolled by a specific user, you can do " + + "so using this REST API", + response = org.wso2.carbon.device.mgt.common.Device.class, + responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK"), + @ApiResponse(code = 500, message = "Device management error") + }) + Response getAllDeviceOfUser(@ApiParam(name = "username", value = "Provide the name of the user you wish " + + "to get the details", required = true) @QueryParam("username") + String username, + @ApiParam(name = "start", value = "Provide the starting pagination index", + required = true) @QueryParam("start") int startIdx, + @ApiParam(name = "length", value = "Provide how many device details you " + + "require from the starting pagination index", required = true) + @QueryParam("length") int length); - /** - * This method is used to retrieve the user count of the system. - * - * @return returns the count. - * @ - */ @GET @Path("count") - public Response getUserCount() { - try { - String[] users = DeviceMgtAPIUtils.getUserStoreManager().listUsers("*", -1); - Integer count = 0; - if (users != null) { - count = users.length; - } - return Response.status(Response.Status.OK).entity(count).build(); - } catch (UserStoreException | MDMAPIException e) { - String msg = - "Error occurred while retrieving the list of users that exist within the current tenant"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } + @ApiOperation( + httpMethod = "GET", + value = "Getting the User Count", + notes = "Get the number of users in WSO2 EMM", + response = int.class) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK"), + @ApiResponse(code = 500, message = "Error occurred while retrieving the list of users that exist" + + " within the current tenant") + }) + Response getUserCount(); - /** - * API is used to update roles of a user - * - * @param username - * @param userList - * @return - * @ - */ @PUT @Path("{roleName}/users") @Produces({MediaType.APPLICATION_JSON}) - public Response updateRoles(@PathParam("username") String username, List userList) { - try { - final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (log.isDebugEnabled()) { - log.debug("Updating the roles of a user"); - } - SetReferenceTransformer transformer = new SetReferenceTransformer<>(); - transformer.transform(Arrays.asList(userStoreManager.getRoleListOfUser(username)), - userList); - final String[] rolesToAdd = transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]); - final String[] rolesToDelete = transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]); + Response updateRoles(@PathParam("roleName") String roleName, List userList); - userStoreManager.updateRoleListOfUser(username, rolesToDelete, rolesToAdd); - } catch (UserStoreException | MDMAPIException e) { - String msg = "Error occurred while saving the roles for user: " + username; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).build(); - } - - /** - * Method to change the user password. - * - * @param credentials Wrapper object representing user credentials. - * @return {Response} Status of the request wrapped inside Response object. - * @ - */ @POST @Path("change-password") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response resetPassword(UserCredentialWrapper credentials) { - return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials); - } + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Changing the User Password", + notes = "A user is able to change the password to secure their EMM profile via this REST API") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "UserImpl password by username: 'Username' was " + + "successfully changed"), + @ApiResponse(code = 400, message = "Old password does not match"), + @ApiResponse(code = 400, message = "Could not change the password of the user: 'Username'. The" + + " Character Encoding is not supported"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + Response resetPassword(@ApiParam(name = "credentials", value = "Include the required properties to change" + + " the user password as value", required = true) + UserCredentialWrapper credentials); - /** - * Method to change the user password. - * - * @param credentials Wrapper object representing user credentials. - * @return {Response} Status of the request wrapped inside Response object. - * @ - */ @POST @Path("reset-password") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) - public Response resetPasswordByAdmin(UserCredentialWrapper credentials) { - return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials); - } - -} \ No newline at end of file + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Resetting the User Password", + notes = "In a situation where you need to block a user from accessing their EMM profile, " + + "the EMM administrator is able to reset the password. This will change the user's " + + "password and the user will not be able to able to login to the account as he/she is " + + "not aware of the new password.") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "UserImpl password by username: 'Username' was " + + "successfully changed"), + @ApiResponse(code = 400, message = "Old password does not match"), + @ApiResponse(code = 400, message = "Could not change the password of the user: 'Username'. The" + + " Character Encoding is not supported"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + Response resetPasswordByAdmin(@ApiParam(name = "credentials", value = "Include the required properties " + + "to change a user password as value", + required = true) UserCredentialWrapper credentials); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/CertificateImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/CertificateImpl.java new file mode 100644 index 0000000000..de062241f9 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/CertificateImpl.java @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.jaxrs.api.Certificate; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate; +import org.wso2.carbon.device.mgt.jaxrs.exception.Message; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +/** + * All the certificate related tasks such as saving certificates, can be done through this endpoint. + */ +@SuppressWarnings("NonJaxWsWebServices") +@Produces({"application/json", "application/xml"}) +@Consumes({ "application/json", "application/xml" }) +public class CertificateImpl implements Certificate { + + private static Log log = LogFactory.getLog(OperationImpl.class); + + /** + * Save a list of certificates and relevant information in the database. + * + * @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as + * a pem and a serial number. + * @return Status of the data persist operation. + */ + @POST + @Path("saveCertificate") + public Response saveCertificate(@HeaderParam("Accept") String acceptHeader, + EnrollmentCertificate[] enrollmentCertificates) { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); + CertificateManagementService certificateService; + List certificates = new ArrayList<>(); + org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate; + certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + try { + for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) { + certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); + certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + certificate.setSerial(enrollmentCertificate.getSerial()); + certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem())); + certificates.add(certificate); + } + certificateService.saveCertificate(certificates); + return Response.status(Response.Status.CREATED).entity("Added successfully."). + type(responseMediaType).build(); + } catch (KeystoreException e) { + String msg = "Error occurred while converting PEM file to X509Certificate."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); + } + } + + /** + * Get a certificate when the serial number is given. + * + * @param serialNumber serial of the certificate needed. + * @return certificate response. + */ + @GET + @Path("{serialNumber}") + public Response getCertificate(@HeaderParam("Accept") String acceptHeader, + @PathParam("serialNumber") String serialNumber) { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); + Message message = new Message(); + + if (serialNumber == null || serialNumber.isEmpty()) { + message.setErrorMessage("Invalid serial number"); + message.setDiscription("Serial number is missing or invalid."); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); + } + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + CertificateResponse certificateResponse; + try { + certificateResponse = certificateService.getCertificateBySerial(serialNumber); + if(certificateResponse != null) { + certificateResponse.setCertificate(null); //avoid sending byte array in response. + } + return Response.status(Response.Status.OK).entity(certificateResponse).type(responseMediaType).build(); + } catch (KeystoreException e) { + String msg = "Error occurred while converting PEM file to X509Certificate"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); + } + } + + /** + * Get all certificates in a paginated manner. + * + * @param startIndex index of the first record to be fetched + * @param length number of records to be fetched starting from the start index. + * @return paginated result of certificate. + * @throws MDMAPIException + */ + @GET + @Path("paginate") + public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader, + @QueryParam("start") int startIndex, + @QueryParam("length") int length) + throws MDMAPIException { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); + Message message = new Message(); + + if (startIndex < 0) { + message.setErrorMessage("Invalid start index."); + message.setDiscription("Start index cannot be less that 0."); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); + } else if (length <= 0) { + message.setErrorMessage("Invalid length value."); + message.setDiscription("Length should be a positive integer."); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); + } + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + PaginationRequest paginationRequest = new PaginationRequest(startIndex, length); + try { + PaginationResult certificates = certificateService.getAllCertificates(paginationRequest); + return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build(); + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while fetching all certificates."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); + } + } + + @DELETE + @Path("{serialNumber}") + public Response removeCertificate(@HeaderParam("Accept") String acceptHeader, + @PathParam("serialNumber") String serialNumber) throws MDMAPIException { + MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader); + Message message = new Message(); + + if (serialNumber == null || serialNumber.isEmpty()) { + message.setErrorMessage("Invalid serial number"); + message.setDiscription("Serial number is missing or invalid."); + return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build(); + } + + CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + boolean deleted; + try { + deleted = certificateService.removeCertificate(serialNumber); + if(deleted){ + return Response.status(Response.Status.OK).entity(deleted).type(responseMediaType).build(); + } else { + return Response.status(Response.Status.GONE).entity(deleted).type(responseMediaType).build(); + } + } catch (CertificateManagementDAOException e) { + String msg = "Error occurred while converting PEM file to X509Certificate"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build(); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/ConfigurationImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/ConfigurationImpl.java new file mode 100644 index 0000000000..1d48daf31d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/ConfigurationImpl.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; +import org.wso2.carbon.device.mgt.jaxrs.api.Configuration; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAppConstants; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +/** + * General Tenant Configuration REST-API implementation. + * All end points support JSON, XMl with content negotiation. + */ +@SuppressWarnings("NonJaxWsWebServices") +@Produces({"application/json", "application/xml"}) +@Consumes({ "application/json", "application/xml" }) +public class ConfigurationImpl implements Configuration{ + + private static Log log = LogFactory.getLog(ConfigurationImpl.class); + + @POST + public Response saveTenantConfiguration(TenantConfiguration configuration) { + ResponsePayload responseMsg = new ResponsePayload(); + try { + DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, + MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); + //Schedule the task service + DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration)); + responseMsg.setMessageFromServer("Tenant configuration saved successfully."); + responseMsg.setStatusCode(HttpStatus.SC_CREATED); + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (ConfigurationManagementException e) { + String msg = "Error occurred while saving the tenant configuration."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @GET + public Response getConfiguration() { + String msg; + try { + TenantConfiguration tenantConfiguration = DeviceMgtAPIUtils.getTenantConfigurationManagementService(). + getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); + ConfigurationEntry configurationEntry = new ConfigurationEntry(); + configurationEntry.setContentType("text"); + configurationEntry.setName("notifierFrequency"); + configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency()); + List configList = tenantConfiguration.getConfiguration(); + if (configList == null) { + configList = new ArrayList<>(); + } + configList.add(configurationEntry); + tenantConfiguration.setConfiguration(configList); + return Response.status(Response.Status.OK).entity(tenantConfiguration).build(); + } catch (ConfigurationManagementException e) { + msg = "Error occurred while retrieving the tenant configuration."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @PUT + public Response updateConfiguration(TenantConfiguration configuration) { + ResponsePayload responseMsg = new ResponsePayload(); + try { + DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration, + MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); + //Schedule the task service + DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration)); + responseMsg.setMessageFromServer("Tenant configuration updated successfully."); + responseMsg.setStatusCode(HttpStatus.SC_CREATED); + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (ConfigurationManagementException e) { + String msg = "Error occurred while updating the tenant configuration."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceImpl.java new file mode 100644 index 0000000000..19ea361c08 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceImpl.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.Device; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.List; + +/** + * Device related operations + */ +@SuppressWarnings("NonJaxWsWebServices") +public class DeviceImpl implements Device{ + private static Log log = LogFactory.getLog(DeviceImpl.class); + + /** + * Get all devices. We have to use accept all the necessary query parameters sent by datatable. + * Hence had to put lot of query params here. + * + * @return Device List + */ + @GET + public Response getAllDevices(@QueryParam("type") String type, @QueryParam("user") String user, + @QueryParam("role") String role, @QueryParam("status") EnrolmentInfo.Status status, + @QueryParam("start") int startIdx, @QueryParam("length") int length, + @QueryParam("device-name") String deviceName, + @QueryParam("ownership") EnrolmentInfo.OwnerShip ownership) { + try { + DeviceManagementProviderService service = DeviceMgtAPIUtils.getDeviceManagementService(); + //Length > 0 means this is a pagination request. + if (length > 0) { + PaginationRequest paginationRequest = new PaginationRequest(startIdx, length); + paginationRequest.setDeviceName(deviceName); + paginationRequest.setOwner(user); + if (ownership != null) { + paginationRequest.setOwnership(ownership.toString()); + } + if (status != null) { + paginationRequest.setStatus(status.toString()); + } + paginationRequest.setDeviceType(type); + return Response.status(Response.Status.OK).entity(service.getAllDevices(paginationRequest)).build(); + } + + List allDevices; + if ((type != null) && !type.isEmpty()) { + allDevices = service.getAllDevices(type); + } else if ((user != null) && !user.isEmpty()) { + allDevices = service.getDevicesOfUser(user); + } else if ((role != null) && !role.isEmpty()) { + allDevices = service.getAllDevicesOfRole(role); + } else if (status != null) { + allDevices = service.getDevicesByStatus(status); + } else if (deviceName != null) { + allDevices = service.getDevicesByName(deviceName); + } else { + allDevices = service.getAllDevices(); + } + return Response.status(Response.Status.OK).entity(allDevices).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the device list."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Fetch device details for a given device type and device Id. + * + * @return Device wrapped inside Response + */ + @GET + @Path("view") + @Produces({MediaType.APPLICATION_JSON}) + public Response getDevice(@QueryParam("type") String type, + @QueryParam("id") String id) { + DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id); + DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); + org.wso2.carbon.device.mgt.common.Device device; + try { + device = deviceManagementProviderService.getDevice(deviceIdentifier); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the device information."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + if (device == null) { + responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND); + responsePayload.setMessageFromServer("Requested device by type: " + + type + " and id: " + id + " does not exist."); + return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build(); + } else { + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Sending Requested device by type: " + type + " and id: " + id + "."); + responsePayload.setResponseContent(device); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + } + + /** + * Fetch device details of a given user. + * + * @param user User Name + * @return Device + */ + @GET + @Path("user/{user}") + public Response getDeviceOfUser(@PathParam("user") String user) { + List devices; + try { + devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(user); + if (devices == null) { + return Response.status(Response.Status.NOT_FOUND).build(); + } + return Response.status(Response.Status.OK).entity(devices).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the devices list of given user."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Fetch device count of a given user. + * + * @param user User Name + * @return Device + */ + @GET + @Path("user/{user}/count") + public Response getDeviceCountOfUser(@PathParam("user") String user) { + try { + Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(user); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the devices list of given user."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Get current device count + * + * @return device count + */ + @GET + @Path("count") + public Response getDeviceCount() { + try { + Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the device count."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Get the list of devices that matches with the given name. + * + * @param deviceName Device name + * @param tenantDomain Callee tenant domain + * @return list of devices. + */ + @GET + @Path("name/{name}/{tenantDomain}") + public Response getDevicesByName(@PathParam("name") String deviceName, + @PathParam("tenantDomain") String tenantDomain) { + List devices; + try { + devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(deviceName); + return Response.status(Response.Status.OK).entity(devices).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the devices list of device name."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Get the list of available device types. + * + * @return list of device types. + */ + @GET + @Path("types") + public Response getDeviceTypes() { + List deviceTypes; + try { + deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes(); + return Response.status(Response.Status.OK).entity(deviceTypes).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the list of device types."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Update device. + * + * @return update status. + */ + @PUT + @Path("type/{type}/id/{deviceId}") + public Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId, + org.wso2.carbon.device.mgt.common.Device updatedDevice) { + try { + DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setType(deviceType); + deviceIdentifier.setId(deviceId); + org.wso2.carbon.device.mgt.common.Device device = deviceManagementService.getDevice(deviceIdentifier); + device.setName(updatedDevice.getName()); + device.setDescription(updatedDevice.getDescription()); + Boolean response = deviceManagementService.modifyEnrollment(device); + return Response.status(Response.Status.OK).entity(response).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the list of device types."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * disenroll device. + * + * @return disenrollment status. + */ + @DELETE + @Path("type/{type}/id/{deviceId}") + public Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId) { + try { + DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setType(deviceType); + deviceIdentifier.setId(deviceId); + Boolean response = deviceManagementService.disenrollDevice(deviceIdentifier); + return Response.status(Response.Status.OK).entity(response).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the list of device types."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java new file mode 100644 index 0000000000..17b59364f6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceInformationImpl.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; +import org.wso2.carbon.device.mgt.jaxrs.api.DeviceInformation; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; + +@SuppressWarnings("NonJaxWsWebServices") +public class DeviceInformationImpl implements DeviceInformation { + + private static Log log = LogFactory.getLog(DeviceInformationImpl.class); + + @GET + @Path("{type}/{id}") + public Response getDeviceInfo(@PathParam("type") String type, @PathParam("id") String id) { + DeviceInformationManager informationManager; + DeviceInfo deviceInfo; + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(id); + deviceIdentifier.setType(type); + informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); + deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); + } catch (DeviceDetailsMgtException e) { + String msg = "Error occurred while getting the device information."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(deviceInfo).build(); + } + + + @GET + @Path("location/{type}/{id}") + public Response getDeviceLocation(@PathParam("type") String type, @PathParam("id") String id) { + DeviceInformationManager informationManager; + DeviceLocation deviceLocation; + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(id); + deviceIdentifier.setType(type); + informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); + deviceLocation = informationManager.getDeviceLocation(deviceIdentifier); + } catch (DeviceDetailsMgtException e) { + String msg = "Error occurred while getting the device location."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(deviceLocation).build(); + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceNotificationImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceNotificationImpl.java new file mode 100644 index 0000000000..3a4ece1a17 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceNotificationImpl.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.DeviceNotification; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; +import java.util.List; + +/** + * DeviceNotification management REST-API implementation. + * All end points support JSON, XMl with content negotiation. + */ +@SuppressWarnings("NonJaxWsWebServices") +@Produces({"application/json", "application/xml"}) +@Consumes({ "application/json", "application/xml" }) +public class DeviceNotificationImpl implements DeviceNotification{ + + private static Log log = LogFactory.getLog(ConfigurationImpl.class); + + @GET + public Response getNotifications() { + String msg; + try { + List notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications(); + return Response.status(Response.Status.OK).entity(notifications).build(); + } catch (NotificationManagementException e) { + msg = "Error occurred while retrieving the notification list."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @GET + @Path("{status}") + public Response getNotificationsByStatus(@PathParam("status") Notification.Status status) { + String msg; + try { + List notifications = DeviceMgtAPIUtils.getNotificationManagementService().getNotificationsByStatus(status); + return Response.status(Response.Status.OK).entity(notifications).build(); + } catch (NotificationManagementException e) { + msg = "Error occurred while retrieving the notification list."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @PUT + @Path("{id}/{status}") + public Response updateNotificationStatus(@PathParam("id") int id, + @PathParam("status") Notification.Status status) { + ResponsePayload responseMsg = new ResponsePayload(); + try { + DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status); + responseMsg.setMessageFromServer("Notification status updated successfully."); + responseMsg.setStatusCode(HttpStatus.SC_ACCEPTED); + return Response.status(Response.Status.ACCEPTED).entity(responseMsg).build(); + } catch (NotificationManagementException e) { + String msg = "Error occurred while updating notification status."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @POST + public Response addNotification(Notification notification) { + ResponsePayload responseMsg = new ResponsePayload(); + try { + DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification); + responseMsg.setMessageFromServer("Notification has added successfully."); + responseMsg.setStatusCode(HttpStatus.SC_CREATED); + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (NotificationManagementException e) { + String msg = "Error occurred while updating notification status."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceSearchImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceSearchImpl.java new file mode 100644 index 0000000000..7ed9576d0b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/DeviceSearchImpl.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; +import org.wso2.carbon.device.mgt.common.search.SearchContext; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; +import org.wso2.carbon.device.mgt.jaxrs.api.DeviceSearch; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; + +import javax.ws.rs.GET; +import javax.ws.rs.core.Response; +import java.util.List; + +@SuppressWarnings("NonJaxWsWebServices") +public class DeviceSearchImpl implements DeviceSearch { + + private static Log log = LogFactory.getLog(DeviceSearchImpl.class); + + @GET + public Response getFilteredDeviceInfo(SearchContext searchContext) { + SearchManagerService searchManagerService; + List devices; + try { + searchManagerService = DeviceMgtAPIUtils.getSearchManagerService(); + devices = searchManagerService.search(searchContext); + + } catch (SearchMgtException e) { + String msg = "Error occurred while searching the device information."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(devices).build(); + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/FeatureImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/FeatureImpl.java new file mode 100644 index 0000000000..11734ae365 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/FeatureImpl.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.Feature; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; +import java.util.List; + +/** + * Features + */ +@SuppressWarnings("NonJaxWsWebServices") +@Produces({"application/json", "application/xml"}) +@Consumes({"application/json", "application/xml"}) +public class FeatureImpl implements Feature{ + private static Log log = LogFactory.getLog(FeatureImpl.class); + + /** + * Get all features for Mobile Device Type + * + * @return Feature + */ + @GET + @Path("/{type}") + public Response getFeatures(@PathParam("type") String type) { + List features; + DeviceManagementProviderService dmService; + try { + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + features = dmService.getFeatureManager(type).getFeatures(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving the list of features"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(features).build(); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java new file mode 100644 index 0000000000..4c47f1b35b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/GroupImpl.java @@ -0,0 +1,533 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +import org.wso2.carbon.device.mgt.jaxrs.api.Group; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import java.util.Date; +import java.util.List; + +@SuppressWarnings("NonJaxWsWebServices") +public class GroupImpl implements Group { + + private static Log log = LogFactory.getLog(GroupImpl.class); + + @Override + @POST + @Consumes("application/json") + public Response createGroup(DeviceGroup group) { + String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + if (group == null) { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + group.setOwner(owner); + group.setDateOfCreation(new Date().getTime()); + group.setDateOfLastUpdate(new Date().getTime()); + try { + GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService(); + groupManagementService.createGroup(group, DeviceGroupConstants.Roles.DEFAULT_ADMIN_ROLE, DeviceGroupConstants.Permissions.DEFAULT_ADMIN_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, + DeviceGroupConstants.Roles.DEFAULT_OPERATOR_ROLE, + DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_STATS_MONITOR_ROLE, + DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_POLICIES, + DeviceGroupConstants.Permissions.DEFAULT_VIEW_POLICIES_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_MANAGE_POLICIES, + DeviceGroupConstants.Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS); + groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_EVENTS, + DeviceGroupConstants.Permissions.DEFAULT_VIEW_EVENTS_PERMISSIONS); + return Response.status(Response.Status.CREATED).build(); + } catch (GroupAlreadyEixistException e) { + return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build(); + } catch (GroupManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/owner/{owner}/name/{groupName}") + @PUT + @Consumes("application/json") + @Produces("application/json") + public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + DeviceGroup deviceGroup) { + try { + DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupName, owner); + return Response.status(Response.Status.OK).build(); + } catch (GroupManagementException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/owner/{owner}/name/{groupName}") + @DELETE + public Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { + try { + DeviceMgtAPIUtils.getGroupManagementProviderService().deleteGroup(groupName, owner); + return Response.status(Response.Status.OK).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @GET + @Produces("application/json") + public Response getGroups(@QueryParam("start") int startIndex, @PathParam("length") int length) { + try { + PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getGroups(startIndex, length); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/all") + @GET + @Produces("application/json") + public Response getAllGroups() { + try { + GroupManagementProviderService groupManagementProviderService = DeviceMgtAPIUtils + .getGroupManagementProviderService(); + PaginationResult paginationResult = groupManagementProviderService + .getGroups(0, groupManagementProviderService.getGroupCount()); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult.getData()).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/user/{user}") + @GET + @Produces("application/json") + public Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex, + @QueryParam("length") int length) { + try { + PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getGroups(userName, startIndex, length); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/user/{user}/all") + @GET + @Produces("application/json") + public Response getGroups(@PathParam("user") String userName) { + try { + List deviceGroups = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getGroups(userName); + if (deviceGroups.size() > 0) { + return Response.status(Response.Status.OK).entity(deviceGroups).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/owner/{owner}/name/{groupName}") + @GET + @Produces("application/json") + public Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { + try { + DeviceGroup deviceGroup = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroup(groupName, owner); + if (deviceGroup != null) { + return Response.status(Response.Status.OK).entity(deviceGroup).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/user/{user}/search") + @GET + @Produces("application/json") + public Response findGroups(@QueryParam("groupName") String groupName, @PathParam("user") String user) { + try { + List groups = DeviceMgtAPIUtils.getGroupManagementProviderService() + .findInGroups(groupName, user); + DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()]; + groups.toArray(deviceGroups); + return Response.status(Response.Status.OK).entity(deviceGroups).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/user/{user}/all") + @GET + @Produces("application/json") + public Response getGroups(@PathParam("user") String userName, @QueryParam("permission") String permission) { + try { + GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService(); + List groups; + if (permission != null) { + groups = groupManagementService.getGroups(userName, permission); + } else { + groups = groupManagementService.getGroups(userName); + } + DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()]; + groups.toArray(deviceGroups); + return Response.status(Response.Status.OK).entity(deviceGroups).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/count") + @GET + @Produces("application/json") + public Response getAllGroupCount() { + try { + int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/user/{user}/count") + @GET + @Produces("application/json") + public Response getGroupCount(@PathParam("user") String userName) { + try { + int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(userName); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/owner/{owner}/name/{groupName}/share") + @PUT + @Produces("application/json") + public Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @FormParam("shareUser") String shareUser, + @FormParam("roleName") String sharingRole) { + + try { + boolean isShared = DeviceMgtAPIUtils.getGroupManagementProviderService().shareGroup( + shareUser, groupName, owner, sharingRole); + if (isShared) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build(); + } + } catch (UserDoesNotExistException e) { + return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/owner/{owner}/name/{groupName}/unshare") + @PUT + @Produces("application/json") + public Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @FormParam("unShareUser") String unShareUser, + @FormParam("roleName") String sharingRole) { + try { + boolean isUnShared = DeviceMgtAPIUtils.getGroupManagementProviderService().unshareGroup( + unShareUser, groupName, owner, sharingRole); + if (isUnShared) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build(); + } + } catch (UserDoesNotExistException e) { + return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions") + @PUT + @Produces("application/json") + public Response addSharing(@QueryParam("shareUser") String shareUser, + @PathParam("groupName") String groupName, @PathParam("owner") String owner, + @PathParam("roleName") String roleName, + @FormParam("permissions") String[] permissions) { + + try { + boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addGroupSharingRole( + shareUser, groupName, owner, roleName, permissions); + if (isAdded) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @DELETE + @Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions") + @Produces("application/json") + public Response removeSharing(@QueryParam("userName") String userName, + @PathParam("groupName") String groupName, @PathParam("owner") String owner, + @PathParam("roleName") String roleName) { + try { + boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeGroupSharingRole( + groupName, owner, roleName); + if (isRemoved) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @GET + @Path("/owner/{owner}/name/{groupName}/share/roles") + @Produces("application/json") + public Response getRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @QueryParam("userName") String userName) { + try { + List roles; + if (userName != null && !userName.isEmpty()) { + roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(userName, groupName, owner); + } else { + roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner); + } + String[] rolesArray = new String[roles.size()]; + roles.toArray(rolesArray); + return Response.status(Response.Status.OK).entity(rolesArray).build(); + } catch (UserDoesNotExistException e) { + return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @PUT + @Path("/owner/{owner}/name/{groupName}/user/{userName}/share/roles") + @Produces("application/json") + public Response setRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @PathParam("userName") String userName, List selectedRoles) { + try { + List allRoles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner); + for (String role : allRoles) { + if (selectedRoles.contains(role)) { + DeviceMgtAPIUtils.getGroupManagementProviderService() + .shareGroup(userName, groupName, owner, role); + } else { + DeviceMgtAPIUtils.getGroupManagementProviderService() + .unshareGroup(userName, groupName, owner, role); + } + } + return Response.status(Response.Status.OK).build(); + } catch (UserDoesNotExistException e) { + return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @GET + @Path("/owner/{owner}/name/{groupName}/users") + @Produces("application/json") + public Response getUsers(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { + try { + List users = DeviceMgtAPIUtils.getGroupManagementProviderService().getUsers( + groupName, owner); + GroupUser[] usersArray = new GroupUser[users.size()]; + users.toArray(usersArray); + return Response.status(Response.Status.OK).entity(usersArray).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @GET + @Path("/owner/{owner}/name/{groupName}/devices") + @Produces("application/json") + public Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @QueryParam("start") int startIdx, @QueryParam("length") int length) { + try { + PaginationResult paginationResult = DeviceMgtAPIUtils + .getGroupManagementProviderService().getDevices(groupName, owner, startIdx, length); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @GET + @Path("/owner/{owner}/name/{groupName}/devices/count") + @Produces("application/json") + public Response getDeviceCount(@PathParam("groupName") String groupName, @PathParam("owner") String owner) { + try { + int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getDeviceCount(groupName, owner); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @POST + @Path("/owner/{owner}/name/{groupName}/devices") + @Produces("application/json") + public Response addDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + DeviceIdentifier deviceIdentifier) { + try { + boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice( + deviceIdentifier, groupName, owner); + if (isAdded) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @DELETE + @Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}") + @Produces("application/json") + public Response removeDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @PathParam("deviceId") String deviceId, + @PathParam("deviceType") String deviceType) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); + boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeDevice( + deviceIdentifier, groupName, owner); + if (isRemoved) { + return Response.status(Response.Status.OK).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + + @Override + @GET + @Path("/owner/{owner}/name/{groupName}/users/{userName}/permissions") + @Produces("application/json") + public Response getPermissions(@PathParam("userName") String userName, + @PathParam("groupName") String groupName, @PathParam("owner") String owner) { + try { + String[] permissions = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getPermissions(userName, groupName, owner); + return Response.status(Response.Status.OK).entity(permissions).build(); + } catch (UserDoesNotExistException e) { + return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/LicenseImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/LicenseImpl.java new file mode 100644 index 0000000000..d4cf6ee5bc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/LicenseImpl.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.License; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +/** + * This class represents license related operations. + */ +@SuppressWarnings("NonJaxWsWebServices") +public class LicenseImpl implements License { + + private static Log log = LogFactory.getLog(LicenseImpl.class); + + /** + * This method returns the license text related to a given device type and language code. + * + * @param deviceType Device type, ex: android, ios + * @param languageCode Language code, ex: en_US + * @return Returns the license text + */ + @GET + @Path ("{deviceType}/{languageCode}") + @Produces ({MediaType.APPLICATION_JSON}) + public Response getLicense(@PathParam ("deviceType") String deviceType, + @PathParam("languageCode") String languageCode) { + + org.wso2.carbon.device.mgt.common.license.mgt.License license; + ResponsePayload responsePayload; + try { + license = DeviceMgtAPIUtils.getDeviceManagementService().getLicense(deviceType, languageCode); + if (license == null) { + return Response.status(HttpStatus.SC_NOT_FOUND).build(); + } + responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK). + messageFromServer("License for '" + deviceType + "' was retrieved successfully"). + responseContent(license.getText()). + build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving the license configured for '" + deviceType + "' device type"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + /** + * This method is used to add license to a specific device type. + * + * @param deviceType Device type, ex: android, ios + * @param license License object + * @return Returns the acknowledgement for the action + */ + @POST + @Path ("{deviceType}") + public Response addLicense(@PathParam ("deviceType") String deviceType, + org.wso2.carbon.device.mgt.common.license.mgt.License license) { + + ResponsePayload responsePayload; + try { + DeviceMgtAPIUtils.getDeviceManagementService().addLicense(deviceType, license); + responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK). + messageFromServer("License added successfully for '" + deviceType + "' device type"). + build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while adding license for '" + deviceType + "' device type"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/OperationImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/OperationImpl.java new file mode 100644 index 0000000000..edd4fc1906 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/OperationImpl.java @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.api.context.DeviceOperationContext; +import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMIOSOperationUtil; +import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.Platform; +import org.wso2.carbon.device.mgt.common.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAndroidOperationUtil; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import java.util.List; + +/** + * Operation related REST-API implementation. + */ +@SuppressWarnings("NonJaxWsWebServices") +@Produces({"application/json", "application/xml"}) +@Consumes({"application/json", "application/xml"}) +public class OperationImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Operation { + + private static Log log = LogFactory.getLog(OperationImpl.class); + + /* @deprecated */ + @Override + @GET + public Response getAllOperations() { + List operations; + DeviceManagementProviderService dmService; + try { + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + operations = dmService.getOperations(null); + } catch (OperationManagementException e) { + String msg = "Error occurred while fetching the operations for the device."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(operations).build(); + } + + @Override + @GET + @Path("paginate/{type}/{id}") + public Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id, + @QueryParam("start") int startIdx, @QueryParam("length") int length, + @QueryParam("search") String search) { + PaginationResult operations; + DeviceManagementProviderService dmService; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + PaginationRequest paginationRequest = new PaginationRequest(startIdx, length); + try { + deviceIdentifier.setType(type); + deviceIdentifier.setId(id); + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + operations = dmService.getOperations(deviceIdentifier, paginationRequest); + } catch (OperationManagementException e) { + String msg = "Error occurred while fetching the operations for the device."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(operations).build(); + } + + @Override + @GET + @Path("{type}/{id}") + public Response getAllDeviceOperations(@PathParam("type") String type, @PathParam("id") String id) { + List operations; + DeviceManagementProviderService dmService; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + try { + deviceIdentifier.setType(type); + deviceIdentifier.setId(id); + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + operations = dmService.getOperations(deviceIdentifier); + } catch (OperationManagementException e) { + String msg = "Error occurred while fetching the operations for the device."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(operations).build(); + } + + /* @deprecated */ + @Override + @POST + public Response addOperation(DeviceOperationContext operationContext) { + DeviceManagementProviderService dmService; + ResponsePayload responseMsg = new ResponsePayload(); + try { + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + int operationId = dmService.addOperation(operationContext.getOperation(), operationContext.getDevices()); + if (operationId > 0) { + responseMsg.setStatusCode(HttpStatus.SC_CREATED); + responseMsg.setMessageFromServer("Operation has added successfully."); + } + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (OperationManagementException e) { + String msg = "Error occurred while saving the operation"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @Override + @GET + @Path("{type}/{id}/apps") + public Response getInstalledApps(@PathParam("type") String type, @PathParam("id") String id) { + List applications; + ApplicationManagementProviderService appManagerConnector; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + try { + deviceIdentifier.setType(type); + deviceIdentifier.setId(id); + appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); + applications = appManagerConnector.getApplicationListForDevice(deviceIdentifier); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while fetching the apps of the device."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.CREATED).entity(applications).build(); + } + + @Override + @POST + @Path("installApp/{tenantDomain}") + public Response installApplication(ApplicationWrapper applicationWrapper, + @PathParam("tenantDomain") String tenantDomain) { + ResponsePayload responseMsg = new ResponsePayload(); + ApplicationManager appManagerConnector; + org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; + try { + appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); + MobileApp mobileApp = applicationWrapper.getApplication(); + + if (applicationWrapper.getDeviceIdentifiers() != null) { + for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { + if (deviceIdentifier.getType().equals(Platform.android.toString())) { + operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp); + } else if (deviceIdentifier.getType().equals(Platform.ios.toString())) { + operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp); + } + } + appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); + } + responseMsg.setStatusCode(HttpStatus.SC_CREATED); + responseMsg.setMessageFromServer("Authentication installation request has been sent to the device."); + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (ApplicationManagementException | MDMAPIException e) { + String msg = "Error occurred while saving the operation"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @Override + @POST + @Path("uninstallApp/{tenantDomain}") + public Response uninstallApplication(ApplicationWrapper applicationWrapper, + @PathParam("tenantDomain") String tenantDomain) { + ResponsePayload responseMsg = new ResponsePayload(); + ApplicationManager appManagerConnector; + org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null; + try { + appManagerConnector = DeviceMgtAPIUtils.getAppManagementService(); + MobileApp mobileApp = applicationWrapper.getApplication(); + + if (applicationWrapper.getDeviceIdentifiers() != null) { + for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) { + if (deviceIdentifier.getType().equals(Platform.android.toString())) { + operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp); + } else if (deviceIdentifier.getType().equals(Platform.ios.toString())) { + operation = MDMIOSOperationUtil.createAppUninstallOperation(mobileApp); + } + } + appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); + } + responseMsg.setStatusCode(HttpStatus.SC_CREATED); + responseMsg.setMessageFromServer("Authentication removal request has been sent to the device."); + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (ApplicationManagementException | MDMAPIException e) { + String msg = "Error occurred while saving the operation"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @Override + @GET + @Path("activity/{id}") + public Response getActivity(@PathParam("id") String id) + throws MDMAPIException { + org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation; + DeviceManagementProviderService dmService; + try { + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + operation = dmService.getOperationByActivityId(id); + } catch (OperationManagementException e) { + String msg = "Error occurred while fetching the activity for the supplied id."; + log.error(msg, e); + throw new MDMAPIException(msg, e); + } + return Response.status(Response.Status.OK).entity(operation).build(); + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/PolicyImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/PolicyImpl.java new file mode 100644 index 0000000000..a1c84a0d05 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/PolicyImpl.java @@ -0,0 +1,445 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; +import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; +import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; +import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; +import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +@SuppressWarnings("NonJaxWsWebServices") +public class PolicyImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Policy { + private static Log log = LogFactory.getLog(PolicyImpl.class); + + @Override + @POST + @Path("inactive-policy") + public Response addPolicy(PolicyWrapper policyWrapper) { + + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + ResponsePayload responseMsg = new ResponsePayload(); + org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); + policy.setPolicyName(policyWrapper.getPolicyName()); + policy.setProfileId(policyWrapper.getProfileId()); + policy.setDescription(policyWrapper.getDescription()); + policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); + policy.setOwnershipType(policyWrapper.getOwnershipType()); + policy.setRoles(policyWrapper.getRoles()); + policy.setUsers(policyWrapper.getUsers()); + policy.setTenantId(policyWrapper.getTenantId()); + policy.setCompliance(policyWrapper.getCompliance()); + + return addPolicy(policyManagementService, responseMsg, policy); + } + + @Override + @POST + @Path("active-policy") + public Response addActivePolicy(PolicyWrapper policyWrapper) { + + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + ResponsePayload responseMsg = new ResponsePayload(); + org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); + policy.setPolicyName(policyWrapper.getPolicyName()); + policy.setProfileId(policyWrapper.getProfileId()); + policy.setDescription(policyWrapper.getDescription()); + policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); + policy.setOwnershipType(policyWrapper.getOwnershipType()); + policy.setRoles(policyWrapper.getRoles()); + policy.setUsers(policyWrapper.getUsers()); + policy.setTenantId(policyWrapper.getTenantId()); + policy.setCompliance(policyWrapper.getCompliance()); + policy.setActive(true); + + return addPolicy(policyManagementService, responseMsg, policy); + } + + private Response addPolicy(PolicyManagerService policyManagementService, ResponsePayload responseMsg, + org.wso2.carbon.policy.mgt.common.Policy policy) { + try { + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + pap.addPolicy(policy); + responseMsg.setStatusCode(HttpStatus.SC_CREATED); + responseMsg.setMessageFromServer("Policy has been added successfully."); + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @Override + @GET + @Produces({MediaType.APPLICATION_JSON}) + public Response getAllPolicies() { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + List policies; + try { + PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); + policies = policyAdministratorPoint.getPolicies(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Sending all retrieved device policies."); + responsePayload.setResponseContent(policies); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + @Override + @GET + @Produces({MediaType.APPLICATION_JSON}) + @Path("{id}") + public Response getPolicy(@PathParam("id") int policyId) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + final org.wso2.carbon.policy.mgt.common.Policy policy; + try { + PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); + policy = policyAdministratorPoint.getPolicy(policyId); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + if (policy == null){ + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND); + responsePayload.setMessageFromServer("Policy for ID " + policyId + " not found."); + return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Sending all retrieved device policies."); + responsePayload.setResponseContent(policy); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + @Override + @GET + @Path("count") + public Response getPolicyCount() { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + try { + PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); + Integer count = policyAdministratorPoint.getPolicyCount(); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @Override + @PUT + @Path("{id}") + public Response updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId) { + + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + ResponsePayload responseMsg = new ResponsePayload(); + org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy(); + policy.setPolicyName(policyWrapper.getPolicyName()); + policy.setId(policyId); + policy.setProfileId(policyWrapper.getProfileId()); + policy.setDescription(policyWrapper.getDescription()); + policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); + policy.setOwnershipType(policyWrapper.getOwnershipType()); + policy.setRoles(policyWrapper.getRoles()); + policy.setUsers(policyWrapper.getUsers()); + policy.setTenantId(policyWrapper.getTenantId()); + policy.setCompliance(policyWrapper.getCompliance()); + + try { + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + pap.updatePolicy(policy); + responseMsg.setStatusCode(HttpStatus.SC_CREATED); + responseMsg.setMessageFromServer("Policy has been updated successfully."); + return Response.status(Response.Status.CREATED).entity(responseMsg).build(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception in policy update."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @Override + @PUT + @Path("priorities") + @Consumes({MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_JSON}) + public Response updatePolicyPriorities(List priorityUpdatedPolicies) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + List policiesToUpdate = + new ArrayList<>(priorityUpdatedPolicies.size()); + int i; + for (i = 0; i < priorityUpdatedPolicies.size(); i++) { + org.wso2.carbon.policy.mgt.common.Policy policyObj = new org.wso2.carbon.policy.mgt.common.Policy(); + policyObj.setId(priorityUpdatedPolicies.get(i).getId()); + policyObj.setPriorityId(priorityUpdatedPolicies.get(i).getPriority()); + policiesToUpdate.add(policyObj); + } + boolean policiesUpdated; + try { + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + policiesUpdated = pap.updatePolicyPriorities(policiesToUpdate); + } catch (PolicyManagementException e) { + String msg = "Exception in updating policy priorities."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + if (policiesUpdated) { + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Policy Priorities successfully updated."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } else { + responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); + responsePayload.setMessageFromServer("Policy priorities did not update. Bad Request."); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); + } + } + + @Override + @POST + @Path("bulk-remove") + @Consumes("application/json") + @Produces("application/json") + public Response bulkRemovePolicy(List policyIds) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + boolean policyDeleted = true; + try { + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + for(int i : policyIds) { + org.wso2.carbon.policy.mgt.common.Policy policy = pap.getPolicy(i); + if(!pap.deletePolicy(policy)){ + policyDeleted = false; + } + } + } catch (PolicyManagementException e) { + String msg = "Exception in deleting policies."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + if (policyDeleted) { + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Policies have been successfully deleted."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } else { + responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); + responsePayload.setMessageFromServer("Policy does not exist."); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); + } + } + + @Override + @PUT + @Produces("application/json") + @Path("activate") + public Response activatePolicy(List policyIds) { + try { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + for(int i : policyIds) { + pap.activatePolicy(i); + } + } catch (PolicyManagementException e) { + String msg = "Exception in activating policies."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Selected policies have been successfully activated."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + @Override + @PUT + @Produces("application/json") + @Path("inactivate") + public Response inactivatePolicy(List policyIds) throws MDMAPIException { + + try { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + for(int i : policyIds) { + pap.inactivatePolicy(i); + } + } catch (PolicyManagementException e) { + String msg = "Exception in inactivating policies."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Selected policies have been successfully inactivated."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + @Override + @PUT + @Produces("application/json") + @Path("apply-changes") + public Response applyChanges() { + + try { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + pap.publishChanges(); + + + } catch (PolicyManagementException e) { + String msg = "Exception in applying changes."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Changes have been successfully updated."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + @Override + @GET + @Path("start-task/{milliseconds}") + public Response startTaskService(@PathParam("milliseconds") int monitoringFrequency) { + + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + try { + TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); + taskScheduleService.startTask(monitoringFrequency); + + + } catch (PolicyMonitoringTaskException e) { + String msg = "Policy Management related exception."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Policy monitoring service started successfully."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + @Override + @GET + @Path("update-task/{milliseconds}") + public Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency) { + + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + try { + TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); + taskScheduleService.updateTask(monitoringFrequency); + + } catch (PolicyMonitoringTaskException e) { + String msg = "Policy Management related exception."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Policy monitoring service updated successfully."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + @Override + @GET + @Path("stop-task") + public Response stopTaskService() { + + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + try { + TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService(); + taskScheduleService.stopTask(); + + } catch (PolicyMonitoringTaskException e) { + String msg = "Policy Management related exception."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Policy monitoring service stopped successfully."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + @Override + @GET + @Path("{type}/{id}") + public Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id) { + try { + DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + ComplianceData complianceData = policyManagementService.getDeviceCompliance(deviceIdentifier); + return Response.status(Response.Status.OK).entity(complianceData).build(); + } catch (PolicyComplianceException e) { + String msg = "Error occurred while getting the compliance data."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @Override + @GET + @Path("{type}/{id}/active-policy") + public Response getDeviceActivePolicy(@PathParam("type") String type, @PathParam("id") String id) { + try { + DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id); + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + org.wso2.carbon.policy.mgt.common.Policy policy = policyManagementService + .getAppliedPolicyToDevice(deviceIdentifier); + return Response.status(Response.Status.OK).entity(policy).build(); + } catch (PolicyManagementException e) { + String msg = "Error occurred while getting the current policy."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/ProfileImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/ProfileImpl.java new file mode 100644 index 0000000000..80fa8c1349 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/ProfileImpl.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.Profile; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; +import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; + +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; + +@SuppressWarnings("NonJaxWsWebServices") +public class ProfileImpl implements Profile{ + private static Log log = LogFactory.getLog(ProfileImpl.class); + + @POST + public Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + try { + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + profile = pap.addProfile(profile); + return Response.status(Response.Status.OK).entity(profile).build(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + @POST + @Path("{id}") + public Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile, + @PathParam("id") String profileId) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + ResponsePayload responseMsg = new ResponsePayload(); + try { + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + pap.updateProfile(profile); + responseMsg.setMessageFromServer("Profile has been updated successfully."); + return Response.status(Response.Status.OK).entity(responseMsg).build(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + @DELETE + @Path("{id}") + public Response deleteProfile(@PathParam("id") int profileId) { + PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); + ResponsePayload responseMsg = new ResponsePayload(); + try { + PolicyAdministratorPoint pap = policyManagementService.getPAP(); + org.wso2.carbon.policy.mgt.common.Profile profile = pap.getProfile(profileId); + pap.deleteProfile(profile); + responseMsg.setMessageFromServer("Profile has been deleted successfully."); + return Response.status(Response.Status.OK).entity(responseMsg).build(); + } catch (PolicyManagementException e) { + String msg = "Policy Management related exception"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/RoleImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/RoleImpl.java new file mode 100644 index 0000000000..278a7dfd26 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/RoleImpl.java @@ -0,0 +1,450 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; +import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; +import org.wso2.carbon.user.api.AuthorizationManager; +import org.wso2.carbon.user.api.Permission; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.user.core.common.AbstractUserStoreManager; +import org.wso2.carbon.user.mgt.UserRealmProxy; +import org.wso2.carbon.user.mgt.common.UIPermissionNode; +import org.wso2.carbon.user.mgt.common.UserAdminException; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@SuppressWarnings("NonJaxWsWebServices") +public class RoleImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Role { + + private static Log log = LogFactory.getLog(RoleImpl.class); + + /** + * Get user roles (except all internal roles) from system. + * + * @return A list of users + */ + @Override + @GET + @Produces({MediaType.APPLICATION_JSON}) + public Response getAllRoles() { + List filteredRoles; + try { + filteredRoles = getRolesFromUserStore(); + } catch (MDMAPIException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("All user roles were successfully retrieved."); + responsePayload.setResponseContent(filteredRoles); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + /** + * Get user roles by user store(except all internal roles) from system. + * + * @return A list of users + */ + @Override + @GET + @Path("{userStore}") + @Produces({MediaType.APPLICATION_JSON}) + public Response getRolesOfUserStore(@PathParam("userStore") String userStore) { + String[] roles; + try { + AbstractUserStoreManager abstractUserStoreManager = + (AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager(); + if (log.isDebugEnabled()) { + log.debug("Getting the list of user roles"); + } + roles = abstractUserStoreManager.getRoleNames(userStore + "/*", -1, false, true, true); + + } catch (UserStoreException | MDMAPIException e) { + String msg = "Error occurred while retrieving the list of user roles."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + // removing all internal roles and roles created for Service-providers + List filteredRoles = new ArrayList<>(); + for (String role : roles) { + if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) { + filteredRoles.add(role); + } + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("All user roles were successfully retrieved."); + responsePayload.setResponseContent(filteredRoles); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + /** + * Get user roles by providing a filtering criteria(except all internal roles & system roles) from system. + * + * @return A list of users + */ + @Override + @GET + @Path("search") + @Produces({MediaType.APPLICATION_JSON}) + public Response getMatchingRoles(@QueryParam("filter") String filter) { + String[] roles; + try { + AbstractUserStoreManager abstractUserStoreManager = + (AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager(); + if (log.isDebugEnabled()) { + log.debug("Getting the list of user roles using filter : " + filter); + } + roles = abstractUserStoreManager.getRoleNames("*" + filter + "*", -1, true, true, true); + + } catch (UserStoreException | MDMAPIException e) { + String msg = "Error occurred while retrieving the list of user roles using the filter : " + filter; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + // removing all internal roles and roles created for Service-providers + List filteredRoles = new ArrayList<>(); + for (String role : roles) { + if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) { + filteredRoles.add(role); + } + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("All matching user roles were successfully retrieved."); + responsePayload.setResponseContent(filteredRoles); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + /** + * Get role permissions. + * + * @return list of permissions + */ + @Override + @GET + @Path("permissions") + @Produces({MediaType.APPLICATION_JSON}) + public Response getPermissions(@QueryParam("rolename") String roleName) { + try { + final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); + org.wso2.carbon.user.core.UserRealm userRealmCore = null; + final UIPermissionNode rolePermissions; + if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { + userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; + } + final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); + rolePermissions = getUIPermissionNode(roleName, userRealmProxy); + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("All permissions retrieved"); + responsePayload.setResponseContent(rolePermissions); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } catch (UserAdminException | MDMAPIException e) { + String msg = "Error occurred while retrieving the user role"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Get user role of the system + * + * @return user role + */ + @Override + @GET + @Path("role") + @Produces({MediaType.APPLICATION_JSON}) + public Response getRole(@QueryParam("rolename") String roleName) { + RoleWrapper roleWrapper = new RoleWrapper(); + try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); + org.wso2.carbon.user.core.UserRealm userRealmCore = null; + if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { + userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; + } + + final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); + if (log.isDebugEnabled()) { + log.debug("Getting the list of user roles"); + } + if (userStoreManager.isExistingRole(roleName)) { + roleWrapper.setRoleName(roleName); + roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName)); + // Get the permission nodes and hand picking only device management and login perms + final UIPermissionNode rolePermissions = getUIPermissionNode(roleName, userRealmProxy); + ArrayList permList = new ArrayList<>(); + iteratePermissions(rolePermissions, permList); + roleWrapper.setPermissionList(rolePermissions); + String[] permListAr = new String[permList.size()]; + roleWrapper.setPermissions(permList.toArray(permListAr)); + } + } catch (UserStoreException | UserAdminException | MDMAPIException e) { + String msg = "Error occurred while retrieving the user role"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("All user roles were successfully retrieved."); + responsePayload.setResponseContent(roleWrapper); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + private UIPermissionNode getUIPermissionNode(String roleName, UserRealmProxy userRealmProxy) + throws UserAdminException { + final UIPermissionNode rolePermissions = + userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); + UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2]; + + for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) { + if (permissionNode.getResourcePath().equals("/permission/admin")) { + for (UIPermissionNode node : permissionNode.getNodeList()) { + if (node.getResourcePath().equals("/permission/admin/device-mgt")) { + deviceMgtPermissions[0] = node; + } else if (node.getResourcePath().equals("/permission/admin/login")) { + deviceMgtPermissions[1] = node; + } + } + } + } + rolePermissions.setNodeList(deviceMgtPermissions); + return rolePermissions; + } + + /** + * API is used to persist a new Role + * + * @param roleWrapper for role + * @return response + */ + @Override + @POST + @Produces({MediaType.APPLICATION_JSON}) + public Response addRole(RoleWrapper roleWrapper) { + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + if (log.isDebugEnabled()) { + log.debug("Persisting the role to user store"); + } + Permission[] permissions = null; + if (roleWrapper.getPermissions() != null && roleWrapper.getPermissions().length > 0) { + permissions = new Permission[roleWrapper.getPermissions().length]; + + for (int i = 0; i < permissions.length; i++) { + String permission = roleWrapper.getPermissions()[i]; + permissions[i] = new Permission(permission, CarbonConstants.UI_PERMISSION_ACTION); + } + } + userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions); + } catch (UserStoreException | MDMAPIException e) { + String msg = e.getMessage(); + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).build(); + } + + /** + * API is used to update a role Role + * + * @param roleWrapper for role + * @return response + */ + @Override + @PUT + @Produces({MediaType.APPLICATION_JSON}) + public Response updateRole(@QueryParam("rolename") String roleName, RoleWrapper roleWrapper) { + String newRoleName = roleWrapper.getRoleName(); + try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager(); + if (log.isDebugEnabled()) { + log.debug("Updating the role to user store"); + } + if (newRoleName != null && !roleName.equals(newRoleName)) { + userStoreManager.updateRoleName(roleName, newRoleName); + } + if (roleWrapper.getUsers() != null) { + SetReferenceTransformer transformer = new SetReferenceTransformer<>(); + transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)), + Arrays.asList(roleWrapper.getUsers())); + final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer + .getObjectsToAdd().size()]); + final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer + .getObjectsToRemove().size()]); + userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd); + } + if (roleWrapper.getPermissions() != null) { + // Delete all authorizations for the current role before authorizing the permission tree + authorizationManager.clearRoleAuthorization(roleName); + if (roleWrapper.getPermissions().length > 0) { + for (int i = 0; i < roleWrapper.getPermissions().length; i++) { + String permission = roleWrapper.getPermissions()[i]; + authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION); + } + } + } + } catch (UserStoreException | MDMAPIException e) { + String msg = e.getMessage(); + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).build(); + } + + /** + * API is used to delete a role and authorizations + * + * @param roleName to delete + * @return response + */ + @Override + @DELETE + @Produces({MediaType.APPLICATION_JSON}) + public Response deleteRole(@QueryParam("rolename") String roleName) { + try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager(); + if (log.isDebugEnabled()) { + log.debug("Deleting the role in user store"); + } + userStoreManager.deleteRole(roleName); + // Delete all authorizations for the current role before deleting + authorizationManager.clearRoleAuthorization(roleName); + } catch (UserStoreException | MDMAPIException e) { + String msg = "Error occurred while deleting the role: " + roleName; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).build(); + } + + /** + * API is used to update users of a role + * + * @param roleName to update + * @param userList of the users + * @return response + */ + @Override + @PUT + @Path("users") + @Produces({MediaType.APPLICATION_JSON}) + public Response updateUsers(@QueryParam("rolename") String roleName, List userList) { + try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + if (log.isDebugEnabled()) { + log.debug("Updating the users of a role"); + } + SetReferenceTransformer transformer = new SetReferenceTransformer<>(); + transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(roleName)), + userList); + final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer + .getObjectsToAdd().size()]); + final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer + .getObjectsToRemove().size()]); + + userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd); + } catch (UserStoreException | MDMAPIException e) { + String msg = "Error occurred while saving the users of the role: " + roleName; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).build(); + } + + private ArrayList iteratePermissions(UIPermissionNode uiPermissionNode, ArrayList list) { + for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) { + list.add(permissionNode.getResourcePath()); + if (permissionNode.getNodeList() != null && permissionNode.getNodeList().length > 0) { + iteratePermissions(permissionNode, list); + } + } + return list; + } + + /** + * This method is used to retrieve the role count of the system. + * + * @return returns the count. + */ + @Override + @GET + @Path("count") + public Response getRoleCount() { + try { + List filteredRoles = getRolesFromUserStore(); + Integer count = filteredRoles.size(); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (MDMAPIException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build(); + } + } + + private List getRolesFromUserStore() throws MDMAPIException { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + String[] roles; + try { + if (log.isDebugEnabled()) { + log.debug("Getting the list of user roles"); + } + roles = userStoreManager.getRoleNames(); + + } catch (UserStoreException e) { + String msg = "Error occurred while retrieving the list of user roles."; + throw new MDMAPIException(msg, e); + } + // removing all internal roles and roles created for Service-providers + List filteredRoles = new ArrayList<>(); + for (String role : roles) { + if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) { + filteredRoles.add(role); + } + } + return filteredRoles; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/UserImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/UserImpl.java new file mode 100644 index 0000000000..427a654e54 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/impl/UserImpl.java @@ -0,0 +1,772 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.api.impl; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; +import org.wso2.carbon.device.mgt.jaxrs.api.util.CredentialManagementResponseBuilder; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Random; +import java.util.TreeSet; + +/** + * This class represents the JAX-RS services of User related functionality. + */ +@SuppressWarnings("NonJaxWsWebServices") +public class UserImpl implements org.wso2.carbon.device.mgt.jaxrs.api.User { + + private static final String ROLE_EVERYONE = "Internal/everyone"; + private static Log log = LogFactory.getLog(UserImpl.class); + + /** + * Method to add user to emm-user-store. + * + * @param userWrapper Wrapper object representing input json payload + * @return {Response} Status of the request wrapped inside Response object + */ + @Override + @POST + @Consumes({MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_JSON}) + public Response addUser(UserWrapper userWrapper) { + ResponsePayload responsePayload = new ResponsePayload(); + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + if (userStoreManager.isExistingUser(userWrapper.getUsername())) { + // if user already exists + if (log.isDebugEnabled()) { + log.debug("User by username: " + userWrapper.getUsername() + + " already exists. Therefore, request made to add user was refused."); + } + // returning response with bad request state + responsePayload.setStatusCode(HttpStatus.SC_CONFLICT); + responsePayload. + setMessageFromServer("User by username: " + userWrapper.getUsername() + + " already exists. Therefore, request made to add user was refused."); + return Response.status(Response.Status.CONFLICT).entity(responsePayload).build(); + } else { + String initialUserPassword = generateInitialUserPassword(); + Map defaultUserClaims = + buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(), + userWrapper.getEmailAddress()); + // calling addUser method of carbon user api + userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword, + userWrapper.getRoles(), defaultUserClaims, null); + // invite newly added user to enroll device + inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword); + // Outputting debug message upon successful addition of user + if (log.isDebugEnabled()) { + log.debug("User by username: " + userWrapper.getUsername() + " was successfully added."); + } + // returning response with success state + responsePayload.setStatusCode(HttpStatus.SC_CREATED); + responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() + + " was successfully added."); + return Response.status(Response.Status.CREATED).entity(responsePayload).build(); + } + } catch (UserStoreException | MDMAPIException e) { + String msg = "Exception in trying to add user by username: " + userWrapper.getUsername(); + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Method to get user information from emm-user-store. + * + * @param username User-name of the user + * @return {Response} Status of the request wrapped inside Response object. + */ + @Override + @GET + @Path("view") + @Produces({MediaType.APPLICATION_JSON}) + public Response getUser(@QueryParam("username") String username) { + ResponsePayload responsePayload = new ResponsePayload(); + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + if (userStoreManager.isExistingUser(username)) { + UserWrapper user = new UserWrapper(); + user.setUsername(username); + user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); + user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); + user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); + // Outputting debug message upon successful retrieval of user + if (log.isDebugEnabled()) { + log.debug("User by username: " + username + " was found."); + } + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("User information was retrieved successfully."); + responsePayload.setResponseContent(user); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } else { + // Outputting debug message upon trying to remove non-existing user + if (log.isDebugEnabled()) { + log.debug("User by username: " + username + " does not exist."); + } + // returning response with bad request state + responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); + responsePayload.setMessageFromServer( + "User by username: " + username + " does not exist."); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); + } + } catch (UserStoreException | MDMAPIException e) { + String msg = "Exception in trying to retrieve user by username: " + username; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Update user in user store + * + * @param userWrapper Wrapper object representing input json payload + * @return {Response} Status of the request wrapped inside Response object. + */ + @Override + @PUT + @Consumes({MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_JSON}) + public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) { + ResponsePayload responsePayload = new ResponsePayload(); + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + if (userStoreManager.isExistingUser(userWrapper.getUsername())) { + Map defaultUserClaims = + buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(), + userWrapper.getEmailAddress()); + if (StringUtils.isNotEmpty(userWrapper.getPassword())) { + // Decoding Base64 encoded password + byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword()); + userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(), + new String(decodedBytes, "UTF-8")); + log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed"); + } + List listofFilteredRoles = getFilteredRoles(userStoreManager, userWrapper.getUsername()); + final String[] existingRoles = listofFilteredRoles.toArray(new String[listofFilteredRoles.size()]); + + /* + Use the Set theory to find the roles to delete and roles to add + The difference of roles in existingRolesSet and newRolesSet needed to be deleted + new roles to add = newRolesSet - The intersection of roles in existingRolesSet and newRolesSet + */ + final TreeSet existingRolesSet = new TreeSet<>(); + Collections.addAll(existingRolesSet, existingRoles); + final TreeSet newRolesSet = new TreeSet<>(); + Collections.addAll(newRolesSet, userWrapper.getRoles()); + existingRolesSet.removeAll(newRolesSet); + // Now we have the roles to delete + String[] rolesToDelete = existingRolesSet.toArray(new String[existingRolesSet.size()]); + List roles = new ArrayList<>(Arrays.asList(rolesToDelete)); + roles.remove(ROLE_EVERYONE); + rolesToDelete = new String[0]; + // Clearing and re-initializing the set + existingRolesSet.clear(); + Collections.addAll(existingRolesSet, existingRoles); + newRolesSet.removeAll(existingRolesSet); + // Now we have the roles to add + String[] rolesToAdd = newRolesSet.toArray(new String[newRolesSet.size()]); + userStoreManager.updateRoleListOfUser(userWrapper.getUsername(), rolesToDelete, rolesToAdd); + userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null); + // Outputting debug message upon successful addition of user + if (log.isDebugEnabled()) { + log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated."); + } + // returning response with success state + responsePayload.setStatusCode(HttpStatus.SC_CREATED); + responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() + + " was successfully updated."); + return Response.status(Response.Status.CREATED).entity(responsePayload).build(); + } else { + if (log.isDebugEnabled()) { + log.debug("User by username: " + userWrapper.getUsername() + + " doesn't exists. Therefore, request made to update user was refused."); + } + // returning response with bad request state + responsePayload.setStatusCode(HttpStatus.SC_CONFLICT); + responsePayload. + setMessageFromServer("User by username: " + userWrapper.getUsername() + + " doesn't exists. Therefore, request made to update user was refused."); + return Response.status(Response.Status.CONFLICT).entity(responsePayload).build(); + } + } catch (UserStoreException | UnsupportedEncodingException | MDMAPIException e) { + String msg = "Exception in trying to update user by username: " + userWrapper.getUsername(); + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Private method to be used by addUser() to + * generate an initial user password for a user. + * This will be the password used by a user for his initial login to the system. + * + * @return {string} Initial User Password + */ + private String generateInitialUserPassword() { + int passwordLength = 6; + //defining the pool of characters to be used for initial password generation + String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz"; + String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + String numericCharset = "0123456789"; + Random randomGenerator = new Random(); + String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset; + int totalCharsetLength = totalCharset.length(); + StringBuilder initialUserPassword = new StringBuilder(); + for (int i = 0; i < passwordLength; i++) { + initialUserPassword + .append(totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength))); + } + if (log.isDebugEnabled()) { + log.debug("Initial user password is created for new user: " + initialUserPassword); + } + return initialUserPassword.toString(); + } + + /** + * Method to build default user claims. + * + * @param firstname First name of the user + * @param lastname Last name of the user + * @param emailAddress Email address of the user + * @return {Object} Default user claims to be provided + */ + private Map buildDefaultUserClaims(String firstname, String lastname, String emailAddress) { + Map defaultUserClaims = new HashMap<>(); + defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstname); + defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastname); + defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress); + if (log.isDebugEnabled()) { + log.debug("Default claim map is created for new user: " + defaultUserClaims.toString()); + } + return defaultUserClaims; + } + + /** + * Method to remove user from emm-user-store. + * + * @param username Username of the user + * @return {Response} Status of the request wrapped inside Response object. + */ + @Override + @DELETE + @Produces({MediaType.APPLICATION_JSON}) + public Response removeUser(@QueryParam("username") String username) { + ResponsePayload responsePayload = new ResponsePayload(); + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + if (userStoreManager.isExistingUser(username)) { + // if user already exists, trying to remove user + userStoreManager.deleteUser(username); + // Outputting debug message upon successful removal of user + if (log.isDebugEnabled()) { + log.debug("User by username: " + username + " was successfully removed."); + } + // returning response with success state + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer( + "User by username: " + username + " was successfully removed."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } else { + // Outputting debug message upon trying to remove non-existing user + if (log.isDebugEnabled()) { + log.debug("User by username: " + username + " does not exist for removal."); + } + // returning response with bad request state + responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); + responsePayload.setMessageFromServer( + "User by username: " + username + " does not exist for removal."); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); + } + } catch (UserStoreException | MDMAPIException e) { + String msg = "Exception in trying to remove user by username: " + username; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * get all the roles except for the internal/xxx and application/xxx + * + * @param userStoreManager User Store Manager associated with the currently logged in user + * @param username Username of the currently logged in user + * @return the list of filtered roles + */ + private List getFilteredRoles(UserStoreManager userStoreManager, String username) { + String[] roleListOfUser = new String[0]; + try { + roleListOfUser = userStoreManager.getRoleListOfUser(username); + } catch (UserStoreException e) { + e.printStackTrace(); + } + List filteredRoles = new ArrayList<>(); + for (String role : roleListOfUser) { + if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) { + filteredRoles.add(role); + } + } + return filteredRoles; + } + + /** + * Get user's roles by username + * + * @param username Username of the user + * @return {Response} Status of the request wrapped inside Response object. + */ + @Override + @GET + @Path("roles") + @Produces({MediaType.APPLICATION_JSON}) + public Response getRolesOfUser(@QueryParam("username") String username) { + ResponsePayload responsePayload = new ResponsePayload(); + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + if (userStoreManager.isExistingUser(username)) { + responsePayload.setResponseContent(Collections.singletonList(getFilteredRoles(userStoreManager, username))); + // Outputting debug message upon successful removal of user + if (log.isDebugEnabled()) { + log.debug("User by username: " + username + " was successfully removed."); + } + // returning response with success state + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer( + "User roles obtained for user " + username); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } else { + // Outputting debug message upon trying to remove non-existing user + if (log.isDebugEnabled()) { + log.debug("User by username: " + username + " does not exist for role retrieval."); + } + // returning response with bad request state + responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); + responsePayload.setMessageFromServer( + "User by username: " + username + " does not exist for role retrieval."); + return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build(); + } + } catch (UserStoreException | MDMAPIException e) { + String msg = "Exception in trying to retrieve roles for user by username: " + username; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Get the list of all users with all user-related info. + * + * @return A list of users + */ + @Override + @GET + @Produces({MediaType.APPLICATION_JSON}) + public Response getAllUsers() { + if (log.isDebugEnabled()) { + log.debug("Getting the list of users with all user-related information"); + } + List userList; + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + String[] users = userStoreManager.listUsers("*", -1); + userList = new ArrayList<>(users.length); + UserWrapper user; + for (String username : users) { + user = new UserWrapper(); + user.setUsername(username); + user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); + user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); + user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); + userList.add(user); + } + } catch (UserStoreException | MDMAPIException e) { + String msg = "Error occurred while retrieving the list of users"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + int count; + count = userList.size(); + responsePayload.setMessageFromServer("All users were successfully retrieved. " + + "Obtained user count: " + count); + responsePayload.setResponseContent(userList); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + /** + * Get the list of all users with all user-related info. + * + * @return A list of users + */ + @Override + @GET + @Path("{filter}") + @Produces({MediaType.APPLICATION_JSON}) + public Response getMatchingUsers(@PathParam("filter") String filter) { + if (log.isDebugEnabled()) { + log.debug("Getting the list of users with all user-related information using the filter : " + filter); + } + List userList; + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + String[] users = userStoreManager.listUsers(filter + "*", -1); + userList = new ArrayList<>(users.length); + UserWrapper user; + for (String username : users) { + user = new UserWrapper(); + user.setUsername(username); + user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); + user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); + user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); + userList.add(user); + } + } catch (UserStoreException | MDMAPIException e) { + String msg = "Error occurred while retrieving the list of users using the filter : " + filter; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + int count; + count = userList.size(); + responsePayload.setMessageFromServer("All users were successfully retrieved. " + + "Obtained user count: " + count); + responsePayload.setResponseContent(userList); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + /** + * Get the list of user names in the system. + * + * @return A list of user names. + */ + @Override + @GET + @Path("view-users") + public Response getAllUsersByUsername(@QueryParam("username") String userName) { + if (log.isDebugEnabled()) { + log.debug("Getting the list of users by name"); + } + List userList; + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + String[] users = userStoreManager.listUsers("*" + userName + "*", -1); + userList = new ArrayList<>(users.length); + UserWrapper user; + for (String username : users) { + user = new UserWrapper(); + user.setUsername(username); + user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); + user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); + user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); + userList.add(user); + } + } catch (UserStoreException | MDMAPIException e) { + String msg = "Error occurred while retrieving the list of users"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + int count; + count = userList.size(); + responsePayload.setMessageFromServer("All users by username were successfully retrieved. " + + "Obtained user count: " + count); + responsePayload.setResponseContent(userList); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + /** + * Get the list of user names in the system. + * + * @return A list of user names. + */ + @Override + @GET + @Path("users-by-username") + public Response getAllUserNamesByUsername(@QueryParam("username") String userName) { + if (log.isDebugEnabled()) { + log.debug("Getting the list of users by name"); + } + List userList; + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + String[] users = userStoreManager.listUsers("*" + userName + "*", -1); + userList = new ArrayList<>(users.length); + Collections.addAll(userList, users); + } catch (UserStoreException | MDMAPIException e) { + String msg = "Error occurred while retrieving the list of users"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + int count; + count = userList.size(); + responsePayload.setMessageFromServer("All users by username were successfully retrieved. " + + "Obtained user count: " + count); + responsePayload.setResponseContent(userList); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + /** + * Gets a claim-value from user-store. + * + * @param username Username of the user + * @param claimUri required ClaimUri + * @return claim value + */ + private String getClaimValue(String username, String claimUri) throws MDMAPIException { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + try { + return userStoreManager.getUserClaimValue(username, claimUri, null); + } catch (UserStoreException e) { + throw new MDMAPIException("Error occurred while retrieving value assigned to the claim '" + + claimUri + "'", e); + } + } + + /** + * Method used to send an invitation email to a new user to enroll a device. + * + * @param username Username of the user + */ + private void inviteNewlyAddedUserToEnrollDevice(String username, String password) throws MDMAPIException { + if (log.isDebugEnabled()) { + log.debug("Sending invitation mail to user by username: " + username); + } + String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) { + tenantDomain = ""; + } + if (!username.contains("/")) { + username = "/" + username; + } + String[] usernameBits = username.split("/"); + DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); + + Properties props = new Properties(); + props.setProperty("username", usernameBits[1]); + props.setProperty("domain-name", tenantDomain); + props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); + props.setProperty("password", password); + + String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS); + + EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); + try { + deviceManagementProviderService.sendRegistrationEmail(metaInfo); + } catch (DeviceManagementException e) { + String msg = "Error occurred while sending registration email to user '" + username + "'"; + log.error(msg, e); + throw new MDMAPIException(msg, e); + } + } + + /** + * Method used to send an invitation email to a existing user to enroll a device. + * + * @param usernames Username list of the users to be invited + */ + @Override + @POST + @Path("email-invitation") + @Produces({MediaType.APPLICATION_JSON}) + public Response inviteExistingUsersToEnrollDevice(List usernames) { + if (log.isDebugEnabled()) { + log.debug("Sending enrollment invitation mail to existing user."); + } + DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); + try { + for (String username : usernames) { + String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS); + + Properties props = new Properties(); + props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); + props.setProperty("username", username); + + EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); + deviceManagementProviderService.sendEnrolmentInvitation(metaInfo); + } + } catch (DeviceManagementException | MDMAPIException e) { + String msg = "Error occurred while inviting user to enrol their device"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + ResponsePayload responsePayload = new ResponsePayload(); + responsePayload.setStatusCode(HttpStatus.SC_OK); + responsePayload.setMessageFromServer("Email invitation was successfully sent to user."); + return Response.status(Response.Status.OK).entity(responsePayload).build(); + } + + /** + * Get a list of devices based on the username. + * + * @param username Username of the device owner + * @return A list of devices + */ + @Override + @GET + @Produces({MediaType.APPLICATION_JSON}) + @Path("devices") + public Response getAllDeviceOfUser(@QueryParam("username") String username, + @QueryParam("start") int startIdx, @QueryParam("length") int length) { + DeviceManagementProviderService dmService; + try { + dmService = DeviceMgtAPIUtils.getDeviceManagementService(); + if (length > 0) { + PaginationRequest request = new PaginationRequest(startIdx, length); + request.setOwner(username); + return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(request)).build(); + } + return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(username)).build(); + } catch (DeviceManagementException e) { + String msg = "Device management error"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * This method is used to retrieve the user count of the system. + * + * @return returns the count. + * @ + */ + @Override + @GET + @Path("count") + public Response getUserCount() { + try { + String[] users = DeviceMgtAPIUtils.getUserStoreManager().listUsers("*", -1); + Integer count = 0; + if (users != null) { + count = users.length; + } + return Response.status(Response.Status.OK).entity(count).build(); + } catch (UserStoreException | MDMAPIException e) { + String msg = + "Error occurred while retrieving the list of users that exist within the current tenant"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * API is used to update roles of a user + * + * @param username + * @param userList + * @return + * @ + */ + @Override + @PUT + @Path("{roleName}/users") + @Produces({MediaType.APPLICATION_JSON}) + public Response updateRoles(@PathParam("roleName") String username, List userList) { + try { + final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + if (log.isDebugEnabled()) { + log.debug("Updating the roles of a user"); + } + SetReferenceTransformer transformer = new SetReferenceTransformer<>(); + transformer.transform(Arrays.asList(userStoreManager.getRoleListOfUser(username)), + userList); + final String[] rolesToAdd = transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]); + final String[] rolesToDelete = transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]); + + userStoreManager.updateRoleListOfUser(username, rolesToDelete, rolesToAdd); + } catch (UserStoreException | MDMAPIException e) { + String msg = "Error occurred while saving the roles for user: " + username; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).build(); + } + + /** + * Method to change the user password. + * + * @param credentials Wrapper object representing user credentials. + * @return {Response} Status of the request wrapped inside Response object. + * @ + */ + @Override + @POST + @Path("change-password") + @Consumes({MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_JSON}) + public Response resetPassword(UserCredentialWrapper credentials) { + return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials); + } + + /** + * Method to change the user password. + * + * @param credentials Wrapper object representing user credentials. + * @return {Response} Status of the request wrapped inside Response object. + * @ + */ + @Override + @POST + @Path("reset-password") + @Consumes({MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_JSON}) + public Response resetPasswordByAdmin(UserCredentialWrapper credentials) { + return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials); + } + +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/CredentialManagementResponseBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/CredentialManagementResponseBuilder.java index d9097edb93..16d0dc7823 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/CredentialManagementResponseBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/CredentialManagementResponseBuilder.java @@ -52,7 +52,7 @@ public class CredentialManagementResponseBuilder { userStoreManager.updateCredential(credentials.getUsername(), new String( decodedNewPassword, "UTF-8"), new String(decodedOldPassword, "UTF-8")); responsePayload.setStatusCode(HttpStatus.SC_CREATED); - responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() + + responsePayload.setMessageFromServer("UserImpl password by username: " + credentials.getUsername() + " was successfully changed."); return Response.status(Response.Status.CREATED).entity(responsePayload).build(); } catch (UserStoreException e) { @@ -84,7 +84,7 @@ public class CredentialManagementResponseBuilder { userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String( decodedNewPassword, "UTF-8")); responsePayload.setStatusCode(HttpStatus.SC_CREATED); - responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() + + responsePayload.setMessageFromServer("UserImpl password by username: " + credentials.getUsername() + " was successfully changed."); return Response.status(Response.Status.CREATED).entity(responsePayload).build(); } catch (UserStoreException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/DeviceMgtAPIUtils.java index be97e21bd5..f1cdbe6e8d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/DeviceMgtAPIUtils.java @@ -87,7 +87,7 @@ public class DeviceMgtAPIUtils { DeviceManagementProviderService deviceManagementProviderService = (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null); if (deviceManagementProviderService == null) { - String msg = "Device Management provider service has not initialized."; + String msg = "DeviceImpl Management provider service has not initialized."; log.error(msg); throw new IllegalStateException(msg); } @@ -99,7 +99,7 @@ public class DeviceMgtAPIUtils { GroupManagementProviderService groupManagementProviderService = (GroupManagementProviderService) ctx.getOSGiService(GroupManagementProviderService.class, null); if (groupManagementProviderService == null) { - String msg = "Group Management service has not initialized."; + String msg = "GroupImpl Management service has not initialized."; log.error(msg); throw new IllegalStateException(msg); } @@ -213,7 +213,7 @@ public class DeviceMgtAPIUtils { ApplicationManagementProviderService applicationManagementProviderService = (ApplicationManagementProviderService) ctx.getOSGiService(ApplicationManagementProviderService.class, null); if (applicationManagementProviderService == null) { - String msg = "Application management service has not initialized."; + String msg = "AuthenticationImpl management service has not initialized."; log.error(msg); throw new IllegalStateException(msg); } @@ -226,7 +226,7 @@ public class DeviceMgtAPIUtils { policyManagementService = (PolicyManagerService) ctx.getOSGiService(PolicyManagerService.class, null); if (policyManagementService == null) { - String msg = "Policy Management service not initialized."; + String msg = "PolicyImpl Management service not initialized."; log.error(msg); throw new IllegalStateException(msg); } @@ -274,7 +274,7 @@ public class DeviceMgtAPIUtils { ctx.getOSGiService(CertificateManagementService.class, null); if (certificateManagementService == null) { - String msg = "Certificate Management service not initialized."; + String msg = "CertificateImpl Management service not initialized."; log.error(msg); throw new IllegalStateException(msg); } @@ -299,7 +299,7 @@ public class DeviceMgtAPIUtils { DeviceInformationManager deviceInformationManager = (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); if (deviceInformationManager == null) { - String msg = "Device information Manager service has not initialized."; + String msg = "DeviceImpl information Manager service has not initialized."; log.error(msg); throw new IllegalStateException(msg); } @@ -313,7 +313,7 @@ public class DeviceMgtAPIUtils { SearchManagerService searchManagerService = (SearchManagerService) ctx.getOSGiService(SearchManagerService.class, null); if (searchManagerService == null) { - String msg = "Device search manager service has not initialized."; + String msg = "DeviceImpl search manager service has not initialized."; log.error(msg); throw new IllegalStateException(msg); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAndroidOperationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAndroidOperationUtil.java index 9dcbec0a3c..643cf3a9bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAndroidOperationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAndroidOperationUtil.java @@ -33,7 +33,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.android.WebApplication; public class MDMAndroidOperationUtil { /** - * This method is used to create Install Application operation. + * This method is used to create Install Authentication operation. * * @param application MobileApp application * @return operation @@ -76,7 +76,7 @@ public class MDMAndroidOperationUtil { } /** - * This method is used to create Uninstall Application operation. + * This method is used to create Uninstall Authentication operation. * @param application MobileApp application * @return operation * @throws MDMAPIException diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMIOSOperationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMIOSOperationUtil.java index 7014174801..0d9f031162 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMIOSOperationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMIOSOperationUtil.java @@ -35,7 +35,7 @@ import java.util.Properties; public class MDMIOSOperationUtil { /** - * This method is used to create Install Application operation. + * This method is used to create Install Authentication operation. * * @param application MobileApp application * @return operation diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ApplicationWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ApplicationWrapper.java index 4631e4e944..1040045dde 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ApplicationWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ApplicationWrapper.java @@ -18,45 +18,57 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + import java.util.List; + +@ApiModel(value = "ApplicationWrapper", description = "Application details together with user, " + + "role or devices the application is associated with.") public class ApplicationWrapper { - private List userNameList; - private List roleNameList; - private List deviceIdentifiers; - private MobileApp application; + @ApiModelProperty(name = "userNameList", value = "List of user names.", required = true) + private List userNameList; + @ApiModelProperty(name = "roleNameList", value = "List of role names.", required = true) + private List roleNameList; + @ApiModelProperty(name = "deviceIdentifiers", value = "List of device identifiers.", required = true, + dataType = "List[org.wso2.carbon.device.mgt.common.DeviceIdentifier]") + private List deviceIdentifiers; + @ApiModelProperty(name = "application", value = "Details of the mobile application.", required = true) + private MobileApp application; - public MobileApp getApplication() { - return application; - } + public MobileApp getApplication() { + return application; + } - public void setApplication(MobileApp application) { - this.application = application; - } - public List getUserNameList() { - return userNameList; - } + public void setApplication(MobileApp application) { + this.application = application; + } - public void setUserNameList(List userNameList) { - this.userNameList = userNameList; - } + public List getUserNameList() { + return userNameList; + } - public List getRoleNameList() { - return roleNameList; - } + public void setUserNameList(List userNameList) { + this.userNameList = userNameList; + } - public void setRoleNameList(List roleNameList) { - this.roleNameList = roleNameList; - } + public List getRoleNameList() { + return roleNameList; + } - public List getDeviceIdentifiers() { - return deviceIdentifiers; - } + public void setRoleNameList(List roleNameList) { + this.roleNameList = roleNameList; + } - public void setDeviceIdentifiers(List deviceIdentifiers) { - this.deviceIdentifiers = deviceIdentifiers; - } + public List getDeviceIdentifiers() { + return deviceIdentifiers; + } + + public void setDeviceIdentifiers(List deviceIdentifiers) { + this.deviceIdentifiers = deviceIdentifiers; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/EnrollmentCertificate.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/EnrollmentCertificate.java index 40d94da4ed..d6a79db6f9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/EnrollmentCertificate.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/EnrollmentCertificate.java @@ -18,9 +18,19 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "EnrollmentCertificate", description = "Details of certificates used in enrollment.") public class EnrollmentCertificate { + + @ApiModelProperty(name = "serial", value = "The unique ID used to identify a certificate. This is the devices " + + "serial number in case of mutual SSL is used for enrollment.", + required = true ) String serial; + @ApiModelProperty(name = "pem", value = "Case 64 encode .pem file content.", required = true ) String pem; + @ApiModelProperty(name = "tenantId", value = "The ID of the tenant who adds the certificate.", required = true ) int tenantId; public int getTenantId() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileApp.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileApp.java index 220b1572c7..fe7f4e0268 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileApp.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileApp.java @@ -18,24 +18,51 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.util.Properties; /** - * This class represents the generic mobile Application information + * This class represents the generic mobile AuthenticationImpl information * which is used by AppM. */ +@ApiModel(value = "MobileApp", description = "Details of a mobile application.") public class MobileApp { + @ApiModelProperty(name = "id", value = "Id of the app used internally.", required = true) private String id; + @ApiModelProperty(name = "name", value = "The name of the application.", required = true) private String name; + @ApiModelProperty(name = "type", value = "The type of the application. The following types of applications are " + + "supported: enterprise, public and webapp..", required = true) private MobileAppTypes type; + @ApiModelProperty(name = "platform", value = "Platform the app can be installed on .", required = true) private String platform; + @ApiModelProperty(name = "version", value = "Version of the application.", required = true) private String version; + @ApiModelProperty(name = "identifier", value = "The package name of the application.", required = true) private String identifier; + @ApiModelProperty(name = "iconImage", value = "Link to the icon of the app.", required = true) private String iconImage; + @ApiModelProperty(name = "packageName", value = "Define the exact name of the application package. You can use one " + + "of the following methods to get the package name.\n" + + "Go to the respective application in the play store and copy the" + + " ID or package name from the URL.\n" + + "Example: The play store application URL for the Viber app is " + + "https://play.google.com/store/apps/details?id=com.viber.voip&hl=en." + + " Therefore, the package name or " + + "the application ID is: id=com.viber.voip \n" + + "Download the System Info for Android to your device from the" + + " play store. \n" + + "Once the application is successfully installed go to the Tasks " + + "tab and you will see the package name under the respective " + + "application..", required = true) private String packageName; + @ApiModelProperty(name = "appIdentifier", value = "The package name of the application.", required = true) private String appIdentifier; private String location; + @ApiModelProperty(name = "properties", value = "List of meta data.", required = true) private Properties properties; public MobileAppTypes getType() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java index c05fa535a5..b8558856fe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java @@ -18,21 +18,52 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.Device; import java.util.List; +@ApiModel(value = "PolicyWrapper", description = "This class carries all information related to Policy " + + "Wrappers") public class PolicyWrapper { + @ApiModelProperty(name = "id", value = "The policy ID", required = true) private int id; + @ApiModelProperty(name = "profile", value = "Contains the details of the profile that is included in the" + + " policy", required = true) private Profile profile; + @ApiModelProperty(name = "policyName", value = "The name of the policy", required = true) private String policyName; + @ApiModelProperty(name = "description", value = "Gives a description on the policy", required = true) private String description; + @ApiModelProperty(name = "compliance", value = "Provides the non-compliance rules. WSO2 EMM provides the" + + " following non-compliance rules:\n" + + "Enforce - Forcefully enforce the policies on the devices\n" + + "Warning - If the device does not adhere to the given policies a warning message will be sent\n" + + "Monitor - If the device does not adhere to the given policies the server is notified of the " + + "violation unknown to the user and the administrator can take the necessary actions with regard" + + " to the reported", required = true) private String compliance; + @ApiModelProperty(name = "roles", value = "The roles to whom the policy is applied on", required = true) private List roles; + @ApiModelProperty(name = "ownershipType", value = "The policy ownership type. It can be any of the " + + "following values:\n" + + "ANY - The policy will be applied on the BYOD and COPE device types\n" + + "BYOD (Bring Your Own Device) - The policy will only be applied on the BYOD device type\n" + + "COPE (Corporate-Owned, Personally-Enabled) - The policy will only be applied on the COPE " + + "device type", required = true) private String ownershipType; + @ApiModelProperty(name = "devices", value = "Lists out the devices the policy is enforced on", + required = true) private List devices; + @ApiModelProperty(name = "users", value = "Lists out the users on whose devices the policy is enforced", + required = true) private List users; + @ApiModelProperty(name = "tenantId", value = "The ID of the tenant that created the policy", + required = true) private int tenantId; + @ApiModelProperty(name = "profileId", value = "The ID of each profile that is in the selected policy", + required = true) private int profileId; public int getId() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PriorityUpdatedPolicyWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PriorityUpdatedPolicyWrapper.java index 20f5248f85..56a4764d0b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PriorityUpdatedPolicyWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PriorityUpdatedPolicyWrapper.java @@ -18,9 +18,17 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "PriorityUpdatedPolicyWrapper", description = "This class carries all information related " + + "to Priority Updated Policy Wrapper ") public class PriorityUpdatedPolicyWrapper { + @ApiModelProperty(name = "id", value = "Define the ID of the policy", required = true) private int id; + @ApiModelProperty(name = "priority", value = "Define the priority of the order, where 1 indicates the " + + "highest priority", required = true) private int priority; public int getId() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java index a54b53b2c2..17f8b905bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java @@ -18,23 +18,36 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; - - +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.core.dto.DeviceType; + import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.sql.Timestamp; import java.util.List; @XmlRootElement +@ApiModel(value = "Profile", description = "This class carries all information related to policy profiles") public class Profile { + @ApiModelProperty(name = "profileId", value = "The ID of each profile that is in the selected policy", + required = true) private int profileId; + @ApiModelProperty(name = "profileName", value = "The name of the profile", required = true) private String profileName; + @ApiModelProperty(name = "tenantId", value = "The ID of the tenant that added the policy", required = true) private int tenantId; + @ApiModelProperty(name = "deviceType", value = "Contains the device type details the policy was created " + + "for", required = true) private DeviceType deviceType; + @ApiModelProperty(name = "createdDate", value = "The date the policy was created", required = true) private Timestamp createdDate; + @ApiModelProperty(name = "updatedDate", value = "The date the changes made to the policy was published to" + + " the devices registered with the EMM", required = true) private Timestamp updatedDate; + @ApiModelProperty(name = "profileFeaturesList", value = "Contains the features specific to each profile " + + "in the policy", required = true) private List profileFeaturesList; // Features included in the policies. public DeviceType getDeviceType() { @@ -53,11 +66,11 @@ public class Profile { this.tenantId = tenantId; } -/* public List getFeaturesList() { +/* public List getFeaturesList() { return featuresList; } - public void setFeaturesList(List featuresList) { + public void setFeaturesList(List featuresList) { this.featuresList = featuresList; }*/ @XmlElement @@ -104,4 +117,5 @@ public class Profile { public void setProfileFeaturesList(List profileFeaturesList) { this.profileFeaturesList = profileFeaturesList; } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ProfileFeature.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ProfileFeature.java index d52f30281b..81d8032799 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ProfileFeature.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ProfileFeature.java @@ -19,15 +19,30 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import com.google.gson.Gson; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; +@ApiModel(value = "ProfileFeature", description = "This class carries all information related to profile " + + "features") public class ProfileFeature implements Serializable { + @ApiModelProperty(name = "id", value = "Define the ID", required = true) private int id; + @ApiModelProperty(name = "featureCode", value = "Provide the code that defines the policy you wish to add", + required = true) private String featureCode; + @ApiModelProperty(name = "profileId", value = "Define the ID of the profile", required = true) private int profileId; + @ApiModelProperty(name = "deviceTypeId", value = "The ID used to define the type of the device platform", + required = true) private int deviceTypeId; + @ApiModelProperty(name = "content", value = "The list of parameters that define the policy", + required = true) private Object content; + @ApiModelProperty(name = "payLoad", value = "The payload which is submitted to each feature", + required = true) private String payLoad; public int getId() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java index b8d633f3f6..c0856021e2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java @@ -18,43 +18,59 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.user.mgt.common.UIPermissionNode; +@ApiModel(value = "RoleWrapper", description = "Role details including permission and the users in the roles are " + + "wrapped here.") public class RoleWrapper { - private String roleName; - private String[] permissions; - private String[] users; - private UIPermissionNode permissionList; - public String getRoleName() { - return roleName; - } + @ApiModelProperty(name = "roleName", value = "The name of the role.", required = true) + private String roleName; + @ApiModelProperty(name = "permissions", value = "Lists out all the permissions associated with roles.", + required = true, dataType = "List[java.lang.String]") + private String[] permissions; + @ApiModelProperty(name = "users", value = "The list of users assigned to the selected role.", + required = true, dataType = "List[java.lang.String]") + private String[] users; + @ApiModelProperty(name = "permissionList", value = "This contain the following, " + + "\n resourcePath\tThe path related to the API.\n " + + "displayName\tThe name of the permission that is shown " + + "in the UI.\n" + + "nodeList\tLists out the nested permissions.", + required = true) + private UIPermissionNode permissionList; - public void setRoleName(String roleName) { - this.roleName = roleName; - } + public String getRoleName() { + return roleName; + } - public String[] getPermissions() { - return permissions; - } + public void setRoleName(String roleName) { + this.roleName = roleName; + } - public void setPermissions(String[] permissions) { - this.permissions = permissions; - } + public String[] getPermissions() { + return permissions; + } - public String[] getUsers() { - return users; - } + public void setPermissions(String[] permissions) { + this.permissions = permissions; + } - public void setUsers(String[] users) { - this.users = users; - } + public String[] getUsers() { + return users; + } - public UIPermissionNode getPermissionList() { - return permissionList; - } + public void setUsers(String[] users) { + this.users = users; + } - public void setPermissionList(UIPermissionNode permissionList) { - this.permissionList = permissionList; - } + public UIPermissionNode getPermissionList() { + return permissionList; + } + + public void setPermissionList(UIPermissionNode permissionList) { + this.permissionList = permissionList; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java index d0c201b8d6..e5674b9de7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java @@ -18,13 +18,20 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "UserCredentialWrapper", description = "User credentials are included in this class.") public class UserCredentialWrapper { + @ApiModelProperty(name = "username", value = "Username of the user.", required = true ) private String username; /* Base64 encoded password */ + @ApiModelProperty(name = "oldPassword", value = "Old password of the user.", required = true ) private String oldPassword; + @ApiModelProperty(name = "newPassword", value = "New password of the user.", required = true ) private String newPassword; public String getNewPassword() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserWrapper.java index c03a762ee3..8009ae233e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserWrapper.java @@ -18,16 +18,26 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "UserWrapper", description = "User details and the roles of the user.") public class UserWrapper { private String username; /* Base64 encoded password */ + + @ApiModelProperty(name = "password", value = "Base64 encoded password.", required = true ) private String password; + @ApiModelProperty(name = "firstname", value = "The first name of the user.", required = true ) private String firstname; + @ApiModelProperty(name = "lastname", value = "The last name of the user.", required = true ) private String lastname; + @ApiModelProperty(name = "emailAddress", value = "The email address of the user.", required = true ) private String emailAddress; + @ApiModelProperty(name = "roles", value = "List of roles.", required = true ) private String[] roles; public String getUsername() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/AppStoreApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/AppStoreApplication.java index bc261e91a5..6d89673b85 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/AppStoreApplication.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/AppStoreApplication.java @@ -24,7 +24,7 @@ import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; import java.io.Serializable; /** - * This class represents the Appstore Application information. + * This class represents the Appstore AuthenticationImpl information. */ public class AppStoreApplication implements Serializable { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/EnterpriseApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/EnterpriseApplication.java index 22d0544602..17592bc112 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/EnterpriseApplication.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/EnterpriseApplication.java @@ -24,7 +24,7 @@ import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; import java.io.Serializable; /** - * This class represents the Enterprise Application information. + * This class represents the Enterprise AuthenticationImpl information. */ public class EnterpriseApplication implements Serializable { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/WebApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/WebApplication.java index 74a0665c3d..e646d5bba0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/WebApplication.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/WebApplication.java @@ -24,7 +24,7 @@ import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; import java.io.Serializable; /** - * This class represents the Web Application information. + * This class represents the Web AuthenticationImpl information. */ public class WebApplication implements Serializable { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java index 533d6964ab..f7bd1a47e6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java @@ -19,7 +19,7 @@ package org.wso2.carbon.device.mgt.jaxrs.util; /** - * Holds the constants used by Device Management Admin web application. + * Holds the constants used by DeviceImpl Management Admin web application. */ public class Constants { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index 05993e75ab..05d9a6d8b4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -24,162 +24,60 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml index ab8d04cbe8..97f0970968 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml @@ -25,6 +25,16 @@ org.apache.cxf.transport.servlet.CXFServlet + + + + + + + + swagger.security.filter + ApiAuthorizationFilterImpl + 1 @@ -41,7 +51,7 @@ doAuthentication - true + false - + device-mgt org.wso2.carbon.devicemgt @@ -47,10 +48,22 @@ org.wso2.carbon.device.mgt.common.* + + javax.xml.bind.annotation, + io.swagger.annotations.*;resolution:=optional + + + + io.swagger + swagger-annotations + provided + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java index feb5f987a2..51c206f6cc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java @@ -17,23 +17,43 @@ */ package org.wso2.carbon.device.mgt.common; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; import java.util.List; -public class Device implements Serializable{ +@ApiModel(value = "Device", description = "This class carries all information related to a managed device.") +public class Device implements Serializable { - private static final long serialVersionUID = 1998101711L; + private static final long serialVersionUID = 1998101711L; - private int id; + @ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.", + required = true) + private int id; + @ApiModelProperty(name = "name", value = "The device name that can be set on the device by the device user.", + required = true) private String name; - private String type; - private String description; - private String deviceIdentifier; + @ApiModelProperty(name = "type", value = "The OS type of the device.", required = true) + private String type; + @ApiModelProperty(name = "description", value = "Additional information on the device.", required = true) + private String description; + @ApiModelProperty(name = "deviceIdentifier", value = "This is a 64-bit number (as a hex string) that is randomly" + + " generated when the user first sets up the device and should" + + " remain constant for the lifetime of the user's device." + + " The value may change if a factory reset is performed on " + + "the device.", + required = true) + private String deviceIdentifier; + @ApiModelProperty(name = "enrolmentInfo", value = "This defines the device registration related information. " + + "It is mandatory to define this information.", required = true) private EnrolmentInfo enrolmentInfo; + @ApiModelProperty(name = "features", value = "List of features.", required = true) private List features; private List properties; - public Device() {} + public Device() { + } public Device(String name, String type, String description, String deviceId, EnrolmentInfo enrolmentInfo, List features, List properties) { @@ -46,13 +66,13 @@ public class Device implements Serializable{ this.properties = properties; } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } public String getName() { return name; @@ -70,21 +90,21 @@ public class Device implements Serializable{ this.type = type; } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public String getDeviceIdentifier() { - return deviceIdentifier; - } + public String getDeviceIdentifier() { + return deviceIdentifier; + } - public void setDeviceIdentifier(String deviceIdentifier) { - this.deviceIdentifier = deviceIdentifier; - } + public void setDeviceIdentifier(String deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } public EnrolmentInfo getEnrolmentInfo() { return enrolmentInfo; @@ -94,43 +114,43 @@ public class Device implements Serializable{ this.enrolmentInfo = enrolmentInfo; } - public List getFeatures() { - return features; - } + public List getFeatures() { + return features; + } - public void setFeatures(List features) { - this.features = features; - } + public void setFeatures(List features) { + this.features = features; + } - public List getProperties() { - return properties; - } + public List getProperties() { + return properties; + } - public void setProperties(List properties) { - this.properties = properties; - } + public void setProperties(List properties) { + this.properties = properties; + } - public static class Property { + public static class Property { - private String name; - private String value; + private String name; + private String value; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } - } + public void setValue(String value) { + this.value = value; + } + } @Override public String toString() { @@ -147,22 +167,22 @@ public class Device implements Serializable{ "]"; } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof Device)) - return false; + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof Device)) + return false; - Device device = (Device) o; + Device device = (Device) o; - return getDeviceIdentifier().equals(device.getDeviceIdentifier()); + return getDeviceIdentifier().equals(device.getDeviceIdentifier()); - } + } - @Override - public int hashCode() { - return getDeviceIdentifier().hashCode(); - } + @Override + public int hashCode() { + return getDeviceIdentifier().hashCode(); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceIdentifier.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceIdentifier.java index 3c5e240502..a88bcb465a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceIdentifier.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceIdentifier.java @@ -17,11 +17,19 @@ */ package org.wso2.carbon.device.mgt.common; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; + +@ApiModel(value = "DeviceIdentifier", description = "This contains device details that is used to identify a device " + + "uniquely.") public class DeviceIdentifier implements Serializable{ + @ApiModelProperty(name = "id", value = "Identity of the device.", required = true) private String id; + @ApiModelProperty(name = "type", value = "Type of the device.", required = true) private String type; public DeviceIdentifier() {} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java index eb37127d2e..2ba839243c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java @@ -18,8 +18,13 @@ */ package org.wso2.carbon.device.mgt.common; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; +@ApiModel(value = "EnrolmentInfo", description = "This class carries all information related to a devices enrollment" + + " status.") public class EnrolmentInfo implements Serializable { private static final long serialVersionUID = 1998101712L; @@ -32,12 +37,24 @@ public class EnrolmentInfo implements Serializable { BYOD, COPE } + @ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.", + required = true) private int id; + @ApiModelProperty(name = "device", value = "Enrolled device.", required = true) private Device device; + @ApiModelProperty(name = "dateOfEnrolment", value = "Date of the device enrollment.", required = true ) private Long dateOfEnrolment; + @ApiModelProperty(name = "dateOfLastUpdate", value = "Date of the device's last update.", required = true ) private Long dateOfLastUpdate; + @ApiModelProperty(name = "ownership", value = "Defines the ownership details. The ownership type can be any of the" + + " following values.\n" + + "BYOD - Bring your own device (BYOD).\n" + + "COPE - Corporate owned personally enabled (COPE).", required = true ) private OwnerShip ownership; + @ApiModelProperty(name = "status", value = "Current status of the device, such as whether the device " + + "is active, removed etc.", required = true ) private Status status; + @ApiModelProperty(name = "owner", value = "The device owner's name.", required = true ) private String owner; public EnrolmentInfo() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java index 375b8d4562..e7dabd76ac 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java @@ -20,16 +20,28 @@ package org.wso2.carbon.device.mgt.common; import javax.xml.bind.annotation.XmlElement; import java.io.Serializable; import java.util.List; +import io.swagger.annotations.*; +@ApiModel(value = "Feature", description = "This class carries all information related to a devices enrollment" + + " status.") public class Feature implements Serializable { + @ApiModelProperty(name = "id", value = "Feature Id.", required = true ) private int id; + @ApiModelProperty(name = "code", value = "The code of the feature. For example the code to lock a device" + + " is DEVICE_LOCK.", required = true ) private String code; + @ApiModelProperty(name = "name", value = "A name that describes a feature.", required = true ) private String name; + @ApiModelProperty(name = "description", value = "Provides a description of the features..", required = true ) private String description; + @ApiModelProperty(name = "deviceType", value = "Provide the device type for the respective feature. " + + "Features allow you to perform operations on any device type, " + + "such as android, iOS or windows..", required = true ) private String deviceType; private String method; private String type; + @ApiModelProperty(name = "metadataEntries", value = "Properties related to features.", required = true ) private List metadataEntries; @XmlElement diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java index 0125b0fd90..433553b2da 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java @@ -18,18 +18,30 @@ package org.wso2.carbon.device.mgt.common; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; import java.util.List; /** * This class holds necessary data to represent a paginated result. */ +@ApiModel(value = "PaginationResult", description = "This class carries all information related Pagination Result") public class PaginationResult implements Serializable { private static final long serialVersionUID = 1998101711L; + + @ApiModelProperty(name = "recordsTotal", value = "The total number of records that are given before filtering", required = true) private int recordsTotal; + + @ApiModelProperty(name = "recordsFiltered", value = "The total number of records that are given after filtering", required = true) private int recordsFiltered; + + @ApiModelProperty(name = "draw", value = "The draw counter that this object is a response to, from the draw parameter sent as part of the data request", required = true) private int draw; + + @ApiModelProperty(name = "data", value = "The details of the SSL certificate", required = true) private List data; public int getRecordsTotal() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java index 0d45f903bd..1b17534dcf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java @@ -18,26 +18,41 @@ */ package org.wso2.carbon.device.mgt.common.app.mgt; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; import java.util.Properties; +@ApiModel(value = "Application", description = "This class carries all information related application") public class Application implements Serializable { private static final long serialVersionUID = 1998101711L; + @ApiModelProperty(name = "id", value = "The ID given to the application when it is stored in the EMM database", required = true) private int id; + @ApiModelProperty(name = "platform", value = "The mobile device platform. It can be android, ios or windows", required = true) private String platform; + @ApiModelProperty(name = "category", value = "The application category", required = true) private String category; + @ApiModelProperty(name = "name", value = "The application's name", required = true) private String name; - private String locationUrl; - private String imageUrl; - private String version; - private String type; - private Properties appProperties; - private String applicationIdentifier; + private String locationUrl; + @ApiModelProperty(name = "imageUrl", value = "The icon url of the application", required = true) + private String imageUrl; + @ApiModelProperty(name = "version", value = "The application's version", required = true) + private String version; + @ApiModelProperty(name = "type", value = "The application type", required = true) + private String type; + @ApiModelProperty(name = "appProperties", value = "The properties of the application", required = true) + private Properties appProperties; + @ApiModelProperty(name = "applicationIdentifier", value = "The application identifier", required = true) + private String applicationIdentifier; + @ApiModelProperty(name = "memoryUsage", value = "AMount of memory used by the application", required = true) private int memoryUsage; + public String getType() { return type; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationEntry.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationEntry.java index cafc157452..5c8a7b6e86 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationEntry.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationEntry.java @@ -18,36 +18,46 @@ package org.wso2.carbon.device.mgt.common.configuration.mgt; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + /** * Represents an individual configuration entry. */ +@ApiModel(value = "ConfigurationEntry", description = "This class carries all information related to Tenant Configuration" + + "Settings") public class ConfigurationEntry { - private String name; - private String contentType; - private Object value; + @ApiModelProperty(name = "name", value = "Name of the configuration", required = true) + private String name; - public String getName() { - return name; - } + @ApiModelProperty(name = "contentType", value = "Type of the configuration", required = true) + private String contentType; - public void setName(String name) { - this.name = name; - } + @ApiModelProperty(name = "value", value = "Value of the configuration", required = true) + private Object value; - public String getContentType() { - return contentType; - } + public String getName() { + return name; + } - public void setContentType(String contentType) { - this.contentType = contentType; - } + public void setName(String name) { + this.name = name; + } - public Object getValue() { - return value; - } + public String getContentType() { + return contentType; + } - public void setValue(Object value) { - this.value = value; - } + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfiguration.java index ece6a23a78..df19ddf1dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfiguration.java @@ -18,6 +18,9 @@ package org.wso2.carbon.device.mgt.common.configuration.mgt; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -30,10 +33,16 @@ import java.util.List; */ @XmlRootElement(name = "tenantConfiguration") @XmlAccessorType(XmlAccessType.NONE) + +@ApiModel(value = "TenantConfiguration", + description = "This class carries all information related to a Tenant configuration") public class TenantConfiguration implements Serializable { @XmlElement(name = "type") + @ApiModelProperty(name = "type", value = "type of device", required = true) private String type; + + @ApiModelProperty(name = "configuration", value = "List of Configuration Entries", required = true) @XmlElement(name = "configuration") private List configuration; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java index 92af0d4544..e76daf6611 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java @@ -19,6 +19,8 @@ package org.wso2.carbon.device.mgt.common.device.details; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import java.io.Serializable; @@ -26,34 +28,60 @@ import java.util.Date; import java.util.HashMap; import java.util.Map; +@ApiModel(value = "DeviceInfo", description = "This class carries all information related to the device information " + + "provided by a device.") public class DeviceInfo implements Serializable { private static final long serialVersionUID = 1998101733L; + @ApiModelProperty(name = "deviceId", value = "Device Id.", required = true) private int deviceId; + @ApiModelProperty(name = "deviceType", value = "Type of the device.", required = true) private String deviceType; + @ApiModelProperty(name = "deviceId", value = "Device identifier.", required = true) private DeviceIdentifier deviceIdentifier; - + @ApiModelProperty(name = "IMEI", value = "IMEI number of the device.", required = true) private String IMEI; + @ApiModelProperty(name = "IMSI", value = "IMSI number of the device.", required = true) private String IMSI; + @ApiModelProperty(name = "deviceModel", value = "Model of the device.", required = true) private String deviceModel; + @ApiModelProperty(name = "vendor", value = "Vendor of the device.", required = true) private String vendor; + @ApiModelProperty(name = "osVersion", value = "Operating system version.", required = true) private String osVersion; + @ApiModelProperty(name = "batteryLevel", value = "Battery level of the device.", required = true) private Double batteryLevel; + @ApiModelProperty(name = "internalTotalMemory", value = "Total internal memory of the device.", required = true) private Double internalTotalMemory; + @ApiModelProperty(name = "internalAvailableMemory", value = "Total available memory of the device.", + required = true) private Double internalAvailableMemory; + @ApiModelProperty(name = "externalTotalMemory", value = "Total external memory of the device.", required = true) private Double externalTotalMemory; + @ApiModelProperty(name = "externalAvailableMemory", value = "Total external memory avilable of the device.", + required = true) private Double externalAvailableMemory; + @ApiModelProperty(name = "operator", value = "Mobile operator of the device.", required = true) private String operator; + @ApiModelProperty(name = "connectionType", value = "How the device is connected to the network.", required = true) private String connectionType; + @ApiModelProperty(name = "mobileSignalStrength", value = "Current mobile signal strength.", required = true) private Double mobileSignalStrength; + @ApiModelProperty(name = "ssid", value = "ssid of the connected WiFi.", required = true) private String ssid; + @ApiModelProperty(name = "cpuUsage", value = "Current total cpu usage.", required = true) private Double cpuUsage; + @ApiModelProperty(name = "totalRAMMemory", value = "Total Ram memory size.", required = true) private Double totalRAMMemory; + @ApiModelProperty(name = "availableRAMMemory", value = "Available total memory of RAM.", required = true) private Double availableRAMMemory; + @ApiModelProperty(name = "pluggedIn", value = "Whether the device is plugged into power or not.", + required = true) private boolean pluggedIn; + @ApiModelProperty(name = "updatedTime", value = "Device updated time.", required = true) private Date updatedTime; - + @ApiModelProperty(name = "deviceDetailsMap", value = ".", required = true) private Map deviceDetailsMap = new HashMap<>(); public int getDeviceId() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java index 1368b92806..5223b0f047 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java @@ -19,27 +19,41 @@ package org.wso2.carbon.device.mgt.common.device.details; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import java.io.Serializable; import java.util.Date; +@ApiModel(value = "DeviceLocation", description = "This class carries all information related to the device location " + + "details provided by a device.") public class DeviceLocation implements Serializable { private static final long serialVersionUID = 1998101722L; + @ApiModelProperty(name = "deviceId", value = "Device id", required = true) private int deviceId; + @ApiModelProperty(name = "deviceIdentifier", value = "Device identifier used to identify a device uniquely.", + required = true) private DeviceIdentifier deviceIdentifier; + @ApiModelProperty(name = "latitude", value = "Device GPS latitude.", required = true) private Double latitude; + @ApiModelProperty(name = "longitude", value = "Device GPS longitude.", required = true) private Double longitude; - + @ApiModelProperty(name = "street1", value = "First line of the address.", required = true) private String street1; + @ApiModelProperty(name = "street2", value = "Second part of the address.", required = true) private String street2; - + @ApiModelProperty(name = "city", value = "City of the device location.", required = true) private String city; + @ApiModelProperty(name = "state", value = "State of the device address.", required = true) private String state; + @ApiModelProperty(name = "zip", value = "Zip code of the device address.", required = true) private String zip; + @ApiModelProperty(name = "country", value = "Country of the device address.", required = true) private String country; + @ApiModelProperty(name = "updatedTime", value = "Update time of the device.", required = true) private Date updatedTime; public int getDeviceId() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceWrapper.java index 0fae898778..5efdea1b51 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceWrapper.java @@ -19,14 +19,23 @@ package org.wso2.carbon.device.mgt.common.device.details; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +@ApiModel(value = "DeviceWrapper", description = "This contains device details including, " + + "location and device meta information.") public class DeviceWrapper { + @ApiModelProperty(name = "device", value = "Device's basic information", required = true) private Device device; + @ApiModelProperty(name = "deviceIdentifier", value = "Device identifier used to identify a device.", + required = true) private DeviceIdentifier deviceIdentifier; + @ApiModelProperty(name = "deviceInfo", value = "Device's runtime information", required = true) private DeviceInfo deviceInfo; + @ApiModelProperty(name = "deviceLocation", value = "Device's current location", required = true) private DeviceLocation deviceLocation; public Device getDevice() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java index 0d3af9886d..f9f776222a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java @@ -18,11 +18,15 @@ package org.wso2.carbon.device.mgt.common.notification.mgt; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; /** * DTO of Notification object which is used to communicate Operation notifications to MDM core. */ + +@ApiModel(value = "Notification", description = "This is used to communicate Operation notifications to MDM.") public class Notification { public enum Status{ @@ -33,10 +37,20 @@ public class Notification { ALERT, } + @ApiModelProperty(name = "notificationId", value = "Defines the notification ID.", required = true ) private int notificationId; + @ApiModelProperty(name = "deviceIdentifier", value = "Defines the device identification properties.", + required = true ) private DeviceIdentifier deviceIdentifier; + @ApiModelProperty(name = "description", value = "Provides the message you want to send to the user.", + required = true ) private String description; + @ApiModelProperty(name = "operationId", value = "Provides the operationID.", required = true ) private int operationId; + @ApiModelProperty(name = "status", value = "Provides the status of the message." + + "The following values can be assigned for the status.\n" + + "NEW: The message is in the unread state.\n" + + "CHECKED: The message is in the read state.", required = true ) private Status status; public Status getStatus() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java index 3496bacb8c..6add610c78 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java @@ -18,12 +18,18 @@ package org.wso2.carbon.device.mgt.common.operation.mgt; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; +import java.util.List; import java.util.Properties; @XmlRootElement +@ApiModel(value = "Operation", description = "This class carries all information related to a operations that can be " + + "applied on a device.") public class Operation implements Serializable { public enum Type { @@ -38,18 +44,53 @@ public class Operation implements Serializable { REPEAT, NO_REPEAT, PAUSE_SEQUENCE, STOP_SEQUENCE } + @ApiModelProperty(name = "code", value = "The code of the operation that you carried out. For example the code of" + + " the operation carried out to device info operation is DEVICE_INFO.", + required = true) private String code; + @ApiModelProperty(name = "properties", value = "Properties of an operation containing meta information.", + required = true) private Properties properties; + @ApiModelProperty(name = "type", value = "The operation type that was carried out on the device. " + + "The operations types can be one of the following: COMMAND, PROFILE", + required = true) private Type type; + @ApiModelProperty(name = "id", value = "The operations carried out on a device is recorded in a database table. " + + "The ID of the operation in the database table is given as the ID " + + "in the output.", + required = true) private int id; + @ApiModelProperty(name = "status", value = "The status of the operation that has been carried out on a device. The" + + " operation status can be any one of the following:\n" + + "IN-PROGRESS - The operation is processing on the EMM server" + + " side and has not yet been delivered to the device.\n" + + "PENDING - The operation is delivered to the device but the response " + + "from the device is pending.\n" + + "COMPLETED - The operation is delivered to the device and the server has " + + "received a response back from the device.\n" + + "ERROR - An error has occurred while carrying out the operation.", + required = true) private Status status; + @ApiModelProperty(name = "control", value = "How the operation should be executed.", required = true) private Control control; + @ApiModelProperty(name = "receivedTimeStamp", value = "The time WSO2 EMM received the response from the device.", + required = true) private String receivedTimeStamp; + @ApiModelProperty(name = "createdTimeStamp", value = "The time when the operation was requested to be carried out.", + required = true) private String createdTimeStamp; + @ApiModelProperty(name = "isEnabled", value = "If the assigned value is true it indicates that a policy is " + + "enforced on the device. If the assigned value is false it indicates" + + " that a policy is not enforced on a device.", required = true) private boolean isEnabled; + @ApiModelProperty(name = "payLoad", value = "Payload of the operation to be sent to the device", required = true) private Object payLoad; + @ApiModelProperty(name = "operationResponse", value = "Response received from the device", required = true) private String operationResponse; + @ApiModelProperty(name = "activityId", value = "The identifier used to identify the operation uniquely.", + required = true) private String activityId; + private List responses; @Override public boolean equals(Object o) { @@ -218,6 +259,14 @@ public class Operation implements Serializable { this.activityId = activityId; } + public List getResponses() { + return responses; + } + + public void setResponses(List responses) { + this.responses = responses; + } + @Override public String toString() { return "Operation{" + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationResponse.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationResponse.java new file mode 100644 index 0000000000..5a154e35b7 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationResponse.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.wso2.carbon.device.mgt.common.operation.mgt; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "OperationResponse", description = "This class carries all information related to operation" + + " responses") +public class OperationResponse { + + @ApiModelProperty(name = "response", value = "Operation response return from the device", required = true) + private String response; + @ApiModelProperty(name = "recievedTimeStamp", value = "Time that the operation response received", + required = true) + private String recievedTimeStamp; + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } + + public String getRecievedTimeStamp() { + return recievedTimeStamp; + } + + public void setRecievedTimeStamp(String recievedTimeStamp) { + this.recievedTimeStamp = recievedTimeStamp; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/Condition.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/Condition.java index 5a4b45dd1e..2cf03c5645 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/Condition.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/Condition.java @@ -19,12 +19,74 @@ package org.wso2.carbon.device.mgt.common.search; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "Condition", description = "Contains the advance search parameters.") public class Condition { + @ApiModelProperty(name = "conditions", value = "Provide the operation code. You can assign the following operation " + + "codes:\n" + + "DEVICE_MODEL : The model of the device.\n" + + "VENDOR : The name of the device vendor.\n" + + "OS_VERSION : The version of the device operating system.\n" + + "BATTERY_LEVEL : The current level of the device battery.\n" + + "INTERNAL_TOTAL_MEMORY : The total capacity of the internal memory" + + " available in the device.\n" + + "INTERNAL_AVAILABLE_MEMORY : The internal memory in the device " + + "that is available.\n" + + "EXTERNAL_TOTAL_MEMORY : The total capacity of the external memory " + + "available in the device.\n" + + "EXTERNAL_AVAILABLE_MEMORY : The external memory in the device" + + " that is available.\n" + + "CONNECTION_TYPE : Define if the device is connected to the GPRS " + + "or Wi-Fi settings.\n" + + "SSID : The name of the Wifi network that the device is " + + "connected to.\n" + + "CPU_USAGE : The current CPU usage of the mobile device.\n" + + "TOTAL_RAM_MEMORY : The total capacity of the random access " + + "memory available in the device.\n" + + "AVAILABLE_RAM_MEMORY : The random access memory capacity " + + "in the device that is available.\n" + + "PLUGGED_IN : Define true if the device is plugged in for charging " + + "or define false if the device is not plugged in for charging.", + required = true) private String key; + @ApiModelProperty(name = "value", value = "Define the value for the key you provide.\n" + + "Example: If you provide the key as VERSION, you can provide the " + + "value as 5.1, which indicates the version of the mobile device you" + + " are searching.", + required = true) private String value; + @ApiModelProperty(name = "operator", value = "Define the search condition between the key and the value you " + + "provide. The following values can be used to define the search " + + "condition:\n" + + "= : Searches for devices where the key is equal to the value " + + "provided.\n" + + "=! : Searches for devices where the key is not equal to the " + + "value provided.\n" + + "<= : Searches for devices where the key is greater than or equal" + + " to the value provide.\n" + + ">= : Searches for devices where the key is less than or equal to" + + " the value provided.\n" + + "> : Searches for devices where the key is greater than the value" + + " provided.\n" + + "< : Searches for devices where the key is less than the value " + + "provided.\n" + + "Example: If you wish to get the devises that have the version " + + "as 5.1, you need to use the = operator..", + required = true) public String operator; + @ApiModelProperty(name = "conditions", value = "There can be many search options as shown in the sample JSON " + + "definition. The field that connects the independent search " + + "options, is known as state.\n" + + "The following values can be assigned to state.\n" + + "AND : Defines if you want the search result to match all the " + + "search conditions provided.\n" + + "OR : Defines if you want the search result to match either of" + + " the search conditions provided.", + required = true) private State state; public enum State { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/SearchContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/SearchContext.java index c7c4be65ca..5207ddc502 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/SearchContext.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/SearchContext.java @@ -19,10 +19,17 @@ package org.wso2.carbon.device.mgt.common.search; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.util.List; + +@ApiModel(value = "SearchContext", description = "Search details when carrying out a search contain in this class.") public class SearchContext { + @ApiModelProperty(name = "conditions", value = "Contains the advance search parameters.", + required = true) private List conditions; // private int start; // private int end; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index bb73550ff6..7e36265173 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -83,6 +83,7 @@ org.apache.catalina.core, org.apache.commons.collections, org.wso2.carbon.email.sender.*, + io.swagger.annotations.*;resolution:=optional, org.wso2.carbon, org.wso2.carbon.base @@ -245,6 +246,12 @@ 1.7.1 + + io.swagger + swagger-annotations + provided + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceType.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceType.java index 52ca3ac891..eb363fff1c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceType.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/DeviceType.java @@ -18,12 +18,19 @@ package org.wso2.carbon.device.mgt.core.dto; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; +@ApiModel(value = "DeviceType", description = "This class carries all information related device types") public class DeviceType implements Serializable { private static final long serialVersionUID = 7927802716452548282L; + + @ApiModelProperty(name = "id", value = "Device type id", required = true) private int id; + @ApiModelProperty(name = "name", value = "Device type name", required = true) private String name; public DeviceType() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java index 360deb868a..c61b2d304f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java @@ -46,6 +46,7 @@ public class Operation implements Serializable { private boolean isEnabled; private Object payLoad; private Object operationResponse; + private String activityId; public String getCode() { return code; @@ -135,4 +136,12 @@ public class Operation implements Serializable { this.operationResponse = operationResponse; } + public String getActivityId() { + return activityId; + } + + public void setActivityId(String activityId) { + this.activityId = activityId; + } + } \ 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 5ec27f4c7c..6784b0cb70 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 @@ -659,12 +659,57 @@ public class OperationManagerImpl implements OperationManager { @Override public Operation getOperationByActivityId(String activity) throws OperationManagementException { // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer. - int operationId = Integer.parseInt( + Operation operation; + int enrollmentOpMappingId = Integer.parseInt( activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); - if(operationId == 0){ + if(enrollmentOpMappingId == 0){ throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); } - return this.getOperation(operationId); + try { + OperationManagementDAOFactory.openConnection(); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = + operationDAO.getOperationFromEnrollment(enrollmentOpMappingId); + + if (dtoOperation == null) { + throw new OperationManagementException("Operation not found for given activity Id:" + activity); + } + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status status = dtoOperation.getStatus(); + if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { + org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; + commandOperation = + (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. + getOperation(dtoOperation.getId()); + dtoOperation.setEnabled(commandOperation.isEnabled()); + } else if (dtoOperation.getType(). + equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { + dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); + } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. + PROFILE)) { + dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); + } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. + POLICY)) { + dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); + } + operation = OperationDAOUtil.convertOperation(dtoOperation); + int enrolmentId = operationDAO.getEnrolmentIdFromMappingId(enrollmentOpMappingId); + if (enrolmentId !=0) { + operation.setResponses(operationDAO.getOperationResponses(enrolmentId, operation.getId())); + } + + operation.setStatus(Operation.Status.valueOf(status.toString())); + operation.setActivityId(activity); + + } catch (SQLException e) { + throw new OperationManagementException("Error occurred while opening a connection to the data source", e); + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the operation with activity Id '" + + activity, e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + + // return this.getOperation(operationId); + return operation; } private OperationDAO lookupOperationDAO(Operation operation) { @@ -722,4 +767,8 @@ public class OperationManagerImpl implements OperationManager { return status; } + private void setActivityId(Operation operation, int enrolmentId) { + operation.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + enrolmentId); + } + } 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 9234953829..c7499d8496 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 @@ -19,6 +19,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.common.operation.mgt.OperationResponse; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import java.util.List; @@ -33,6 +34,8 @@ public interface OperationDAO { Operation getOperation(int operationId) throws OperationManagementDAOException; + Operation getOperationFromEnrollment(int enrollmentOpMappingId) throws OperationManagementDAOException; + Operation getOperationByDeviceAndId(int enrolmentId, int operationId) throws OperationManagementDAOException; List getOperationsByDeviceAndStatus(int enrolmentId, Operation.Status status) @@ -58,4 +61,8 @@ public interface OperationDAO { void addOperationResponse(int enrolmentId, int operationId, Object operationResponse) throws OperationManagementDAOException; + List getOperationResponses(int enrolmentId, int operationId) throws OperationManagementDAOException; + + int getEnrolmentIdFromMappingId(int enrollmentOpMappingId) throws OperationManagementDAOException; + } \ 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/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 592be91c71..45e9f4d2cc 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 @@ -20,15 +20,15 @@ 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.common.operation.mgt.OperationResponse; +import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; 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; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; +import java.io.*; import java.sql.*; import java.util.ArrayList; import java.util.Date; @@ -149,7 +149,7 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection connection = OperationManagementDAOFactory.getConnection(); stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID,ENROLMENT_ID," + - "OPERATION_RESPONSE) VALUES(?, ?, ?)"); + "OPERATION_RESPONSE, RECEIVED_TIMESTAMP) VALUES(?, ?, ?, ?)"); bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); oos.writeObject(operationResponse); @@ -157,6 +157,7 @@ public class GenericOperationDAOImpl implements OperationDAO { stmt.setInt(1, operationId); stmt.setInt(2, enrolmentId); stmt.setBytes(3, bao.toByteArray()); + stmt.setTimestamp(4, new Timestamp(new Date().getTime())); stmt.executeUpdate(); } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while inserting operation response", e); @@ -181,6 +182,92 @@ public class GenericOperationDAOImpl implements OperationDAO { } } + @Override + public List getOperationResponses(int enrolmentId, int operationId) throws + OperationManagementDAOException { + + PreparedStatement stmt = null; + ResultSet rs = null; + List responces = new ArrayList<>(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT * FROM DM_DEVICE_OPERATION_RESPONSE WHERE ENROLMENT_ID = ? AND OPERATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + stmt.setInt(2, operationId); + rs = stmt.executeQuery(); + + while (rs.next()) { + OperationResponse response = new OperationResponse(); + response.setRecievedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + ByteArrayInputStream bais = null; + ObjectInputStream ois = null; + byte[] contentBytes; + try { + contentBytes = (byte[]) rs.getBytes("OPERATION_RESPONSE"); + bais = new ByteArrayInputStream(contentBytes); + ois = new ObjectInputStream(bais); + response.setResponse(ois.readObject().toString()); + + } finally { + if (bais != null) { + try { + bais.close(); + } catch (IOException e) { + log.warn("Error occurred while closing ByteArrayOutputStream", e); + } + } + if (ois != null) { + try { + ois.close(); + } catch (IOException e) { + log.warn("Error occurred while closing ObjectOutputStream", e); + } + } + } + responces.add(response); + } + + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL Error occurred while retrieving the operation responses for " + + "operation id " + operationId + " and enrolment id " + enrolmentId, e); + } catch (ClassNotFoundException e) { + throw new OperationManagementDAOException("Error occurred while converting the operation responses to string" + + " for operation id " + operationId + " and enrolment id " + enrolmentId, e); + } catch (IOException e) { + throw new OperationManagementDAOException("Error occurred while converting the operation responses to string" + + " for operation id " + operationId + " and enrolment id " + enrolmentId, e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + + return responces; + } + + @Override + public int getEnrolmentIdFromMappingId(int enrollmentOpMappingId) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT * FROM DM_ENROLMENT_OP_MAPPING WHERE ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrollmentOpMappingId); + rs = stmt.executeQuery(); + + if (rs.next()) { + return rs.getInt("ENROLMENT_ID"); + } + + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL Error occurred while retrieving the enrolment id " + + " for the mapping id '" + enrollmentOpMappingId, e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return -1; + } + @Override public void deleteOperation(int id) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -231,6 +318,43 @@ public class GenericOperationDAOImpl implements OperationDAO { return operation; } + @Override + public Operation getOperationFromEnrollment(int enrollmentOpMappingId) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Operation operation = null; + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, \n" + + " om.STATUS FROM DM_OPERATION o \n" + + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm WHERE dm.ID = ? ) om \n" + + "ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC "; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrollmentOpMappingId); + rs = stmt.executeQuery(); + + if (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + this.setActivityId(operation, enrollmentOpMappingId); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation .", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operation; + } + @Override public Operation getOperationByDeviceAndId(int enrolmentId, int operationId) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -238,7 +362,7 @@ public class GenericOperationDAOImpl implements OperationDAO { Operation operation = null; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.STATUS, o.OPERATION_CODE " + + String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.STATUS, o.OPERATION_CODE, om.ID AS OM_MAPPING_ID " + " FROM (SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, STATUS," + "OPERATION_CODE FROM DM_OPERATION WHERE id = ?) o INNER JOIN (SELECT * FROM " + "DM_ENROLMENT_OP_MAPPING dm where dm.OPERATION_ID = ? AND dm.ENROLMENT_ID = ?) om " + @@ -260,6 +384,7 @@ public class GenericOperationDAOImpl implements OperationDAO { operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); } operation.setCode(rs.getString("OPERATION_CODE")); + this.setActivityId(operation, rs.getInt("OM_MAPPING_ID")); } } catch (SQLException e) { throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + @@ -279,7 +404,7 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, om.ID AS OM_MAPPING_ID" + "FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC"; @@ -300,6 +425,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } operation.setCode(rs.getString("OPERATION_CODE")); operation.setStatus(status); + this.setActivityId(operation, rs.getInt("OM_MAPPING_ID")); operations.add(operation); } } catch (SQLException e) { @@ -321,7 +447,7 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, om.ID AS OM_MAPPING_ID " + "FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + @@ -345,6 +471,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } operation.setCode(rs.getString("OPERATION_CODE")); operation.setStatus(status); + this.setActivityId(operation, rs.getInt("OM_MAPPING_ID")); operations.add(operation); } } catch (SQLException e) { @@ -365,7 +492,7 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection conn = OperationManagementDAOFactory.getConnection(); String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + - "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + + "OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC"; stmt = conn.prepareStatement(sql); @@ -384,6 +511,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } operation.setCode(rs.getString("OPERATION_CODE")); operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + this.setActivityId(operation, rs.getInt("OM_MAPPING_ID")); operations.add(operation); } } catch (SQLException e) { @@ -405,7 +533,7 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection conn = OperationManagementDAOFactory.getConnection(); String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + - "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + + "OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ?,?"; stmt = conn.prepareStatement(sql); @@ -426,6 +554,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } operation.setCode(rs.getString("OPERATION_CODE")); operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + this.setActivityId(operation, rs.getInt("OM_MAPPING_ID")); operations.add(operation); } } catch (SQLException e) { @@ -468,7 +597,7 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection connection = OperationManagementDAOFactory.getConnection(); stmt = connection.prepareStatement("SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + - "OPERATION_CODE FROM DM_OPERATION o " + + "OPERATION_CODE, om.ID AS OM_MAPPING_ID FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID " + "ORDER BY o.CREATED_TIMESTAMP ASC LIMIT 1"); @@ -489,6 +618,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } operation.setCode(rs.getString("OPERATION_CODE")); operation.setStatus(Operation.Status.PENDING); + this.setActivityId(operation, rs.getInt("OM_MAPPING_ID")); } return operation; } catch (SQLException e) { @@ -507,7 +637,7 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE FROM " + + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, om.ID AS OM_MAPPING_ID FROM " + "(SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + "FROM DM_OPERATION o WHERE o.TYPE = ?) o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + @@ -530,6 +660,7 @@ public class GenericOperationDAOImpl implements OperationDAO { operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); } operation.setCode(rs.getString("OPERATION_CODE")); + this.setActivityId(operation, rs.getInt("OM_MAPPING_ID")); operations.add(operation); } } catch (SQLException e) { @@ -545,4 +676,9 @@ public class GenericOperationDAOImpl implements OperationDAO { return Operation.Type.valueOf(type); } + private void setActivityId(Operation operation, int enrolmentId) { + operation.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + enrolmentId); + } + + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java index 6625ceab89..03e7e64143 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java @@ -95,7 +95,7 @@ public class OperationDAOUtil { operation.setReceivedTimeStamp(dtoOperation.getReceivedTimeStamp()); operation.setEnabled(dtoOperation.isEnabled()); operation.setProperties(dtoOperation.getProperties()); - operation.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + dtoOperation.getId()); + operation.setActivityId(dtoOperation.getActivityId()); return operation; diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java index 352e8177aa..cbfa846c21 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/src/main/java/org/wso2/carbon/identity/jwt/client/extension/util/JWTClientUtil.java @@ -73,7 +73,7 @@ public class JWTClientUtil { private static final Log log = LogFactory.getLog(JWTClientUtil.class); private static final String HTTPS_PROTOCOL = "https"; - private static final String TENANT_JWT_CONFIG_LOCATION = "/jwt-config/jwt.properties"; + private static final String TENANT_JWT_CONFIG_LOCATION = File.separator + "jwt-config" + File.separator + "jwt.properties"; private static final String JWT_CONFIG_FILE_NAME = "jwt.properties"; private static final String SUPERTENANT_JWT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + JWT_CONFIG_FILE_NAME; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml index cfa51b818b..597ea8239a 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml @@ -53,6 +53,8 @@ ${carbon.device.mgt.version} Policy Management Common Bundle + javax.xml.bind.annotation, + io.swagger.annotations.*;resolution:=optional, org.wso2.carbon.device.mgt.common.*, org.wso2.carbon.device.mgt.core.dto.*, javax.xml.bind.*, @@ -91,6 +93,11 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.core + + io.swagger + swagger-annotations + provided + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java index 25c5f48cc4..4620adb72e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java @@ -17,6 +17,8 @@ */ package org.wso2.carbon.policy.mgt.common; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.Device; import javax.xml.bind.annotation.XmlElement; @@ -29,24 +31,50 @@ import java.util.Map; * This class will be the used to create policy object with relevant information for evaluating. */ @XmlRootElement +@ApiModel(value = "Policy", description = "This class carries all information related to Policies") public class Policy implements Comparable, Serializable { private static final long serialVersionUID = 19981017L; + @ApiModelProperty(name = "id", value = "The policy ID", required = true) private int id; // Identifier of the policy. - private int priorityId; // Priority of the policies. This will be used only for simple evaluation. + @ApiModelProperty(name = "priorityId", value = "The priority order of the policy. 1 indicates the highest" + + " priority", required = true) + private int priorityId; // Priority of the policies. This will be used only for simple evaluation. + @ApiModelProperty(name = "profile", value = "Contains the details of the profile that is included in the " + + "policy", required = true) private Profile profile; // Profile + @ApiModelProperty(name = "policyName", value = "The name of the policy", required = true) private String policyName; // Name of the policy. + @ApiModelProperty(name = "generic", value = "If true, this should be applied to all related device", + required = true) private boolean generic; // If true, this should be applied to all related device. + @ApiModelProperty(name = "roles", value = "The roles to whom the policy is applied on", required = true) private List roles; // Roles which this policy should be applied. + @ApiModelProperty(name = "ownershipType", value = "The policy ownership type. It can be any of the " + + "following values:\n" + + "ANY - The policy will be applied on the BYOD and COPE device types\n" + + "BYOD (Bring Your Own Device) - The policy will only be applied on the BYOD device type\n" + + "COPE (Corporate-Owned, Personally-Enabled) - The policy will only be applied on the COPE " + + "device type\n", required = true) private String ownershipType; // Ownership type (COPE, BYOD, CPE) + @ApiModelProperty(name = "devices", value = "Lists out the devices the policy is enforced on", + required = true) private List devices; // Individual devices this policy should be applied + @ApiModelProperty(name = "users", value = "Lists out the users on whose devices the policy is enforced", + required = true) private List users; + @ApiModelProperty(name = "active", value = "If the value is true it indicates that the policy is active. " + + "If the value is false it indicates that the policy is inactive", required = true) private boolean active; + @ApiModelProperty(name = "updated", value = "If you have made changes to the policy but have not applied" + + " these changes to the devices that are registered with EMM, then the value is defined as true." + + " But if you have already applied any changes made to the policy then the value is defined as" + + " false.", required = true) private boolean updated; + @ApiModelProperty(name = "description", value = "Gives a description on the policy", required = true) private String description; - /* Compliance data*/ private String compliance; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/ProfileFeature.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/ProfileFeature.java index 00e3b65d96..5de755a35d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/ProfileFeature.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/ProfileFeature.java @@ -18,16 +18,29 @@ package org.wso2.carbon.policy.mgt.common; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import java.io.Serializable; +@ApiModel(value = "ProfileFeature", description = "This class carries all information related to profile " + + "features") public class ProfileFeature implements Serializable { private static final long serialVersionUID = 19981018L; + @ApiModelProperty(name = "id", value = "Define the ID", required = true) private int id; + @ApiModelProperty(name = "featureCode", value = "Provide the code that defines the policy you wish to add", + required = true) private String featureCode; + @ApiModelProperty(name = "profileId", value = "Define the ID of the profile", required = true) private int profileId; + @ApiModelProperty(name = "deviceTypeId", value = "The ID used to define the type of the device platform", + required = true) private int deviceTypeId; + @ApiModelProperty(name = "content", value = "The list of parameters that define the policy", + required = true) private Object content; public int getId() { 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 6b40e2022b..0f9026a3a4 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 @@ -28,6 +28,7 @@ public class CertificateAuthenticator implements WebappAuthenticator { private static final Log log = LogFactory.getLog(CertificateAuthenticator.class); private static final String CERTIFICATE_AUTHENTICATOR = "CertificateAuth"; private static final String MUTUAL_AUTH_HEADER = "mutual-auth-header"; + private static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header"; private static final String CERTIFICATE_VERIFICATION_HEADER = "certificate-verification-header"; private static final String CLIENT_CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate"; @@ -38,8 +39,8 @@ public class CertificateAuthenticator implements WebappAuthenticator { @Override public boolean canHandle(Request request) { - if (request.getHeader(CERTIFICATE_VERIFICATION_HEADER) != null || request.getHeader(MUTUAL_AUTH_HEADER) != - null) { + if (request.getHeader(CERTIFICATE_VERIFICATION_HEADER) != null || request.getHeader(MUTUAL_AUTH_HEADER) != null + || request.getHeader(PROXY_MUTUAL_AUTH_HEADER) != null) { return true; } return false; @@ -56,35 +57,20 @@ public class CertificateAuthenticator implements WebappAuthenticator { String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER); try { - - if (request.getHeader(MUTUAL_AUTH_HEADER) != null) { + // When there is a load balancer terminating mutual SSL, it should pass this header along and + // as the value of this header, the client certificate subject dn should be passed. + if (request.getHeader(PROXY_MUTUAL_AUTH_HEADER) != null) { + CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance(). + getCertificateManagementService().verifySubjectDN(request.getHeader(PROXY_MUTUAL_AUTH_HEADER)); + authenticationInfo = checkCertificateResponse(certificateResponse); + } + else if (request.getHeader(MUTUAL_AUTH_HEADER) != null) { X509Certificate[] clientCertificate = (X509Certificate[]) request. getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE); if (clientCertificate != null && clientCertificate[0] != null) { CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance(). getCertificateManagementService().verifyPEMSignature(clientCertificate[0]); - if (certificateResponse == null) { - authenticationInfo.setStatus(Status.FAILURE); - authenticationInfo.setMessage("Certificate sent doesn't match any certificate in the store." + - " Unauthorized access attempt."); - } else if (certificateResponse.getCommonName() != null && !certificateResponse.getCommonName(). - isEmpty()) { - authenticationInfo.setTenantId(certificateResponse.getTenantId()); - authenticationInfo.setStatus(Status.CONTINUE); - authenticationInfo.setUsername(certificateResponse.getCommonName()); - try { - authenticationInfo.setTenantDomain(Utils. - getTenantDomain( - certificateResponse.getTenantId())); - } catch (AuthenticationException e) { - authenticationInfo.setStatus(Status.FAILURE); - authenticationInfo.setMessage("Could not identify tenant domain."); - } - } else { - authenticationInfo.setStatus(Status.FAILURE); - authenticationInfo.setMessage("A matching certificate is found, " + - "but the serial number is missing in the database."); - } + authenticationInfo = checkCertificateResponse(certificateResponse); } else { authenticationInfo.setStatus(Status.FAILURE); @@ -133,6 +119,33 @@ public class CertificateAuthenticator implements WebappAuthenticator { return authenticationInfo; } + private AuthenticationInfo checkCertificateResponse(CertificateResponse certificateResponse) { + AuthenticationInfo authenticationInfo = new AuthenticationInfo(); + if (certificateResponse == null) { + authenticationInfo.setStatus(Status.FAILURE); + authenticationInfo.setMessage("Certificate sent doesn't match any certificate in the store." + + " Unauthorized access attempt."); + } else if (certificateResponse.getCommonName() != null && !certificateResponse.getCommonName(). + isEmpty()) { + authenticationInfo.setTenantId(certificateResponse.getTenantId()); + authenticationInfo.setStatus(Status.CONTINUE); + authenticationInfo.setUsername(certificateResponse.getCommonName()); + try { + authenticationInfo.setTenantDomain(Utils. + getTenantDomain( + certificateResponse.getTenantId())); + } catch (AuthenticationException e) { + authenticationInfo.setStatus(Status.FAILURE); + authenticationInfo.setMessage("Could not identify tenant domain."); + } + } else { + authenticationInfo.setStatus(Status.FAILURE); + authenticationInfo.setMessage("A matching certificate is found, " + + "but the serial number is missing in the database."); + } + return authenticationInfo; + } + @Override public String getName() { return CERTIFICATE_AUTHENTICATOR; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 67cdf57a33..a767ae6bfb 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -123,6 +123,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, OPERATION_RESPONSE BLOB DEFAULT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index e18fcf915a..5c7e5e9799 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -123,6 +123,7 @@ CREATE TABLE DM_DEVICE_OPERATION_RESPONSE ( ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, OPERATION_RESPONSE VARBINARY(max) DEFAULT NULL, + RECEIVED_TIMESTAMP DATETIME2(0) NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index 0fd8889cc3..b7f06c57aa 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -108,6 +108,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, OPERATION_RESPONSE BLOB DEFAULT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql index 7a41ae3a66..fa18093ba9 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -229,6 +229,7 @@ CREATE TABLE DM_DEVICE_OPERATION_RESPONSE ( ENROLMENT_ID NUMBER(10) NOT NULL, OPERATION_ID NUMBER(10) NOT NULL, OPERATION_RESPONSE BLOB DEFAULT NULL, + RECEIVED_TIMESTAMP TIMESTAMP(0) NULL, CONSTRAINT PK_DM_DEVICE_OP_RESPONSE PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_OP_RES_DEVICE FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID), diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 9ec4ef3778..de4a8ca016 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 @@ -94,6 +94,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, OPERATION_RESPONSE BYTEA DEFAULT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties index 6649b50d1c..2b22f91475 100644 --- a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties +++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/src/main/resources/jwt.properties @@ -19,7 +19,7 @@ #issuer of the JWT iss=CDMF_DEFAULT_IDP -TokenEndpoint=https://${server.host}:${mgt.transport.https.port}/oauth2/token +TokenEndpoint=https://localhost:${carbon.https.port}/oauth2/token #audience of JWT claim #comma seperated values diff --git a/pom.xml b/pom.xml index 3dbcc79a48..54e1346008 100644 --- a/pom.xml +++ b/pom.xml @@ -1456,10 +1456,23 @@ swagger-annotations ${swagger.version} + + io.swagger + swagger-core + ${swagger.version} + + + io.swagger + swagger-jaxrs + ${swagger.version} + + + + javax.servlet + servlet-api + ${servlet-api.version} + - - - @@ -1823,6 +1836,7 @@ [2.26.1, 3.0.0) 1.5.8 + 2.5