Resolve conflicts

pull/1/head
osh 2 years ago
commit 9b9defed19

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>analytics-mgt</artifactId> <artifactId>analytics-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -3,7 +3,7 @@
<parent> <parent>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -256,10 +256,14 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
keyManagerId = keyManagerConfigurationDTO.getUuid(); keyManagerId = keyManagerConfigurationDTO.getUuid();
} }
} }
String applicationAccessTokenExpiryTime = "N/A";
if (!StringUtils.isEmpty(validityTime)) {
applicationAccessTokenExpiryTime = validityTime;
}
String jsonString = "{\"grant_types\":\"refresh_token,access_token," + String jsonString = "{\"grant_types\":\"refresh_token,access_token," +
"urn:ietf:params:oauth:grant-type:saml2-bearer," + "urn:ietf:params:oauth:grant-type:saml2-bearer," +
"password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-bearer\"," + "password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-bearer\"," +
"\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"N\\/A\\\"," + "\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"" + applicationAccessTokenExpiryTime + "\\\"," +
"\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," + "\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," + "\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," + "\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," +

@ -3,7 +3,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

@ -40,6 +40,9 @@ public class DCRRequest {
@XmlElement @XmlElement
private boolean isSaasApp; private boolean isSaasApp;
@XmlElement
private int validityPeriod;
public String getApplicationName() { public String getApplicationName() {
return applicationName; return applicationName;
} }
@ -87,4 +90,12 @@ public class DCRRequest {
public void setIsSaasApp(boolean saasApp) { public void setIsSaasApp(boolean saasApp) {
isSaasApp = saasApp; isSaasApp = saasApp;
} }
public int getValidityPeriod() {
return validityPeriod;
}
public void setValidityPeriod(int validityPeriod) {
this.validityPeriod = validityPeriod;
}
} }

@ -46,5 +46,6 @@ public interface KeyManagerService {
@FormParam("assertion") String assertion, @FormParam("assertion") String assertion,
@FormParam("admin_access_token") String admin_access_token, @FormParam("admin_access_token") String admin_access_token,
@FormParam("username") String username, @FormParam("username") String username,
@FormParam("password") String password); @FormParam("password") String password,
@FormParam("validityPeriod") int validityPeriod);
} }

@ -51,7 +51,7 @@ public class KeyManagerServiceImpl implements KeyManagerService {
try { try {
KeyMgtService keyMgtService = new KeyMgtServiceImpl(); KeyMgtService keyMgtService = new KeyMgtServiceImpl();
DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(), DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(),
dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp()); dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod());
return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build(); return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) { } catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
@ -69,7 +69,8 @@ public class KeyManagerServiceImpl implements KeyManagerService {
@FormParam("assertion") String assertion, @FormParam("assertion") String assertion,
@FormParam("admin_access_token") String admin_access_token, @FormParam("admin_access_token") String admin_access_token,
@FormParam("username") String username, @FormParam("username") String username,
@FormParam("password") String password) { @FormParam("password") String password,
@FormParam("validityPeriod") int validityPeriod) {
try { try {
if (basicAuthHeader == null) { if (basicAuthHeader == null) {
String msg = "Invalid credentials. Make sure your API call is invoked with a Basic Authorization header."; String msg = "Invalid credentials. Make sure your API call is invoked with a Basic Authorization header.";
@ -80,7 +81,7 @@ public class KeyManagerServiceImpl implements KeyManagerService {
TokenResponse resp = keyMgtService.generateAccessToken( TokenResponse resp = keyMgtService.generateAccessToken(
new TokenRequest(encodedClientCredentials.split(":")[0], new TokenRequest(encodedClientCredentials.split(":")[0],
encodedClientCredentials.split(":")[1], refreshToken, scope, encodedClientCredentials.split(":")[1], refreshToken, scope,
grantType, assertion, admin_access_token, username, password)); grantType, assertion, admin_access_token, username, password, validityPeriod));
return Response.status(Response.Status.OK).entity(gson.toJson(resp)).build(); return Response.status(Response.Status.OK).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) { } catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();

@ -3,7 +3,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -29,8 +29,10 @@ public class TokenRequest {
private String username; private String username;
private String password; private String password;
private int validityPeriod;
public TokenRequest(String clientId, String clientSecret, String refreshToken, String scope, String grantType, public TokenRequest(String clientId, String clientSecret, String refreshToken, String scope, String grantType,
String assertion, String admin_access_token, String username, String password) { String assertion, String admin_access_token, String username, String password, int validityPeriod) {
this.clientId = clientId; this.clientId = clientId;
this.clientSecret = clientSecret; this.clientSecret = clientSecret;
this.refreshToken = refreshToken; this.refreshToken = refreshToken;
@ -40,6 +42,7 @@ public class TokenRequest {
this.admin_access_token = admin_access_token; this.admin_access_token = admin_access_token;
this.username = username; this.username = username;
this.password = password; this.password = password;
this.validityPeriod = validityPeriod;
} }
public String getClientId() { public String getClientId() {
@ -113,4 +116,12 @@ public class TokenRequest {
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
public int getValidityPeriod() {
return validityPeriod;
}
public void setValidityPeriod(int validityPeriod) {
this.validityPeriod = validityPeriod;
}
} }

@ -39,7 +39,7 @@ public interface KeyMgtService {
* @throws KeyMgtException if any error occurs during DCR process * @throws KeyMgtException if any error occurs during DCR process
*/ */
DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
String[] tags, boolean isSaasApp) throws KeyMgtException; String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException;
/*** /***
* This method will handle the access token requests * This method will handle the access token requests

@ -77,7 +77,7 @@ public class KeyMgtServiceImpl implements KeyMgtService {
String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null; String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null;
public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
String[] tags, boolean isSaasApp) throws KeyMgtException { String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException {
if (owner == null) { if (owner == null) {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
@ -105,13 +105,13 @@ public class KeyMgtServiceImpl implements KeyMgtService {
kmConfig = getKeyManagerConfig(); kmConfig = getKeyManagerConfig();
if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) { if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) {
OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags); OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, validityPeriod);
return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret()); return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret());
} else { } else {
// super-tenant admin dcr and token generation // super-tenant admin dcr and token generation
OAuthApplication superTenantOauthApp = createOauthApplication( OAuthApplication superTenantOauthApp = createOauthApplication(
KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT, KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT,
kmConfig.getAdminUsername(), null); kmConfig.getAdminUsername(), null, validityPeriod);
String superAdminAccessToken = createAccessToken(superTenantOauthApp); String superAdminAccessToken = createAccessToken(superTenantOauthApp);
// create new key manager for the tenant, under super-tenant space // create new key manager for the tenant, under super-tenant space
@ -133,7 +133,7 @@ public class KeyMgtServiceImpl implements KeyMgtService {
createUserIfNotExists(subTenantUserUsername, subTenantUserPassword); createUserIfNotExists(subTenantUserUsername, subTenantUserPassword);
// DCR for the requesting user // DCR for the requesting user
OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags); OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod);
String requestingUserAccessToken = createAccessToken(dcrApplication); String requestingUserAccessToken = createAccessToken(dcrApplication);
// get application id // get application id
@ -167,7 +167,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
case "client_credentials": case "client_credentials":
appTokenPayload = new FormBody.Builder() appTokenPayload = new FormBody.Builder()
.add("grant_type", "client_credentials") .add("grant_type", "client_credentials")
.add("scope", tokenRequest.getScope()).build(); .add("scope", tokenRequest.getScope())
.add("validityPeriod", String.valueOf(tokenRequest.getValidityPeriod())).build();
break; break;
case "password": case "password":
appTokenPayload = new FormBody.Builder() appTokenPayload = new FormBody.Builder()
@ -322,8 +323,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
* @return @{@link OAuthApplication} OAuth application object * @return @{@link OAuthApplication} OAuth application object
* @throws KeyMgtException if any error occurs while creating response object * @throws KeyMgtException if any error occurs while creating response object
*/ */
private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags) throws KeyMgtException { private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, int validityPeriod) throws KeyMgtException {
String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags); String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod);
RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON); RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON);
kmConfig = getKeyManagerConfig(); kmConfig = getKeyManagerConfig();
String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT; String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT;
@ -442,11 +443,12 @@ public class KeyMgtServiceImpl implements KeyMgtService {
} }
} }
private String createOauthAppCreationPayload(String clientName, String owner, String[] tags) { private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod) {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("applicationName", clientName); jsonObject.put("applicationName", clientName);
jsonObject.put("username", owner); jsonObject.put("username", owner);
jsonObject.put("tags", tags); jsonObject.put("tags", tags);
jsonObject.put("validityPeriod", validityPeriod);
return jsonObject.toString(); return jsonObject.toString();
} }

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -20,7 +20,7 @@
<parent> <parent>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -94,6 +94,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl {
|| StringUtils.isNotEmpty(filter.getAppReleaseType())) { || StringUtils.isNotEmpty(filter.getAppReleaseType())) {
sql += "LEFT JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "; sql += "LEFT JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID ";
} }
sql += "WHERE AP_APP.TENANT_ID = ? ";
if (StringUtils.isNotEmpty(filter.getAppType()) && !Constants.ALL.equalsIgnoreCase(filter.getAppType())) { if (StringUtils.isNotEmpty(filter.getAppType()) && !Constants.ALL.equalsIgnoreCase(filter.getAppType())) {
sql += "AND AP_APP.TYPE = ? "; sql += "AND AP_APP.TYPE = ? ";
} }
@ -128,7 +129,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl {
sql += filter.getSortBy() +" "; sql += filter.getSortBy() +" ";
} }
if (filter.getLimit() != -1) { if (filter.getLimit() != -1) {
sql += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "; sql += "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ";
} }
sql += ") AS app_data ON app_data.ID = AP_APP.ID " sql += ") AS app_data ON app_data.ID = AP_APP.ID "
+ "LEFT JOIN (" + "LEFT JOIN ("
@ -145,6 +146,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIndex = 1; int paramIndex = 1;
stmt.setInt(paramIndex++, tenantId);
if (StringUtils.isNotEmpty(filter.getAppType()) && !Constants.ALL.equalsIgnoreCase(filter.getAppType())) { if (StringUtils.isNotEmpty(filter.getAppType()) && !Constants.ALL.equalsIgnoreCase(filter.getAppType())) {
stmt.setString(paramIndex++, filter.getAppType()); stmt.setString(paramIndex++, filter.getAppType());
} }

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -38,7 +38,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -23,7 +23,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -48,6 +48,22 @@ public interface EntgraLogger extends Log {
void warn(Object object, Throwable t, LogContext logContext); void warn(Object object, Throwable t, LogContext logContext);
void info(String message, LogContext logContext);
void debug(String message, LogContext logContext);
void error(String message, LogContext logContext);
void error(String message, Throwable t, LogContext logContext);
void warn(String message, LogContext logContext);
void warn(String message, Throwable t, LogContext logContext);
void trace(String message, LogContext logContext);
void fatal(String message, LogContext logContext);
void clearLogContext(); void clearLogContext();
} }

@ -23,7 +23,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -425,5 +425,30 @@
<artifactId>io.entgra.application.mgt.core</artifactId> <artifactId>io.entgra.application.mgt.core</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.keymgt.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.stream.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.receiver.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.publisher.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.rdbms</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

@ -0,0 +1,116 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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.beans;
import io.swagger.annotations.ApiModel;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import java.util.List;
@ApiModel(value = "DeviceConfig", description = "Device config")
public class DeviceConfig {
private String clientId;
private String clientSecret;
private String deviceId;
private String type;
private String accessToken;
private String refreshToken;
private String mqttGateway;
private String httpsGateway;
private String httpGateway;
private PlatformConfiguration platformConfiguration;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getMqttGateway() {
return mqttGateway;
}
public void setMqttGateway(String mqttGateway) {
this.mqttGateway = mqttGateway;
}
public String getHttpsGateway() {
return httpsGateway;
}
public void setHttpsGateway(String httpsGateway) {
this.httpsGateway = httpsGateway;
}
public String getHttpGateway() {
return httpGateway;
}
public void setHttpGateway(String httpGateway) {
this.httpGateway = httpGateway;
}
public PlatformConfiguration getPlatformConfiguration() {
return platformConfiguration;
}
public void setPlatformConfiguration(PlatformConfiguration platformConfiguration) {
this.platformConfiguration = platformConfiguration;
}
}

@ -20,14 +20,18 @@ package org.wso2.carbon.device.mgt.jaxrs.beans.analytics;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/** /**
* This hold stats data record * This hold stats data record
*/ */
public class DeviceTypeEvent { public class DeviceTypeEvent {
private String eventName;
private EventAttributeList eventAttributes; private EventAttributeList eventAttributes;
private TransportType transport; private TransportType transport;
private String eventTopicStructure;
@ApiModelProperty(value = "Attributes related to device type event") @ApiModelProperty(value = "Attributes related to device type event")
@JsonProperty("eventAttributes") @JsonProperty("eventAttributes")
public EventAttributeList getEventAttributeList() { public EventAttributeList getEventAttributeList() {
@ -48,5 +52,25 @@ public class DeviceTypeEvent {
public void setTransportType(TransportType transport) { public void setTransportType(TransportType transport) {
this.transport = transport; this.transport = transport;
} }
@ApiModelProperty(value = "event topic structure")
@JsonProperty("eventTopicStructure")
public String getEventTopicStructure() {
return eventTopicStructure;
}
public void setEventTopicStructure(String eventTopicStructure) {
this.eventTopicStructure = eventTopicStructure;
}
@ApiModelProperty(value = "event topic name")
@JsonProperty("eventName")
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
} }

@ -29,6 +29,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List;
@SwaggerDefinition( @SwaggerDefinition(
info = @Info( info = @Info(
@ -69,64 +70,64 @@ import javax.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public interface DeviceEventManagementService { public interface DeviceEventManagementService {
// @POST @POST
// @Path("/{type}") @Path("/{type}")
// @ApiOperation( @ApiOperation(
// produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
// httpMethod = "POST", httpMethod = "POST",
// value = "Adding the Event Type Definition", value = "Adding the Event Type Definition",
// notes = "Add the event definition for a device.", notes = "Add the event definition for a device.",
// tags = "Device Event Management", tags = "Device Event Management",
// extensions = { extensions = {
// @Extension(properties = { @Extension(properties = {
// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events") @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events")
// }) })
// } }
// ) )
// @ApiResponses( @ApiResponses(
// value = { value = {
// @ApiResponse( @ApiResponse(
// code = 200, code = 200,
// message = "OK. \n Successfully added the event defintion.", message = "OK. \n Successfully added the event defintion.",
// responseHeaders = { responseHeaders = {
// @ResponseHeader( @ResponseHeader(
// name = "Content-Type", name = "Content-Type",
// description = "The content type of the body"), description = "The content type of the body"),
// @ResponseHeader( @ResponseHeader(
// name = "ETag", name = "ETag",
// description = "Entity Tag of the response resource.\n" + description = "Entity Tag of the response resource.\n" +
// "Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
// @ResponseHeader( @ResponseHeader(
// name = "Last-Modified", name = "Last-Modified",
// description = description =
// "Date and time the resource was last modified.\n" + "Date and time the resource was last modified.\n" +
// "Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
// } }
// ), ),
// @ApiResponse( @ApiResponse(
// code = 400, code = 400,
// message = message =
// "Bad Request. \n"), "Bad Request. \n"),
// @ApiResponse( @ApiResponse(
// code = 406, code = 406,
// message = "Not Acceptable.\n The requested media type is not supported"), message = "Not Acceptable.\n The requested media type is not supported"),
// @ApiResponse( @ApiResponse(
// code = 500, code = 500,
// message = "Internal Server Error. \n Server error occurred while fetching the " + message = "Internal Server Error. \n Server error occurred while fetching the " +
// "list of supported device types.", "list of supported device types.",
// response = ErrorResponse.class) response = ErrorResponse.class)
// } }
// ) )
// Response deployDeviceTypeEventDefinition( Response deployDeviceTypeEventDefinition(
// @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.") @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.")
// @PathParam("type")String deviceType, @PathParam("type")String deviceType,
// @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not") @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not")
// @QueryParam("skipPersist") boolean skipPersist, @QueryParam("skipPersist") boolean skipPersist,
// @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants") @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants")
// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
// @ApiParam(name = "deviceTypeEvent", value = "Add the data to complete the DeviceTypeEvent object.", @ApiParam(name = "deviceTypeEvents", value = "Add the data to complete the DeviceTypeEvent object.",
// required = true) required = true)
// @Valid DeviceTypeEvent deviceTypeEvent); @Valid List<DeviceTypeEvent> deviceTypeEvent);
@DELETE @DELETE
@Path("/{type}") @Path("/{type}")

@ -188,6 +188,13 @@ import java.util.List;
roles = {"Internal/devicemgt-user"}, roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/owning-device/add"} permissions = {"/device-mgt/devices/owning-device/add"}
), ),
@Scope(
name = "Viewing Enrollment Guide",
description = "Show enrollment guide to users",
key = "perm:devices:enrollment-guide:view",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/enrollment-guide/view"}
),
} }
) )
@Path("/devices") @Path("/devices")
@ -802,6 +809,59 @@ public interface DeviceManagementService {
@QueryParam("requireDeviceInfo") @QueryParam("requireDeviceInfo")
boolean requireDeviceInfo); boolean requireDeviceInfo);
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/enrollment/guide")
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Sending Enrollment Mode chosen by customer",
notes = "Enrollment mode selected and path is sent as parameters",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:enrollment-guide:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully mailed the Enrollment Guide of customer.",
response = Device.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while sending mail of the Enrollment Guide.",
response = ErrorResponse.class)
})
Response sendEnrollmentGuide(
@ApiParam(
name = "enrolmentGuide",
value = "The details of the enrolment path suggested.",
required = true)
String enrolmentGuide);
@POST @POST
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/type/any/list") @Path("/type/any/list")
@ -1059,6 +1119,82 @@ public interface DeviceManagementService {
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince); String ifModifiedSince);
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/config")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the Configuration of a Device",
notes = "Get the configuration of a device by specifying the device type and device identifier.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the configuration of the device.",
response = DeviceInfo.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Location data for the specified device was not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getDeviceConfiguration(
@ApiParam(
name = "type",
value = "The device type name, such as ios, android, windows, or fire-alarm.",
required = true)
@PathParam("type")
@Size(max = 45)
String type,
@ApiParam(
name = "id",
value = "The device identifier of the device you want ot get details.",
required = true)
@PathParam("id")
@Size(max = 45)
String id,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z. \n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false)
@HeaderParam("If-Modified-Since")
String ifModifiedSince);
//device rename request would looks like follows //device rename request would looks like follows
//POST devices/type/virtual_firealarm/id/us06ww93auzp/rename //POST devices/type/virtual_firealarm/id/us06ww93auzp/rename
@POST @POST
@ -1209,7 +1345,7 @@ public interface DeviceManagementService {
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/features") @Path("/device-type/{type}/features")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
@ -1280,14 +1416,6 @@ public interface DeviceManagementService {
@PathParam("type") @PathParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam(
name = "id",
value = "The device identifier of the device.\n" +
"INFO: Make sure to add the ID of a device that is already registered with WSO2 IoTS.",
required = true)
@PathParam("id")
@Size(max = 45)
String id,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + value = "Checks if the requested variant was modified, since the specified date-time. \n" +
@ -1883,7 +2011,7 @@ public interface DeviceManagementService {
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/getstatushistory") @Path("/{type}/{id}/status-history")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
@ -1948,9 +2076,10 @@ public interface DeviceManagementService {
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
String id); String id);
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/getenrolmentstatushistory") @Path("/{type}/{id}/enrolment-status-history")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",

@ -192,6 +192,13 @@ import java.util.List;
key = "perm:groups:device", key = "perm:groups:device",
roles = {"Internal/devicemgt-user"}, roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/groups/devices/view"} permissions = {"/device-mgt/groups/devices/view"}
),
@Scope(
name = "View whether the groups has relevant device types",
description = "View whether the groups has relevant device types",
key = "perm:groups:devices-types",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/groups/devices/types"}
) )
} }
) )
@ -1185,4 +1192,58 @@ public interface GroupManagementService {
@QueryParam("requireGroupProps") @QueryParam("requireGroupProps")
boolean requireGroupProps); boolean requireGroupProps);
@Path("/device-types")
@POST
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HTTPConstants.HEADER_GET,
value = "Getting Details whether the groups has relevant device type or not",
notes = "Getting Details whether the groups has relevant device type or not.",
tags = "Device Group Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:devices-types")
})
},
nickname = "getGroupByGroupNameFilter"
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the device types of groups.",
response = DeviceGroup.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of " +
"the requested resource."),
@ApiResponse(
code = 404,
message = "Error occurred",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the group details.",
response = ErrorResponse.class)
})
Response getGroupHasDeviceTypes(
@ApiParam(
name = "identifiers",
value = "GET list of identifiers.",
required = true)
List<String> identifiers);
} }

@ -1,12 +1,30 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl; package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import edu.emory.mathcs.backport.java.util.Arrays;
import org.apache.axis2.AxisFault; import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Stub; import org.apache.axis2.client.Stub;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.velocity.util.ArrayListWrapper;
import org.json.JSONObject;
import org.opensaml.xml.signature.J;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminService;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub;
import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTable;
import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTableRecord;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.databridge.commons.StreamDefinition;
import org.wso2.carbon.databridge.commons.exception.MalformedStreamDefinitionException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.DeviceTypeEvent; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.DeviceTypeEvent;
@ -15,26 +33,50 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.TransportType;
import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceEventManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceEventManagementService;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration;
import org.wso2.carbon.event.input.adapter.core.MessageType;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.event.output.adapter.rdbms.RDBMSEventAdapter;
import org.wso2.carbon.event.output.adapter.rdbms.internal.ds.RDBMSEventAdapterServiceDS;
import org.wso2.carbon.event.processor.manager.core.EventProcessorManagementService;
import org.wso2.carbon.event.processor.manager.core.EventPublisherManagementService;
import org.wso2.carbon.event.publisher.core.EventPublisherService;
import org.wso2.carbon.event.publisher.core.config.EventPublisherConfiguration;
import org.wso2.carbon.event.publisher.core.config.mapping.JSONOutputMapping;
import org.wso2.carbon.event.publisher.core.config.mapping.MapOutputMapping;
import org.wso2.carbon.event.publisher.core.exception.EventPublisherConfigurationException;
import org.wso2.carbon.event.publisher.core.internal.ds.EventPublisherServiceDS;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceCallbackHandler; import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceCallbackHandler;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub; import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub;
import org.wso2.carbon.event.receiver.core.EventReceiverService;
import org.wso2.carbon.event.receiver.core.config.EventReceiverConfiguration;
import org.wso2.carbon.event.receiver.core.config.InputMapping;
import org.wso2.carbon.event.receiver.core.config.mapping.JSONInputMapping;
import org.wso2.carbon.event.receiver.core.config.mapping.WSO2EventInputMapping;
import org.wso2.carbon.event.receiver.core.exception.EventReceiverConfigurationException;
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceCallbackHandler; import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceCallbackHandler;
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub; import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub;
import org.wso2.carbon.event.receiver.stub.types.BasicInputAdapterPropertyDto; import org.wso2.carbon.event.receiver.stub.types.BasicInputAdapterPropertyDto;
import org.wso2.carbon.event.receiver.stub.types.EventReceiverConfigurationDto; import org.wso2.carbon.event.receiver.stub.types.EventReceiverConfigurationDto;
import org.wso2.carbon.event.receiver.stub.types.InputAdapterConfigurationDto;
import org.wso2.carbon.event.stream.core.EventStreamService;
import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException;
import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto;
import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.DELETE; import javax.validation.Valid;
import javax.ws.rs.GET; import javax.ws.rs.*;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.IOException;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
@ -173,65 +215,73 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
/** /**
* Deploy Event Stream, Receiver, Publisher and Store Configuration. * Deploy Event Stream, Receiver, Publisher and Store Configuration.
*/ */
// @POST @POST
// @Path("/{type}") @Path("/{type}")
// @Override @Override
// public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType, public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType,
// @QueryParam("skipPersist") boolean skipPersist, @QueryParam("skipPersist") boolean skipPersist,
// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
// @Valid DeviceTypeEvent deviceTypeEvent) { @Valid List<DeviceTypeEvent> deviceTypeEvents) {
// TransportType transportType = deviceTypeEvent.getTransportType();
// EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList();
// String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
// try { try {
// if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 || for (DeviceTypeEvent deviceTypeEvent : deviceTypeEvents) {
// deviceType == null || transportType == null || TransportType transportType = deviceTypeEvent.getTransportType();
// !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList();
// String errorMessage = "Invalid Payload"; String eventName = deviceTypeEvent.getEventName();
// log.error(errorMessage);
// return Response.status(Response.Status.BAD_REQUEST).build();
// } if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 ||
// String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain); deviceType == null || transportType == null ||
// String streamNameWithVersion = streamName + ":" + Constants.DEFAULT_STREAM_VERSION; !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); String errorMessage = "Invalid Payload";
// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); log.error(errorMessage);
// if (!skipPersist) { return Response.status(Response.Status.BAD_REQUEST).build();
// publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes); }
// } String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain, eventName);
// publishWebsocketPublisherDefinition(streamNameWithVersion, deviceType); publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes);
// try {
// PrivilegedCarbonContext.startTenantFlow(); String receiverName = getReceiverName(deviceType, tenantDomain, transportType, eventName);
// PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( publishEventReceivers(streamName, Constants.DEFAULT_STREAM_VERSION, transportType, tenantDomain,
// MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); isSharedWithAllTenants, deviceType, deviceTypeEvent.getEventTopicStructure(), receiverName);
// if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { if (!skipPersist) {
// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); String rdbmsPublisherName = getPublisherName(deviceType, tenantDomain, eventName) + "_rdbms_publisher";
// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, rdbmsPublisherName);
// } }
// } finally { String wsPublisherName = getPublisherName(deviceType, tenantDomain, eventName) + "_ws_publisher";
// PrivilegedCarbonContext.endTenantFlow(); publishWebsocketPublisherDefinition(streamName, Constants.DEFAULT_STREAM_VERSION, wsPublisherName);
// } try {
// return Response.ok().build(); PrivilegedCarbonContext.startTenantFlow();
// } catch (AxisFault e) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
// log.error("Failed to create event definitions for tenantDomain:" + tenantDomain, e); MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// } catch (RemoteException e) { publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes);
// log.error("Failed to connect with the remote services:" + tenantDomain, e); publishEventReceivers(streamName, Constants.DEFAULT_STREAM_VERSION, transportType, tenantDomain,
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); isSharedWithAllTenants, deviceType, deviceTypeEvent.getEventTopicStructure(), receiverName);
// } catch (JWTClientException e) { }
// log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e); } finally {
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); PrivilegedCarbonContext.endTenantFlow();
// } catch (UserStoreException e) { }
// log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e); }
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.ok().build();
// } catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
// log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e); log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
// } catch (EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException e) { } catch (MalformedStreamDefinitionException e) {
// log.error("Failed to create event store for, tenantDomain: " + tenantDomain + " deviceType" + deviceType, log.error("Failed while creating stream definition, tenantDomain: " + tenantDomain, e);
// e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } catch (EventStreamConfigurationException e) {
// } log.error("Failed while configuring stream definition, tenantDomain: " + tenantDomain, e);
// } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (EventPublisherConfigurationException e) {
log.error("Failed while configuring event publisher, tenantDomain: " + tenantDomain, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (EventReceiverConfigurationException e) {
log.error("Failed while configuring event receiver, tenantDomain: " + tenantDomain, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
/** /**
* Delete device type specific artifacts from DAS. * Delete device type specific artifacts from DAS.
@ -498,158 +548,172 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
// return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); // return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
// } // }
// } // }
private void publishEventReceivers(String streamName, String version, TransportType transportType
, String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType,
private void publishEventReceivers(String streamNameWithVersion, TransportType transportType String eventTopicStructure, String receiverName) throws EventReceiverConfigurationException {
, String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType) EventReceiverService eventReceiverService = DeviceMgtAPIUtils.getEventReceiverService();
throws RemoteException, UserStoreException, JWTClientException {
EventReceiverAdminServiceStub receiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub();
try { try {
TransportType transportTypeToBeRemoved = TransportType.HTTP; // TransportType transportTypeToBeRemoved = TransportType.HTTP;
if (transportType == TransportType.HTTP) { // if (transportType == TransportType.HTTP) {
transportTypeToBeRemoved = TransportType.MQTT; // transportTypeToBeRemoved = TransportType.MQTT;
} // }
String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved); // String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved);
EventReceiverConfigurationDto eventReceiverConfigurationDto = receiverAdminServiceStub EventReceiverConfiguration eventReceiverConfiguration =
.getActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved); eventReceiverService.getActiveEventReceiverConfiguration(receiverName);
if (eventReceiverConfigurationDto != null) { if (eventReceiverConfiguration != null) {
EventReceiverAdminServiceCallbackHandler eventReceiverAdminServiceCallbackHandler = eventReceiverService.undeployActiveEventReceiverConfiguration(receiverName);
new EventReceiverAdminServiceCallbackHandler() {
};
receiverAdminServiceStub.startundeployActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved
, eventReceiverAdminServiceCallbackHandler);
} }
String adapterType = OAUTH_MQTT_ADAPTER_TYPE; InputEventAdapterConfiguration inputEventAdapterConfiguration = new InputEventAdapterConfiguration();
BasicInputAdapterPropertyDto basicInputAdapterPropertyDtos[]; Map<String, String> propertyMap = new HashMap<>();
if (transportType == TransportType.MQTT) { if (transportType == TransportType.MQTT) {
basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[3]; inputEventAdapterConfiguration.setType(OAUTH_MQTT_ADAPTER_TYPE);
String topic; String topic;
if (!StringUtils.isEmpty(eventTopicStructure)) {
if (isSharedWithAllTenants) {
topic = eventTopicStructure.replace("${deviceId}", "+")
.replace("${deviceType}", deviceType)
.replace("${tenantDomain}", "+");
} else {
topic = eventTopicStructure.replace("${deviceId}", "+")
.replace("${deviceType}", deviceType)
.replace("${tenantDomain}", requestedTenantDomain);
}
} else {
if (isSharedWithAllTenants) { if (isSharedWithAllTenants) {
topic = "+/" + deviceType + "/+/events"; topic = "+/" + deviceType + "/+/events";
} else { } else {
topic = requestedTenantDomain + "/" + deviceType + "/+/events"; topic = requestedTenantDomain + "/" + deviceType + "/+/events";
} }
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("topic", topic); }
basicInputAdapterPropertyDtos[1] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_TRANSFORMER_TYPE propertyMap.put("topic", topic);
, MQTT_CONTENT_TRANSFORMER); propertyMap.put(MQTT_CONTENT_TRANSFORMER_TYPE, MQTT_CONTENT_TRANSFORMER);
basicInputAdapterPropertyDtos[2] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_VALIDATOR_TYPE propertyMap.put(MQTT_CONTENT_VALIDATOR_TYPE, MQTT_CONTENT_VALIDATOR);
, MQTT_CONTENT_VALIDATOR);
} else { } else {
adapterType = THRIFT_ADAPTER_TYPE; inputEventAdapterConfiguration.setType(THRIFT_ADAPTER_TYPE);
basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[1]; propertyMap.put("events.duplicated.in.cluster", "false");
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("events.duplicated.in.cluster", "false");
} }
String eventRecieverName = getReceiverName(deviceType, requestedTenantDomain, transportType); inputEventAdapterConfiguration.setProperties(propertyMap);
if (receiverAdminServiceStub.getActiveEventReceiverConfiguration(eventRecieverName) == null) {
if (eventReceiverService.getActiveEventReceiverConfiguration(receiverName) == null) {
EventReceiverConfiguration configuration = new EventReceiverConfiguration();
configuration.setEventReceiverName(receiverName);
configuration.setToStreamName(streamName);
configuration.setToStreamVersion(version);
configuration.setFromAdapterConfiguration(inputEventAdapterConfiguration);
if (transportType == TransportType.MQTT) { if (transportType == TransportType.MQTT) {
receiverAdminServiceStub.deployJsonEventReceiverConfiguration(eventRecieverName, streamNameWithVersion JSONInputMapping jsonInputMapping = new JSONInputMapping();
, adapterType, null, basicInputAdapterPropertyDtos, false); jsonInputMapping.setCustomMappingEnabled(false);
configuration.setInputMapping(jsonInputMapping);
eventReceiverService.deployEventReceiverConfiguration(configuration);
} else { } else {
receiverAdminServiceStub.deployWso2EventReceiverConfiguration(eventRecieverName, streamNameWithVersion WSO2EventInputMapping wso2EventInputMapping = new WSO2EventInputMapping();
, adapterType, null, null, null, basicInputAdapterPropertyDtos, false, null); wso2EventInputMapping.setCustomMappingEnabled(false);
configuration.setInputMapping(wso2EventInputMapping);
eventReceiverService.deployEventReceiverConfiguration(configuration);
} }
} }
} finally { } catch (EventReceiverConfigurationException e) {
cleanup(receiverAdminServiceStub); log.error("Error while publishing event receiver" , e);
throw new EventReceiverConfigurationException(e);
} }
} }
private void publishStreamDefinitons(String streamName, String version, String deviceType private void publishStreamDefinitons(String streamName, String version, EventAttributeList eventAttributes)
, EventAttributeList eventAttributes) throws MalformedStreamDefinitionException, EventStreamConfigurationException {
throws RemoteException, UserStoreException, JWTClientException { EventStreamService eventStreamService = DeviceMgtAPIUtils.getEventStreamService();
EventStreamAdminServiceStub eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
try { try {
EventStreamDefinitionDto eventStreamDefinitionDto = new EventStreamDefinitionDto(); StreamDefinition streamDefinition = new StreamDefinition(streamName, version);
eventStreamDefinitionDto.setName(streamName);
eventStreamDefinitionDto.setVersion(version); List<org.wso2.carbon.databridge.commons.Attribute> payloadDataAttributes = new ArrayList<>();
EventStreamAttributeDto eventStreamAttributeDtos[] =
new EventStreamAttributeDto[eventAttributes.getList().size()];
EventStreamAttributeDto metaStreamAttributeDtos[] =
new EventStreamAttributeDto[1];
int i = 0;
for (Attribute attribute : eventAttributes.getList()) { for (Attribute attribute : eventAttributes.getList()) {
EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto(); payloadDataAttributes.add(new org.wso2.carbon.databridge.commons.Attribute(attribute.getName(),
eventStreamAttributeDto.setAttributeName(attribute.getName()); org.wso2.carbon.databridge.commons.AttributeType.valueOf(attribute.getType().name())));
eventStreamAttributeDto.setAttributeType(attribute.getType().toString()); }
eventStreamAttributeDtos[i] = eventStreamAttributeDto; streamDefinition.setPayloadData(payloadDataAttributes);
i++;
} List<org.wso2.carbon.databridge.commons.Attribute> metaDataAttributes = new ArrayList<>();
metaDataAttributes.add(new org.wso2.carbon.databridge.commons.Attribute(DEFAULT_DEVICE_ID_ATTRIBUTE,
EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto(); org.wso2.carbon.databridge.commons.AttributeType.STRING));
eventStreamAttributeDto.setAttributeName(DEFAULT_DEVICE_ID_ATTRIBUTE); streamDefinition.setMetaData(metaDataAttributes);
eventStreamAttributeDto.setAttributeType(AttributeType.STRING.toString());
metaStreamAttributeDtos[0] = eventStreamAttributeDto; if (eventStreamService.getStreamDefinition(streamDefinition.getStreamId()) != null) {
eventStreamDefinitionDto.setPayloadData(eventStreamAttributeDtos); eventStreamService.removeEventStreamDefinition(streamName, version);
eventStreamDefinitionDto.setMetaData(metaStreamAttributeDtos); eventStreamService.addEventStreamDefinition(streamDefinition);
String streamId = streamName + ":" + version;
if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamId) != null) {
eventStreamAdminServiceStub.editEventStreamDefinitionAsDto(eventStreamDefinitionDto, streamId);
} else { } else {
eventStreamAdminServiceStub.addEventStreamDefinitionAsDto(eventStreamDefinitionDto); eventStreamService.addEventStreamDefinition(streamDefinition);
} }
} finally {
cleanup(eventStreamAdminServiceStub); } catch (MalformedStreamDefinitionException e) {
log.error("Error while initializing stream definition " , e);
throw new MalformedStreamDefinitionException(e);
} catch (EventStreamConfigurationException e) {
log.error("Error while configuring stream definition " , e);
throw new EventStreamConfigurationException(e);
} }
} }
/*
// private void publishEventStore(String streamName, String version, EventAttributeList eventAttributes) */
// throws RemoteException, UserStoreException, JWTClientException,
// EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException { private void publishEventStore(String streamName, String version, String publisherName)
// EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub = throws EventPublisherConfigurationException {
// DeviceMgtAPIUtils.getEventStreamPersistenceAdminServiceStub();
// try { EventPublisherService eventPublisherService = DeviceMgtAPIUtils.getEventPublisherService();
// AnalyticsTable analyticsTable = new AnalyticsTable();
// analyticsTable.setRecordStoreName(DEFAULT_EVENT_STORE_NAME);
// analyticsTable.setStreamVersion(version);
// analyticsTable.setTableName(streamName);
// analyticsTable.setMergeSchema(false);
// analyticsTable.setPersist(true);
// AnalyticsTableRecord analyticsTableRecords[] = new AnalyticsTableRecord[eventAttributes.getList().size() + 1];
// int i = 0;
// for (Attribute attribute : eventAttributes.getList()) {
// AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord();
// analyticsTableRecord.setColumnName(attribute.getName());
// analyticsTableRecord.setColumnType(attribute.getType().toString().toUpperCase());
// analyticsTableRecord.setFacet(false);
// analyticsTableRecord.setIndexed(false);
// analyticsTableRecord.setPersist(true);
// analyticsTableRecord.setPrimaryKey(false);
// analyticsTableRecord.setScoreParam(false);
// analyticsTableRecords[i] = analyticsTableRecord;
// i++;
// }
// AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord();
// analyticsTableRecord.setColumnName(DEFAULT_META_DEVICE_ID_ATTRIBUTE);
// analyticsTableRecord.setColumnType(AttributeType.STRING.toString().toUpperCase());
// analyticsTableRecord.setFacet(false);
// analyticsTableRecord.setIndexed(true);
// analyticsTableRecord.setPersist(true);
// analyticsTableRecord.setPrimaryKey(false);
// analyticsTableRecord.setScoreParam(false);
// analyticsTableRecords[i] = analyticsTableRecord;
// analyticsTable.setAnalyticsTableRecords(analyticsTableRecords);
// eventStreamPersistenceAdminServiceStub.addAnalyticsTable(analyticsTable);
// } finally {
// cleanup(eventStreamPersistenceAdminServiceStub);
// }
// }
private void publishWebsocketPublisherDefinition(String streamNameWithVersion, String deviceType)
throws RemoteException, UserStoreException, JWTClientException {
EventPublisherAdminServiceStub eventPublisherAdminServiceStub = DeviceMgtAPIUtils
.getEventPublisherAdminServiceStub();
try { try {
String eventPublisherName = deviceType.trim().replace(" ", "_") + "_websocket_publisher"; if (eventPublisherService.getActiveEventPublisherConfiguration(publisherName) == null) {
if (eventPublisherAdminServiceStub.getActiveEventPublisherConfiguration(eventPublisherName) == null) { EventPublisherConfiguration configuration = new EventPublisherConfiguration();
eventPublisherAdminServiceStub.deployJsonEventPublisherConfiguration(eventPublisherName configuration.setEventPublisherName(publisherName);
, streamNameWithVersion, DEFAULT_WEBSOCKET_PUBLISHER_ADAPTER_TYPE, null, null configuration.setFromStreamName(streamName);
, null, false); configuration.setFromStreamVersion(version);
MapOutputMapping mapOutputMapping = new MapOutputMapping();
mapOutputMapping.setCustomMappingEnabled(false);
configuration.setOutputMapping(mapOutputMapping);
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setType("rdbms");
Map<String, String> staticProperties = new HashMap<>();
staticProperties.put("datasource.name", "EVENT_DB");
staticProperties.put("execution.mode", "insert");
staticProperties.put("table.name", "table_" + publisherName.replace(".", ""));
outputEventAdapterConfiguration.setStaticProperties(staticProperties);
configuration.setProcessEnabled(true);
configuration.setToAdapterConfiguration(outputEventAdapterConfiguration);
eventPublisherService.deployEventPublisherConfiguration(configuration);
}
} catch (EventPublisherConfigurationException e) {
log.error("Error while publishing to rdbms store" , e);
throw new EventPublisherConfigurationException(e);
}
}
private void publishWebsocketPublisherDefinition(String streamName, String version, String publisherName)
throws EventPublisherConfigurationException {
EventPublisherService eventPublisherService = DeviceMgtAPIUtils.getEventPublisherService();
try {
if (eventPublisherService.getActiveEventPublisherConfiguration(publisherName) == null) {
EventPublisherConfiguration configuration = new EventPublisherConfiguration();
configuration.setEventPublisherName(publisherName);
configuration.setFromStreamName(streamName);
configuration.setFromStreamVersion(version);
JSONOutputMapping jsonOutputMapping = new JSONOutputMapping();
jsonOutputMapping.setCustomMappingEnabled(false);
configuration.setOutputMapping(jsonOutputMapping);
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setType("websocket-local");
configuration.setToAdapterConfiguration(outputEventAdapterConfiguration);
eventPublisherService.deployEventPublisherConfiguration(configuration);
} }
} finally { } catch (EventPublisherConfigurationException e) {
cleanup(eventPublisherAdminServiceStub); log.error("Error while publishing to websocket-local" , e);
throw new EventPublisherConfigurationException(e);
} }
} }
private BasicInputAdapterPropertyDto getBasicInputAdapterPropertyDto(String key, String value) { private BasicInputAdapterPropertyDto getBasicInputAdapterPropertyDto(String key, String value) {
@ -667,6 +731,13 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
return deviceType.replace(" ", "_").trim() + "-" + tenantDomain + "-" + transportType.toString() + "-receiver"; return deviceType.replace(" ", "_").trim() + "-" + tenantDomain + "-" + transportType.toString() + "-receiver";
} }
private String getReceiverName(String deviceType, String tenantDomain, TransportType transportType, String eventName) {
return eventName + "-" + getReceiverName(deviceType, tenantDomain, transportType);
}
private String getPublisherName(String tenantDomain, String deviceType, String eventName) {
return eventName + "_" + tenantDomain.replace(".", "_") + "_" + deviceType;
}
private void cleanup(Stub stub) { private void cleanup(Stub stub) {
if (stub != null) { if (stub != null) {

@ -37,33 +37,26 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl; package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.entgra.application.mgt.common.ApplicationInstallResponse;
import io.entgra.application.mgt.common.SubscriptionType;
import io.entgra.application.mgt.common.exception.SubscriptionManagementException;
import io.entgra.application.mgt.common.services.ApplicationManager; import io.entgra.application.mgt.common.services.ApplicationManager;
import io.entgra.application.mgt.common.services.SubscriptionManager;
import io.entgra.application.mgt.core.util.HelperUtil;
import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.apimgt.keymgt.extension.DCRResponse;
import org.wso2.carbon.apimgt.keymgt.extension.TokenRequest;
import org.wso2.carbon.apimgt.keymgt.extension.TokenResponse;
import org.wso2.carbon.apimgt.keymgt.extension.exception.KeyMgtException;
import org.wso2.carbon.apimgt.keymgt.extension.service.KeyMgtService;
import org.wso2.carbon.apimgt.keymgt.extension.service.KeyMgtServiceImpl;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.application.mgt.common.ApplicationInstallResponse; import org.wso2.carbon.device.mgt.common.*;
import io.entgra.application.mgt.common.SubscriptionType;
import io.entgra.application.mgt.common.exception.SubscriptionManagementException;
import io.entgra.application.mgt.common.services.SubscriptionManager;
import io.entgra.application.mgt.core.util.HelperUtil;
import org.wso2.carbon.device.mgt.common.DeviceFilters;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.OperationLogFilters;
import org.wso2.carbon.device.mgt.common.MDMAppConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.Device;
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.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo;
import org.wso2.carbon.device.mgt.common.app.mgt.Application; 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.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
@ -72,12 +65,8 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; 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.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException; import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException;
import org.wso2.carbon.device.mgt.common.exceptions.UnAuthorizedException; import org.wso2.carbon.device.mgt.common.exceptions.*;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
@ -91,6 +80,8 @@ import org.wso2.carbon.device.mgt.common.search.PropertyMap;
import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; 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.core.device.details.mgt.DeviceInformationManager;
@ -103,19 +94,10 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.*;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationList;
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationStatusBean;
import org.wso2.carbon.device.mgt.jaxrs.beans.ComplianceDeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationRequest;
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationUninstallation;
import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
@ -128,29 +110,17 @@ import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerSer
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.validation.Valid; import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.DELETE; import javax.ws.rs.*;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.ArrayList;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
@ -616,9 +586,13 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier
(deviceId, deviceType), true); (deviceId, deviceType), true);
persistedDevice.setName(device.getName()); persistedDevice.setName(device.getName());
boolean response = deviceManagementProviderService.modifyEnrollment(persistedDevice); System.out.println("This is rename device");
return Response.status(Response.Status.CREATED).entity(response).build(); boolean responseOfmodifyEnrollment = deviceManagementProviderService.modifyEnrollment(persistedDevice);
boolean responseOfDeviceNameChanged = deviceManagementProviderService.sendDeviceNameChangedNotification(
persistedDevice);
boolean response = responseOfmodifyEnrollment && responseOfDeviceNameChanged;
return Response.status(Response.Status.CREATED).entity(response).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error("Error encountered while updating device of type : " + deviceType + " and " + log.error("Error encountered while updating device of type : " + deviceType + " and " +
"ID : " + deviceId); "ID : " + deviceId);
@ -812,6 +786,32 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.OK).entity(device).build(); return Response.status(Response.Status.OK).entity(device).build();
} }
@POST
@Path("/enrollment/guide")
@Override
public Response sendEnrollmentGuide(String enrolmentGuide) {
if (log.isDebugEnabled()) {
log.debug("Sending enrollment invitation mail to existing user.");
}
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
if (!config.getEnrollmentGuideConfiguration().isEnabled()) {
String msg = "Sending enrollment guide config is not enabled.";
log.error(msg);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
}
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
try {
dms.sendEnrolmentGuide(enrolmentGuide);
return Response.status(Response.Status.OK).entity("Invitation mails have been sent.").build();
} catch (DeviceManagementException e) {
String msg = "Error occurred sending mail to group in enrollment guide";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@POST @POST
@Path("/type/any/list") @Path("/type/any/list")
@Override @Override
@ -883,19 +883,118 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} }
return Response.status(Response.Status.OK).entity(deviceInfo).build(); return Response.status(Response.Status.OK).entity(deviceInfo).build();
}
@GET
@Path("/{type}/{id}/config")
@Override
public Response getDeviceConfiguration(
@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
DeviceConfig deviceConfig = new DeviceConfig();
deviceConfig.setDeviceId(id);
deviceConfig.setType(type);
// find token validity time
DeviceManagementProviderService deviceManagementProviderService =
DeviceMgtAPIUtils.getDeviceManagementService();
int validityTime = 3600;
// add scopes for event topics
List<String> mqttEventTopicStructure = new ArrayList<>();
try {
DeviceType deviceType = deviceManagementProviderService.getDeviceType(type);
if (deviceType != null) {
if (deviceType.getDeviceTypeMetaDefinition().isLongLivedToken()) {
validityTime = Integer.MAX_VALUE;
}
mqttEventTopicStructure = deviceType.getDeviceTypeMetaDefinition().getMqttEventTopicStructures();
} else {
String msg = "Device not found, device id : " + id + ", device type : " + type;
log.error(msg);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving device, device id : " + id + ", device type : " + type;
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String applicationName = type.replace(" ", "").replace("_", "")
+ "_" + tenantDomain;
KeyMgtService keyMgtService = new KeyMgtServiceImpl();
try {
DCRResponse dcrResponse = keyMgtService.dynamicClientRegistration(applicationName, username,
"client_credentials", null, new String[] {"device_management"}, false, validityTime);
deviceConfig.setClientId(dcrResponse.getClientId());
deviceConfig.setClientSecret(dcrResponse.getClientSecret());
StringBuilder scopes = new StringBuilder("device_" + type.replace(" ", "")
.replace("_", "") + "_" + id);
for (String topic : mqttEventTopicStructure) {
if (topic.contains("${deviceId}")) {
topic = topic.replace("${deviceId}", id);
}
topic = topic.replace("/",":");
// scopes.append(" perm:topic:sub:".concat(topic));
scopes.append(" perm:topic:pub:".concat(topic));
}
// add scopes for retrieve operation topic /tenantDomain/deviceType/deviceId/operation/#
scopes.append(" perm:topic:sub:" + tenantDomain + ":" + type + ":" + id + ":operation");
// add scopes for update operation /tenantDomain/deviceType/deviceId/update/operation
scopes.append(" perm:topic:pub:" + tenantDomain + ":" + type + ":" + id + ":update:operation");
TokenRequest tokenRequest = new TokenRequest(dcrResponse.getClientId(), dcrResponse.getClientSecret(),
null, scopes.toString(), "client_credentials", null,
null, null, null, validityTime);
TokenResponse tokenResponse = keyMgtService.generateAccessToken(tokenRequest);
deviceConfig.setAccessToken(tokenResponse.getAccessToken());
deviceConfig.setRefreshToken(tokenResponse.getRefreshToken());
try {
deviceConfig.setPlatformConfiguration(deviceManagementProviderService.getConfiguration(type));
} catch (DeviceManagementException e) {
String msg = "Error occurred while reading platform configurations token, device id : " + id + ", device type : " + type;
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
deviceConfig.setMqttGateway("tcp://" + System.getProperty("mqtt.broker.host") + ":" + System.getProperty("mqtt.broker.port"));
deviceConfig.setHttpGateway("http://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.http.port"));
deviceConfig.setHttpsGateway("https://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.https.port"));
} catch (KeyMgtException e) {
String msg = "Error occurred while creating oauth application, device id : " + id + ", device type : " + type;
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (org.wso2.carbon.apimgt.keymgt.extension.exception.BadRequestException e) {
String msg = "Error occurred while generating token, device id : " + id + ", device type : " + type;
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.OK).entity(deviceConfig).build();
} }
@GET @GET
@Path("/{type}/{id}/features") @Path("/device-type/{type}/features")
@Override @Override
public Response getFeaturesOfDevice( public Response getFeaturesOfDevice(
@PathParam("type") @Size(max = 45) String type, @PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) { @HeaderParam("If-Modified-Since") String ifModifiedSince) {
List<Feature> features = new ArrayList<>(); List<Feature> features = new ArrayList<>();
DeviceManagementProviderService dms; DeviceManagementProviderService dms;
try { try {
RequestValidationUtil.validateDeviceIdentifier(type, id);
dms = DeviceMgtAPIUtils.getDeviceManagementService(); dms = DeviceMgtAPIUtils.getDeviceManagementService();
FeatureManager fm; FeatureManager fm;
try { try {
@ -909,8 +1008,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
features = fm.getFeatures(); features = fm.getFeatures();
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving the list of features of '" + type + "' device, which " + String msg = "Error occurred while retrieving the list of features of '" + type + "'";
"carries the id '" + id + "'";
log.error(msg, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
@ -1261,7 +1359,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
* @return {@link Response} object * @return {@link Response} object
*/ */
@GET @GET
@Path("/{type}/{id}/getstatushistory") @Path("/{type}/{id}/status-history")
public Response getDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type, public Response getDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id) { @PathParam("id") @Size(max = 45) String id) {
//TODO check authorization for this //TODO check authorization for this
@ -1293,7 +1391,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
* @return {@link Response} object * @return {@link Response} object
*/ */
@GET @GET
@Path("/{type}/{id}/getenrolmentstatushistory") @Path("/{type}/{id}/enrolment-status-history")
public Response getCurrentEnrolmentDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type, public Response getCurrentEnrolmentDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id) { @PathParam("id") @Size(max = 45) String id) {
//TODO check authorization for this or current enrolment should be based on for the enrolment associated with the user //TODO check authorization for this or current enrolment should be based on for the enrolment associated with the user

@ -48,6 +48,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; 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.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceTypesOfGroups;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException;
@ -66,6 +67,7 @@ import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import javax.ws.rs.DefaultValue; import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@ -429,4 +431,20 @@ public class GroupManagementServiceImpl implements GroupManagementService {
} }
} }
@POST
@Path("/device-types")
@Override
public Response getGroupHasDeviceTypes(List<String> identifiers) {
try {
DeviceTypesOfGroups deviceTypesOfGroups = DeviceMgtAPIUtils.getGroupManagementProviderService()
.getDeviceTypesOfGroups(identifiers);
return Response.status(Response.Status.OK).entity(deviceTypesOfGroups).build();
} catch (GroupManagementException e) {
String msg = "Only numbers can exists in a group ID or Invalid Group ID provided.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
} }

@ -50,15 +50,12 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI; import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub; import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
@ -96,8 +93,11 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventAttributeList;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub;
import org.wso2.carbon.event.publisher.core.EventPublisherService;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub; import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub;
import org.wso2.carbon.event.receiver.core.EventReceiverService;
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub; import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub;
import org.wso2.carbon.event.stream.core.EventStreamService;
import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
import org.wso2.carbon.identity.claim.metadata.mgt.dto.ClaimPropertyDTO; import org.wso2.carbon.identity.claim.metadata.mgt.dto.ClaimPropertyDTO;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient; import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
@ -112,11 +112,7 @@ import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.api.AuthorizationManager; import org.wso2.carbon.user.api.*;
import org.wso2.carbon.user.api.RealmConfiguration;
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.jdbc.JDBCUserStoreManager; import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.mgt.common.UIPermissionNode; import org.wso2.carbon.user.mgt.common.UIPermissionNode;
@ -129,11 +125,7 @@ import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.security.KeyManagementException; import java.security.*;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
@ -173,7 +165,7 @@ public class DeviceMgtAPIUtils {
private static KeyStore trustStore; private static KeyStore trustStore;
private static char[] keyStorePassword; private static char[] keyStorePassword;
// private static IntegrationClientService integrationClientService; // private static IntegrationClientService integrationClientService;
private static MetadataManagementService metadataManagementService; private static MetadataManagementService metadataManagementService;
private static WhiteLabelManagementService whiteLabelManagementService; private static WhiteLabelManagementService whiteLabelManagementService;
private static OTPManagementService otpManagementService; private static OTPManagementService otpManagementService;
@ -605,6 +597,36 @@ public class DeviceMgtAPIUtils {
return geoService; return geoService;
} }
public static EventStreamService getEventStreamService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventStreamService
eventStreamService = (EventStreamService) ctx.getOSGiService(EventStreamService.class, null);
if (eventStreamService == null) {
throw new IllegalStateException("Event Stream Service has not been initialized.");
}
return eventStreamService;
}
public static EventReceiverService getEventReceiverService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventReceiverService
eventReceiverService = (EventReceiverService) ctx.getOSGiService(EventReceiverService.class, null);
if (eventReceiverService == null) {
throw new IllegalStateException("Event Receiver Service has not been initialized.");
}
return eventReceiverService;
}
public static EventPublisherService getEventPublisherService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventPublisherService
eventPublisherService = (EventPublisherService) ctx.getOSGiService(EventPublisherService.class, null);
if (eventPublisherService == null) {
throw new IllegalStateException("Event Receiver Service has not been initialized.");
}
return eventPublisherService;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() { public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI = AnalyticsDataAPI analyticsDataAPI =
@ -666,10 +688,13 @@ public class DeviceMgtAPIUtils {
// return eventsPublisherService; // return eventsPublisherService;
// } // }
public static String getStreamDefinition(String deviceType, String tenantDomain, String eventName) {
return getStreamDefinition(deviceType, tenantDomain) + "." + eventName;
}
public static String getStreamDefinition(String deviceType, String tenantDomain) { public static String getStreamDefinition(String deviceType, String tenantDomain) {
return STREAM_DEFINITION_PREFIX + tenantDomain + "." + deviceType.replace(" ", "."); return STREAM_DEFINITION_PREFIX + tenantDomain + "." + deviceType.replace(" ", ".");
} }
public static EventStreamAdminServiceStub getEventStreamAdminServiceStub() public static EventStreamAdminServiceStub getEventStreamAdminServiceStub()
throws AxisFault, UserStoreException, JWTClientException { throws AxisFault, UserStoreException, JWTClientException {
EventStreamAdminServiceStub eventStreamAdminServiceStub = new EventStreamAdminServiceStub( EventStreamAdminServiceStub eventStreamAdminServiceStub = new EventStreamAdminServiceStub(

@ -590,7 +590,7 @@ public class DeviceManagementServiceImplTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); .getFeaturesOfDevice(TEST_DEVICE_TYPE, null);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
} }
@ -601,7 +601,7 @@ public class DeviceManagementServiceImplTest {
Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())) Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString()))
.thenThrow(new DeviceTypeNotFoundException()); .thenThrow(new DeviceTypeNotFoundException());
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); .getFeaturesOfDevice(TEST_DEVICE_TYPE, null);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
Mockito.reset(this.deviceManagementProviderService); Mockito.reset(this.deviceManagementProviderService);
} }

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -44,6 +44,7 @@ public class PaginationRequest {
private Map<String, Object> property = new HashMap<>(); private Map<String, Object> property = new HashMap<>();
private List<String> statusList = new ArrayList<>(); private List<String> statusList = new ArrayList<>();
private OperationLogFilters operationLogFilters = new OperationLogFilters(); private OperationLogFilters operationLogFilters = new OperationLogFilters();
private List<SortColumn> sortColumn = new ArrayList<>();
public OperationLogFilters getOperationLogFilters() { public OperationLogFilters getOperationLogFilters() {
return operationLogFilters; return operationLogFilters;
} }
@ -172,11 +173,38 @@ public class PaginationRequest {
this.filter = filter; this.filter = filter;
} }
public void setSortColumn(List<SortColumn> sortColumn) { this.sortColumn = sortColumn; }
public List<SortColumn> getSortColumn() { return sortColumn; }
/**
* Convert SortColumns field parameter and splitting string into columnName and sortType
*
* @param sortColumns which is separated by a colon(:) and first will be the columnNane and the second will be type ASC or DESC,
* if there is no colon(:) detected, ASC will be default
* (Ex: sort=col1:ASC&sort=col2:DESC, sort=col1&sort=col2:DESC)
* @return sortColumnList as a list of sortColumn
*/
public void setSortColumns(List<String> sortColumns) {
List<SortColumn> sortColumnList = new ArrayList<>();
SortColumn sortColumn;
String[] sorting;
for (String sortBy: sortColumns) {
sortColumn = new SortColumn();
sorting = sortBy.split(":");
sortColumn.setName(sorting[0]);
sortColumn.setType(sorting.length >= 2 && (sorting[1].equalsIgnoreCase("desc"))
? SortColumn.types.DESC : SortColumn.types.ASC);
sortColumnList.add(sortColumn);
}
setSortColumn(sortColumnList);
}
@Override @Override
public String toString() { public String toString() {
return "Device type '" + this.deviceType + "' Device Name '" + this.deviceName + "' row count: " + this.rowCount return "Device type '" + this.deviceType + "' Device Name '" + this.deviceName + "' row count: " + this.rowCount
+ " Owner role '" + this.ownerRole + "' owner pattern '" + this.ownerPattern + "' ownership " + " Owner role '" + this.ownerRole + "' owner pattern '" + this.ownerPattern + "' ownership "
+ this.ownership + "' Status '" + this.statusList + "' owner '" + this.owner + "' groupId: " + this.groupId + this.ownership + "' Status '" + this.statusList + "' owner '" + this.owner + "' groupId: " + this.groupId
+ " start index: " + this.startIndex; + " start index: " + this.startIndex + ", SortColumns: " + this.sortColumn;
} }
} }

@ -0,0 +1,62 @@
/*
* Copyright (c) 2023, Entgra (pvt) Ltd. (https://entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common;
/**
* This class holds required parameters for a querying a sort by column in pagination.
*
*/
public class SortColumn {
String name;
SortColumn.types type;
public enum types {
ASC, DESC
}
/**
* ColumnName setter method
* @param name of the column
*/
public void setName(String name) { this.name = name; }
/**
* get the name of the column
* @return name
*/
public String getName() { return name; }
/**
* Column sort type
* @param type of sort as ASC or DESC
*/
public void setType(SortColumn.types type) { this.type = type; }
/**
* get column sort type
* @return type of sort
*/
public SortColumn.types getType() { return type; }
@Override
public String toString() {
return "Column Name - " + this.name + ", Type - " + this.type ;
}
}

@ -0,0 +1,60 @@
/*
* Copyright (c) 2022, Entgra (pvt) Ltd. (https://entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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.group.mgt;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@ApiModel(value = "DeviceTypesOfGroups", description = "This class carries whether the groups has device type or not.")
public class DeviceTypesOfGroups implements Serializable {
private static final long serialVersionUID = 5562356373277828099L;
@ApiModelProperty(name = "hasAndroid", value = "groups has Android devices.")
private boolean hasAndroid;
@ApiModelProperty(name = "id", value = "groups has iOS devices.")
private boolean hasIos;
@ApiModelProperty(name = "hasAndroid", value = "groups has Windows devices.")
private boolean hasWindows;
public boolean isHasAndroid() {
return hasAndroid;
}
public void setHasAndroid(boolean hasAndroid) {
this.hasAndroid = hasAndroid;
}
public boolean isHasIos() {
return hasIos;
}
public void setHasIos(boolean hasIos) {
this.hasIos = hasIos;
}
public boolean isHasWindows() {
return hasWindows;
}
public void setHasWindows(boolean hasWindows) {
this.hasWindows = hasWindows;
}
}

@ -5,6 +5,7 @@ import org.wso2.carbon.device.mgt.common.InitialOperationConfig;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class DeviceTypeMetaDefinition { public class DeviceTypeMetaDefinition {
@ -19,6 +20,10 @@ public class DeviceTypeMetaDefinition {
private String description; private String description;
private boolean isSharedWithAllTenants; private boolean isSharedWithAllTenants;
private List<String> mqttEventTopicStructures;
private boolean longLivedToken = false;
public String getDescription() { public String getDescription() {
return description; return description;
} }
@ -83,4 +88,20 @@ public class DeviceTypeMetaDefinition {
public void setSharedWithAllTenants(boolean sharedWithAllTenants) { public void setSharedWithAllTenants(boolean sharedWithAllTenants) {
isSharedWithAllTenants = sharedWithAllTenants; isSharedWithAllTenants = sharedWithAllTenants;
} }
public List<String> getMqttEventTopicStructures() {
return mqttEventTopicStructures;
}
public void setMqttEventTopicStructures(List<String> mqttEventTopicStructures) {
this.mqttEventTopicStructures = mqttEventTopicStructures;
}
public boolean isLongLivedToken() {
return longLivedToken;
}
public void setLongLivedToken(boolean longLivedToken) {
this.longLivedToken = longLivedToken;
}
} }

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -103,6 +103,7 @@
org.wso2.carbon.ndatasource.core, org.wso2.carbon.ndatasource.core,
org.wso2.carbon.ntask.core.*, org.wso2.carbon.ntask.core.*,
org.wso2.carbon.ntask.common, org.wso2.carbon.ntask.common,
io.entgra.task.mgt.common.*,
org.apache.commons.collections;version="${commons-collections.version.range}", org.apache.commons.collections;version="${commons-collections.version.range}",
org.wso2.carbon.email.sender.*, org.wso2.carbon.email.sender.*,
io.swagger.annotations.*;resolution:=optional, io.swagger.annotations.*;resolution:=optional,
@ -112,7 +113,9 @@
org.wso2.carbon.event.processor.stub, org.wso2.carbon.event.processor.stub,
org.wso2.carbon.identity.jwt.client.extension.service, org.wso2.carbon.identity.jwt.client.extension.service,
org.apache.commons.codec.binary, org.apache.commons.codec.binary,
io.entgra.server.bootup.heartbeat.beacon io.entgra.server.bootup.heartbeat.beacon,
io.entgra.device.mgt.extensions.logger.*,
io.entgra.notification.logger.*
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.device.mgt.core.internal, !org.wso2.carbon.device.mgt.core.internal,
@ -347,6 +350,14 @@
<artifactId>okhttp</artifactId> <artifactId>okhttp</artifactId>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.task.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.notification.logger</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

@ -136,6 +136,7 @@ public final class DeviceManagementConstants {
public static final String POLICY_VIOLATE_TEMPLATE = "policy-violating-notifier"; public static final String POLICY_VIOLATE_TEMPLATE = "policy-violating-notifier";
public static final String USER_WELCOME_TEMPLATE = "user-welcome"; public static final String USER_WELCOME_TEMPLATE = "user-welcome";
public static final String DEFAULT_ENROLLMENT_TEMPLATE = "default-enrollment-invitation"; public static final String DEFAULT_ENROLLMENT_TEMPLATE = "default-enrollment-invitation";
public static final String ENROLLMENT_GUIDE_TEMPLATE = "enrollment-guide";
} }
public static final class OperationAttributes { public static final class OperationAttributes {

@ -24,4 +24,6 @@ public class Constants {
public static final String URI_SEPARATOR = "/"; public static final String URI_SEPARATOR = "/";
public static final String BASIC_AUTH_HEADER_PREFIX = "Basic "; public static final String BASIC_AUTH_HEADER_PREFIX = "Basic ";
public static final String BEARER = "Bearer "; public static final String BEARER = "Bearer ";
public static final String SEND_USERNAME = "SEND_USERNAME";
} }

@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.core.config.cache.BillingCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.GeoFenceCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.GeoFenceCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.enrollment.guide.EnrollmentGuideConfiguration;
import org.wso2.carbon.device.mgt.core.config.operation.timeout.OperationTimeoutConfiguration; import org.wso2.carbon.device.mgt.core.config.operation.timeout.OperationTimeoutConfiguration;
import org.wso2.carbon.device.mgt.core.config.metadata.mgt.MetaDataConfiguration; import org.wso2.carbon.device.mgt.core.config.metadata.mgt.MetaDataConfiguration;
import org.wso2.carbon.device.mgt.core.event.config.EventOperationTaskConfiguration; import org.wso2.carbon.device.mgt.core.event.config.EventOperationTaskConfiguration;
@ -72,6 +73,7 @@ public final class DeviceManagementConfig {
private DefaultRoles defaultRoles; private DefaultRoles defaultRoles;
private OperationTimeoutConfiguration operationTimeoutConfiguration; private OperationTimeoutConfiguration operationTimeoutConfiguration;
private MetaDataConfiguration metaDataConfiguration; private MetaDataConfiguration metaDataConfiguration;
private EnrollmentGuideConfiguration enrollmentGuideConfiguration;
@XmlElement(name = "ManagementRepository", required = true) @XmlElement(name = "ManagementRepository", required = true)
public DeviceManagementConfigRepository getDeviceManagementConfigRepository() { public DeviceManagementConfigRepository getDeviceManagementConfigRepository() {
@ -276,5 +278,14 @@ public final class DeviceManagementConfig {
public void setMetaDataConfiguration(MetaDataConfiguration metaDataConfiguration) { public void setMetaDataConfiguration(MetaDataConfiguration metaDataConfiguration) {
this.metaDataConfiguration = metaDataConfiguration; this.metaDataConfiguration = metaDataConfiguration;
} }
@XmlElement(name = "EnrollmentGuideConfiguration", required = true)
public EnrollmentGuideConfiguration getEnrollmentGuideConfiguration() {
return enrollmentGuideConfiguration;
}
public void setEnrollmentGuideConfiguration(EnrollmentGuideConfiguration enrollmentGuideConfiguration) {
this.enrollmentGuideConfiguration = enrollmentGuideConfiguration;
}
} }

@ -0,0 +1,30 @@
package org.wso2.carbon.device.mgt.core.config.enrollment.guide;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "EnrollmentGuideConfiguration")
public class EnrollmentGuideConfiguration {
private boolean isEnabled;
private String mail;
@XmlElement(name = "Enable", required = true)
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean enabled) {
isEnabled = enabled;
}
@XmlElement(name = "Mail", required = true)
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}

@ -0,0 +1,72 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.config.ui;
import javax.xml.bind.annotation.XmlElement;
public class HubspotChat {
private boolean isEnableHubspot;
private String trackingUrl;
private String accessToken;
private String senderActorId;
private long channelAccountId;
@XmlElement(name = "EnableHubspot")
public boolean isEnableHubspot() {
return isEnableHubspot;
}
public void setEnableHubspot(boolean enableHubspot) {
isEnableHubspot = enableHubspot;
}
@XmlElement(name = "TrackingUrl")
public String getTrackingUrl() {
return trackingUrl;
}
public void setTrackingUrl(String trackingUrl) {
this.trackingUrl = trackingUrl;
}
@XmlElement(name = "AccessToken")
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@XmlElement(name = "SenderActorId")
public String getSenderActorId() {
return senderActorId;
}
public void setSenderActorId(String senderActorId) {
this.senderActorId = senderActorId;
}
@XmlElement(name = "ChannelAccountId")
public long getChannelAccountId() {
return channelAccountId;
}
public void setChannelAccountId(long channelAccountId) {
this.channelAccountId = channelAccountId;
}
}

@ -34,6 +34,7 @@ public class UIConfiguration {
private int sessionTimeOut; private int sessionTimeOut;
private int loginCacheCapacity; private int loginCacheCapacity;
private Billing billing; private Billing billing;
private HubspotChat hubspotChat;
@XmlElement(name = "AppRegistration", required=true) @XmlElement(name = "AppRegistration", required=true)
public AppRegistration getAppRegistration() { public AppRegistration getAppRegistration() {
@ -63,6 +64,14 @@ public class UIConfiguration {
isSsoEnable = ssoEnable; isSsoEnable = ssoEnable;
} }
@XmlElement(name = "HubspotChat", required = true)
public HubspotChat getHubspotChat() {
return hubspotChat;
}
public void setHubspotChat(HubspotChat hubspotChat) {
this.hubspotChat = hubspotChat;
}
@XmlElement(name = "Billing", required=true) @XmlElement(name = "Billing", required=true)
public Billing getBilling() { public Billing getBilling() {
return billing; return billing;

@ -409,7 +409,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
} }
if (!HttpReportingUtil.isTrackerEnabled()) { if (!HttpReportingUtil.isTrackerEnabled()) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.info("Traccar is disabled"); log.debug("Traccar is disabled");
} }
} }
} }
@ -473,7 +473,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
} }
if (!HttpReportingUtil.isTrackerEnabled()) { if (!HttpReportingUtil.isTrackerEnabled()) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.info("Traccar is disabled"); log.debug("Traccar is disabled");
} }
} }
} }

@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.metadata.mgt;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
@ -90,8 +91,14 @@ public class MetadataManagementServiceImpl implements MetadataManagementService
} }
try { try {
MetadataManagementDAOFactory.openConnection(); MetadataManagementDAOFactory.openConnection();
return metadataDAO.getMetadata( int tenantId;
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true), metaKey); if (metaKey.equals("EVALUATE_TENANTS")){
// for getting evaluate tenant list to provide the live chat feature
tenantId = MultitenantConstants.SUPER_TENANT_ID;
} else {
tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
}
return metadataDAO.getMetadata(tenantId, metaKey);
} catch (MetadataManagementDAOException e) { } catch (MetadataManagementDAOException e) {
String msg = "Error occurred while retrieving the metadata entry for metaKey:" + metaKey; String msg = "Error occurred while retrieving the metadata entry for metaKey:" + metaKey;
log.error(msg, e); log.error(msg, e);

@ -18,8 +18,9 @@
package org.wso2.carbon.device.mgt.core.notification.mgt; package org.wso2.carbon.device.mgt.core.notification.mgt;
import org.apache.commons.logging.Log; import io.entgra.device.mgt.extensions.logger.spi.EntgraLogger;
import org.apache.commons.logging.LogFactory; import io.entgra.notification.logger.DeviceLogContext;
import io.entgra.notification.logger.impl.EntgraDeviceLoggerImpl;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
@ -45,8 +46,8 @@ import java.util.List;
*/ */
public class NotificationManagementServiceImpl implements NotificationManagementService { public class NotificationManagementServiceImpl implements NotificationManagementService {
private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class); private static final EntgraLogger log = new EntgraDeviceLoggerImpl(NotificationManagementServiceImpl.class);
DeviceLogContext.Builder deviceLogContexBuilder = new DeviceLogContext.Builder();
private NotificationDAO notificationDAO; private NotificationDAO notificationDAO;
public NotificationManagementServiceImpl() { public NotificationManagementServiceImpl() {

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.core.operation.mgt; package org.wso2.carbon.device.mgt.core.operation.mgt;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -792,9 +793,7 @@ public class OperationManagerImpl implements OperationManager {
if (dtoOperation != null) { if (dtoOperation != null) {
long currentTime = Calendar.getInstance().getTime().getTime(); long currentTime = Calendar.getInstance().getTime().getTime();
log.info("Current timestamp:" + currentTime);
long updatedTime = Timestamp.valueOf(dtoOperation.getReceivedTimeStamp()).getTime(); long updatedTime = Timestamp.valueOf(dtoOperation.getReceivedTimeStamp()).getTime();
log.info("Updated timestamp: " + updatedTime);
// check if notnow frequency is met and set next pending operation if not, otherwise let notnow // check if notnow frequency is met and set next pending operation if not, otherwise let notnow
// operation to proceed // operation to proceed

@ -32,31 +32,10 @@ import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
public class OperationTimeoutTask extends DynamicPartitionedScheduleTask { public class OperationTimeoutTask extends DynamicPartitionedScheduleTask {
private static final Log log = LogFactory.getLog(OperationTimeoutTask.class); private static final Log log = LogFactory.getLog(OperationTimeoutTask.class);
private OperationTimeout operationTimeoutConfig;
@Override
public void setProperties(Map<String, String> properties) {
super.setProperties(properties);
String operationTimeoutTaskConfigStr = properties
.get(OperationTimeoutTaskManagerServiceImpl.OPERATION_TIMEOUT_TASK_CONFIG);
Gson gson = new Gson();
operationTimeoutConfig = gson.fromJson(operationTimeoutTaskConfigStr, OperationTimeout.class);
}
@Override
public String getProperty(String name) {
return super.getProperty(name);
}
@Override
public void refreshContext() {
super.refreshContext();
}
@Override @Override
protected void setup() { protected void setup() {
@ -65,12 +44,15 @@ public class OperationTimeoutTask extends DynamicPartitionedScheduleTask {
@Override @Override
protected void executeDynamicTask() { protected void executeDynamicTask() {
String operationTimeoutTaskConfigStr = getProperty(
OperationTimeoutTaskManagerServiceImpl.OPERATION_TIMEOUT_TASK_CONFIG);
Gson gson = new Gson();
OperationTimeout operationTimeoutConfig = gson.fromJson(operationTimeoutTaskConfigStr, OperationTimeout.class);
try { try {
long timeMillis = System.currentTimeMillis() - operationTimeoutConfig.getTimeout() * 60 * 1000; long timeMillis = System.currentTimeMillis() - operationTimeoutConfig.getTimeout() * 60 * 1000;
List<String> deviceTypes = new ArrayList<>(); List<String> deviceTypes = new ArrayList<>();
if (operationTimeoutConfig.getDeviceTypes().size() == 1 && if (operationTimeoutConfig.getDeviceTypes().size() == 1 &&
"ALL".equals(operationTimeoutConfig.getDeviceTypes().get( 0))) { "ALL".equals(operationTimeoutConfig.getDeviceTypes().get(0))) {
try { try {
List<DeviceType> deviceTypeList = DeviceManagementDataHolder.getInstance() List<DeviceType> deviceTypeList = DeviceManagementDataHolder.getInstance()
.getDeviceManagementProvider().getDeviceTypes(); .getDeviceManagementProvider().getDeviceTypes();

@ -645,6 +645,8 @@ public interface DeviceManagementProviderService {
void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException, void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException,
ConfigurationManagementException; ConfigurationManagementException;
void sendEnrolmentGuide(String enrolmentGuide) throws DeviceManagementException;
void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException, ConfigurationManagementException; void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException, ConfigurationManagementException;
FeatureManager getFeatureManager(String deviceType) throws DeviceTypeNotFoundException; FeatureManager getFeatureManager(String deviceType) throws DeviceTypeNotFoundException;
@ -1030,4 +1032,6 @@ public interface DeviceManagementProviderService {
*/ */
PaginationResult getDevicesDetails(PaginationRequest request, List<Integer> devicesIds, String groupName) PaginationResult getDevicesDetails(PaginationRequest request, List<Integer> devicesIds, String groupName)
throws DeviceManagementException; throws DeviceManagementException;
Boolean sendDeviceNameChangedNotification(Device device) throws DeviceManagementException;
} }

@ -123,6 +123,7 @@ import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository;
import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey;
import org.wso2.carbon.device.mgt.core.cache.impl.BillingCacheManagerImpl; import org.wso2.carbon.device.mgt.core.cache.impl.BillingCacheManagerImpl;
import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl;
import org.wso2.carbon.device.mgt.core.common.Constants;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO;
@ -146,6 +147,7 @@ import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.email.sender.core.ContentProviderInfo; import org.wso2.carbon.email.sender.core.ContentProviderInfo;
@ -196,6 +198,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
private final ApplicationDAO applicationDAO; private final ApplicationDAO applicationDAO;
private MetadataDAO metadataDAO; private MetadataDAO metadataDAO;
private final DeviceStatusDAO deviceStatusDAO; private final DeviceStatusDAO deviceStatusDAO;
int count = 0;
public DeviceManagementProviderServiceImpl() { public DeviceManagementProviderServiceImpl() {
this.pluginRepository = new DeviceManagementPluginRepository(); this.pluginRepository = new DeviceManagementPluginRepository();
@ -442,7 +445,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
//Exception was not thrown due to being conflicted with non-traccar features //Exception was not thrown due to being conflicted with non-traccar features
} }
} else { } else {
log.info("Traccar is disabled"); if (log.isDebugEnabled()) {
log.debug("Traccar is disabled");
}
} }
//enroll Traccar device //enroll Traccar device
@ -542,7 +547,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
//Exception was not thrown due to being conflicted with non-traccar features //Exception was not thrown due to being conflicted with non-traccar features
} }
} else { } else {
log.info("Traccar is disabled"); if (log.isDebugEnabled()) {
log.debug("Traccar is disabled");
}
} }
//enroll Traccar device //enroll Traccar device
return status; return status;
@ -1549,6 +1556,25 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
} }
@Override
public void sendEnrolmentGuide(String enrolmentGuide) throws DeviceManagementException {
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
String recipientMail = config.getEnrollmentGuideConfiguration().getMail();
Properties props = new Properties();
props.setProperty("mail-subject", "[Enrollment Guide Triggered] (#" + ++count + ")");
props.setProperty("enrollment-guide", enrolmentGuide);
try {
EmailMetaInfo metaInfo = new EmailMetaInfo(recipientMail, props);
sendEnrolmentInvitation(DeviceManagementConstants.EmailAttributes.ENROLLMENT_GUIDE_TEMPLATE, metaInfo);
} catch (ConfigurationManagementException e) {
String msg = "Error occurred while sending the mail.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
}
@Override @Override
public void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException, public void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException,
ConfigurationManagementException { ConfigurationManagementException {
@ -4874,4 +4900,34 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
paginationResult.setData(populateAllDeviceInfo(subscribedDeviceDetails)); paginationResult.setData(populateAllDeviceInfo(subscribedDeviceDetails));
return paginationResult; return paginationResult;
} }
@Override
public Boolean sendDeviceNameChangedNotification(Device device) throws DeviceManagementException {
try {
ProfileOperation operation = new ProfileOperation();
operation.setCode(Constants.SEND_USERNAME);
operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(device.getName());
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(device.getDeviceIdentifier());
deviceIdentifier.setType(device.getType());
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(deviceIdentifier);
Activity activity;
activity = addOperation(device.getType(), operation, deviceIdentifiers);
return activity != null;
} catch (OperationManagementException e) {
String msg = "Error occurred while sending operation";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (InvalidDeviceException e) {
String msg = "Invalid Device exception occurred";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
}
} }

@ -41,6 +41,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; 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.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceTypesOfGroups;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException;
@ -335,4 +336,11 @@ public interface GroupManagementProviderService {
*/ */
boolean isDeviceMappedToGroup(int groupId, DeviceIdentifier deviceIdentifier) throws GroupManagementException; boolean isDeviceMappedToGroup(int groupId, DeviceIdentifier deviceIdentifier) throws GroupManagementException;
/**
*
* @param identifiers identifiers of groups
* @return whether the groups has android, iOS, Windows device types
* @throws GroupManagementException
*/
DeviceTypesOfGroups getDeviceTypesOfGroups(List<String> identifiers) throws GroupManagementException;
} }

@ -43,6 +43,7 @@ import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
@ -51,6 +52,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; 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.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceTypesOfGroups;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException;
@ -79,6 +81,7 @@ import java.util.stream.Collectors;
public class GroupManagementProviderServiceImpl implements GroupManagementProviderService { public class GroupManagementProviderServiceImpl implements GroupManagementProviderService {
private static final Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class); private static final Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class);
private static final String DEVICE_STATUS_REMOVED = "REMOVED";
private final GroupDAO groupDAO; private final GroupDAO groupDAO;
private final DeviceDAO deviceDAO; private final DeviceDAO deviceDAO;
@ -1379,4 +1382,60 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
createGroupWithChildren(nextParentGroup, childrenGroups, requireGroupProps, tenantId, depth, counter); createGroupWithChildren(nextParentGroup, childrenGroups, requireGroupProps, tenantId, depth, counter);
} }
} }
@Override
public DeviceTypesOfGroups getDeviceTypesOfGroups(List<String> identifiers) throws GroupManagementException {
DeviceTypesOfGroups deviceTypesOfGroups = new DeviceTypesOfGroups();
List<Integer> groupsIDs = new ArrayList<>();
try {
for (String id : identifiers) {
groupsIDs.add(Integer.parseInt(id));
}
List<String> deviceIDs = new ArrayList<>();
List<Device> allDevices = new ArrayList<>();
for (Integer groupID : groupsIDs) {
DeviceGroup deviceGroup = getGroup(groupID, false);
if (deviceGroup == null) {
String errorMessage = "Invalid Group ID provided.";
log.error(errorMessage);
throw new GroupManagementException(errorMessage);
}
List<Device> devices = getAllDevicesOfGroup(deviceGroup.getName(), false);
for (Device device : devices) {
if (!DEVICE_STATUS_REMOVED.equals(device.getEnrolmentInfo().getStatus().toString())
&& !deviceIDs.contains(device.getDeviceIdentifier())) {
deviceIDs.add(device.getDeviceIdentifier());
allDevices.add(device);
}
}
}
for (Device device : allDevices) {
if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID.equals(device.getType())) {
deviceTypesOfGroups.setHasAndroid(true);
break;
}
}
for (Device device : allDevices) {
if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS.equals(device.getType())) {
deviceTypesOfGroups.setHasIos(true);
break;
}
}
for (Device device : allDevices) {
if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS.equals(device.getType())) {
deviceTypesOfGroups.setHasWindows(true);
break;
}
}
} catch (NumberFormatException e) {
String errorMessage = "Only numbers can exists in a group ID";
log.error(errorMessage);
throw new GroupManagementException(errorMessage, e);
}
return deviceTypesOfGroups;
}
} }

@ -37,7 +37,6 @@ import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* This implements the Task service which monitors the device activity periodically & update the device-status if * This implements the Task service which monitors the device activity periodically & update the device-status if
@ -47,19 +46,8 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask {
private static final Log log = LogFactory.getLog(DeviceStatusMonitoringTask.class); private static final Log log = LogFactory.getLog(DeviceStatusMonitoringTask.class);
private String deviceType; private String deviceType;
private DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig;
private int deviceTypeId = -1; private int deviceTypeId = -1;
@Override
public void setProperties(Map<String, String> properties) {
super.setProperties(properties);
deviceType = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE);
deviceTypeId = Integer.parseInt(properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE_ID));
String deviceStatusTaskConfigStr = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_STATUS_TASK_CONFIG);
Gson gson = new Gson();
deviceStatusTaskPluginConfig = gson.fromJson(deviceStatusTaskConfigStr, DeviceStatusTaskPluginConfig.class);
}
@Override @Override
protected void setup() { protected void setup() {
} }
@ -92,6 +80,11 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask {
@Override @Override
public void executeDynamicTask() { public void executeDynamicTask() {
deviceType = getProperty(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE);
deviceTypeId = Integer.parseInt(getProperty(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE_ID));
String deviceStatusTaskConfigStr = getProperty(DeviceStatusTaskManagerServiceImpl.DEVICE_STATUS_TASK_CONFIG);
Gson gson = new Gson();
DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig = gson.fromJson(deviceStatusTaskConfigStr, DeviceStatusTaskPluginConfig.class);
try { try {
List<EnrolmentInfo> enrolmentInfoTobeUpdated = new ArrayList<>(); List<EnrolmentInfo> enrolmentInfoTobeUpdated = new ArrayList<>();
List<DeviceMonitoringData> allDevicesForMonitoring = getAllDevicesForMonitoring(); List<DeviceMonitoringData> allDevicesForMonitoring = getAllDevicesForMonitoring();
@ -102,10 +95,10 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask {
EnrolmentInfo enrolmentInfo = monitoringData.getDevice().getEnrolmentInfo(); EnrolmentInfo enrolmentInfo = monitoringData.getDevice().getEnrolmentInfo();
EnrolmentInfo.Status status = null; EnrolmentInfo.Status status = null;
if (lastUpdatedTime >= this.deviceStatusTaskPluginConfig if (lastUpdatedTime >= deviceStatusTaskPluginConfig
.getIdleTimeToMarkInactive()) { .getIdleTimeToMarkInactive()) {
status = EnrolmentInfo.Status.INACTIVE; status = EnrolmentInfo.Status.INACTIVE;
} else if (lastUpdatedTime >= this.deviceStatusTaskPluginConfig } else if (lastUpdatedTime >= deviceStatusTaskPluginConfig
.getIdleTimeToMarkUnreachable()) { .getIdleTimeToMarkUnreachable()) {
status = EnrolmentInfo.Status.UNREACHABLE; status = EnrolmentInfo.Status.UNREACHABLE;
} }

@ -48,7 +48,6 @@ import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager;
import java.util.List; import java.util.List;
import java.util.Map;
public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask { public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask {
@ -56,14 +55,9 @@ public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask {
private String deviceType; private String deviceType;
private DeviceManagementProviderService deviceManagementProviderService; private DeviceManagementProviderService deviceManagementProviderService;
@Override
public void setProperties(Map<String, String> map) {
super.setProperties(map);
deviceType = map.get("DEVICE_TYPE");
}
@Override @Override
public void executeDynamicTask() { public void executeDynamicTask() {
deviceType = getProperty("DEVICE_TYPE");
deviceManagementProviderService = DeviceManagementDataHolder.getInstance() deviceManagementProviderService = DeviceManagementDataHolder.getInstance()
.getDeviceManagementProvider(); .getDeviceManagementProvider();
OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementProviderService OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementProviderService

@ -19,10 +19,11 @@
package org.wso2.carbon.device.mgt.core.task.impl; package org.wso2.carbon.device.mgt.core.task.impl;
import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException;
import io.entgra.task.mgt.common.constant.TaskMgtConstants;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.ServerCtxInfo;
import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.DynamicTaskContext;
import org.wso2.carbon.device.mgt.common.ServerCtxInfo;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.ntask.core.Task; import org.wso2.carbon.ntask.core.Task;
@ -37,11 +38,11 @@ public abstract class DynamicPartitionedScheduleTask implements Task {
private Map<String, String> properties; private Map<String, String> properties;
@Override @Override
public void setProperties(Map<String, String> properties) { public final void setProperties(Map<String, String> properties) {
this.properties = properties; this.properties = properties;
} }
public String getProperty(String name) { public final String getProperty(String name) {
if (properties == null) { if (properties == null) {
return null; return null;
} }
@ -62,7 +63,7 @@ public abstract class DynamicPartitionedScheduleTask implements Task {
} }
} }
} catch (HeartBeatManagementException e) { } catch (HeartBeatManagementException e) {
log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function." , e); log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function.", e);
} }
setup(); setup();
} }
@ -70,11 +71,41 @@ public abstract class DynamicPartitionedScheduleTask implements Task {
@Override @Override
public final void execute() { public final void execute() {
refreshContext(); refreshContext();
if (taskContext != null && taskContext.isPartitioningEnabled()) {
String localHashIndex = getProperty(TaskMgtConstants.Task.LOCAL_HASH_INDEX);
// These tasks are not dynamically scheduled. They are added via a config so scheduled in each node
// during the server startup
if (localHashIndex == null ) {
if (log.isDebugEnabled()) {
log.debug("Executing startup scheduled task (" + getTaskName() + ") with class: " +
this.getClass().getName());
}
executeDynamicTask(); executeDynamicTask();
return;
}
if (localHashIndex.equals(String.valueOf(taskContext.getServerHashIndex()))) {
if (log.isDebugEnabled()) {
log.debug("Executing dynamically scheduled task (" + getTaskName() +
") for current server hash index: " + localHashIndex);
}
executeDynamicTask();
} else {
if (log.isDebugEnabled()) {
log.debug("Ignoring execution of task (" + getTaskName() +
") not belonging to current serer hash index: " + localHashIndex);
}
}
} else {
executeDynamicTask();
}
}
public String getTaskName() {
return getProperty(TaskMgtConstants.Task.LOCAL_TASK_NAME);
} }
public void refreshContext(){ public void refreshContext() {
if(taskContext != null && taskContext.isPartitioningEnabled()) { if (taskContext != null && taskContext.isPartitioningEnabled()) {
try { try {
updateContext(); updateContext();
} catch (HeartBeatManagementException e) { } catch (HeartBeatManagementException e) {

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -23,7 +23,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>heartbeat-management</artifactId> <artifactId>heartbeat-management</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -19,13 +19,14 @@
package io.entgra.server.bootup.heartbeat.beacon.dto; package io.entgra.server.bootup.heartbeat.beacon.dto;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class ElectedCandidate { public class ElectedCandidate {
private String serverUUID; private String serverUUID;
private Timestamp timeOfElection; private Timestamp timeOfElection;
private List<String> acknowledgedTaskList = null; private List<String> acknowledgedTaskList = new ArrayList<>();
public List<String> getAcknowledgedTaskList() { public List<String> getAcknowledgedTaskList() {
return acknowledgedTaskList; return acknowledgedTaskList;

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>identity-extensions</artifactId> <artifactId>identity-extensions</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>identity-extensions</artifactId> <artifactId>identity-extensions</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
~
~ Entgra (pvt) Ltd. 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>logger</artifactId>
<version>5.0.21-SNAPSHOT</version>
</parent>
<artifactId>io.entgra.notification.logger</artifactId>
<name>Entgra - Notification Logger</name>
<packaging>bundle</packaging>
<url>http://entgra.io</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.device.mgt.extensions.logger</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Device Notification Logger Bundle</Bundle-Description>
<Import-Package>
io.entgra.device.mgt.extensions.logger.*,
org.apache.commons.logging;version="[1.2,2)",
org.apache.log4j;version="[1.2,2)",
org.wso2.carbon.context;version="[4.4,5)
</Import-Package>
<Export-Package>
io.entgra.notification.logger.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,103 @@
/*
* Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. 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 io.entgra.notification.logger;
import io.entgra.device.mgt.extensions.logger.LogContext;
public class DeviceLogContext extends LogContext {
private final String deviceName;
private final String operationCode;
private final String deviceType;
private final String tenantID;
private DeviceLogContext(Builder builder) {
this.operationCode = builder.operationCode;
this.deviceName = builder.deviceName;
this.deviceType = builder.deviceType;
this.tenantID = builder.tenantID;
}
public String getTenantID() {
return tenantID;
}
public String getDeviceName() {
return deviceName;
}
public String getOperationCode() {
return operationCode;
}
public String getDeviceType() {
return deviceType;
}
public static class Builder {
private String deviceName;
private String operationCode;
private String deviceType;
private String tenantID;
public Builder() {
}
public String getDeviceType() {
return deviceType;
}
public Builder setDeviceType(String deviceType) {
this.deviceType = deviceType;
return this;
}
public String getTenantID() {
return tenantID;
}
public Builder setTenantID(String tenantID) {
this.tenantID = tenantID;
return this;
}
public String getDeviceName() {
return deviceName;
}
public Builder setDeviceName(String deviceName) {
this.deviceName = deviceName;
return this;
}
public String getOperationCode() {
return operationCode;
}
public Builder setOperationCode(String operationCode) {
this.operationCode = operationCode;
return this;
}
public DeviceLogContext build() {
return new DeviceLogContext(this);
}
}
}

@ -0,0 +1,103 @@
/*
* Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. 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 io.entgra.notification.logger;
import io.entgra.device.mgt.extensions.logger.LogContext;
public class UserLogContext extends LogContext {
private final String userName;
private final String userEmail;
private final String metaInfo;
private final String tenantID;
private UserLogContext(Builder builder) {
this.userEmail = builder.userEmail;
this.userName = builder.userName;
this.metaInfo = builder.metaInfo;
this.tenantID = builder.tenantID;
}
public String getTenantID() {
return tenantID;
}
public String getUserName() {
return userName;
}
public String getUserEmail() {
return userEmail;
}
public String getMetaInfo() {
return metaInfo;
}
public static class Builder {
private String userName;
private String userEmail;
private String metaInfo;
private String tenantID;
public Builder() {
}
public String getMetaInfo() {
return metaInfo;
}
public Builder setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
return this;
}
public String getTenantID() {
return tenantID;
}
public Builder setTenantID(String tenantID) {
this.tenantID = tenantID;
return this;
}
public String getUserName() {
return userName;
}
public Builder setUserName(String userName) {
this.userName = userName;
return this;
}
public String getUserEmail() {
return userEmail;
}
public Builder setUserEmail(String userEmail) {
this.userEmail = userEmail;
return this;
}
public UserLogContext build() {
return new UserLogContext(this);
}
}
}

@ -0,0 +1,294 @@
/*
* Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. 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 io.entgra.notification.logger.impl;
import io.entgra.device.mgt.extensions.logger.LogContext;
import io.entgra.device.mgt.extensions.logger.spi.EntgraLogger;
import io.entgra.notification.logger.DeviceLogContext;
import io.entgra.notification.logger.util.MDCContextUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
public class EntgraDeviceLoggerImpl implements EntgraLogger {
private static Log log = null;
public EntgraDeviceLoggerImpl(Class<?> clazz) {
log = LogFactory.getLog(clazz);
}
@Override
public void info(Object object, LogContext logContext) {
}
@Override
public void info(Object object, Throwable t, LogContext logContext) {
}
@Override
public void debug(Object object, LogContext logContext) {
}
@Override
public void debug(Object object, Throwable t, LogContext logContext) {
}
@Override
public void error(Object object, LogContext logContext) {
}
@Override
public void error(Object object, Throwable t, LogContext logContext) {
}
@Override
public void fatal(Object object, LogContext logContext) {
}
@Override
public void fatal(Object object, Throwable t, LogContext logContext) {
}
@Override
public void trace(Object object, LogContext logContext) {
}
@Override
public void trace(Object object, Throwable t, LogContext logContext) {
}
@Override
public void warn(Object object, LogContext logContext) {
}
@Override
public void warn(Object object, Throwable t, LogContext logContext) {
}
public void info(String message) {
}
public void info(String message, Throwable t) {
log.info(message, t);
}
@Override
public void info(String message, LogContext logContext) {
DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
log.info(message);
}
public void debug(String message) {
log.debug(message);
}
public void debug(String message, Throwable t) {
log.debug(message, t);
}
@Override
public void debug(String message, LogContext logContext) {
DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
log.debug(message);
}
public void error(String message) {
log.error(message);
}
public void error(String message, Throwable t) {
log.error(message, t);
}
@Override
public void error(String message, LogContext logContext) {
DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
log.error(message);
}
@Override
public void error(String message, Throwable t, LogContext logContext) {
DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
log.error(message, t);
}
public void warn(String message) {
log.warn(message);
}
public void warn(String message, Throwable t) {
log.warn(message, t);
}
@Override
public void warn(String message, LogContext logContext) {
DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
log.warn(message);
}
@Override
public void warn(String message, Throwable t, LogContext logContext) {
DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
log.warn(message, t);
}
public void trace(String message) {
log.trace(message);
}
public void trace(String message, Throwable t) {
log.trace(message, t);
}
@Override
public void trace(String message, LogContext logContext) {
DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
log.trace(message);
}
public void fatal(String message) {
log.fatal(message);
}
public void fatal(String message, Throwable t) {
log.fatal(message, t);
}
@Override
public void fatal(String message, LogContext logContext) {
DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
log.fatal(message);
}
@Override
public void debug(Object o) {
log.debug(o);
}
@Override
public void debug(Object o, Throwable throwable) {
log.debug(o, throwable);
}
@Override
public void error(Object o) {
log.error(o);
}
@Override
public void error(Object o, Throwable throwable) {
log.error(o, throwable);
}
@Override
public void fatal(Object o) {
log.fatal(0);
}
@Override
public void fatal(Object o, Throwable throwable) {
log.fatal(0, throwable);
}
@Override
public void info(Object o) {
log.info(o);
}
@Override
public void info(Object o, Throwable throwable) {
log.info(o, throwable);
}
@Override
public boolean isDebugEnabled() {
return log.isDebugEnabled();
}
@Override
public boolean isErrorEnabled() {
return log.isErrorEnabled();
}
@Override
public boolean isFatalEnabled() {
return log.isFatalEnabled();
}
@Override
public boolean isInfoEnabled() {
return log.isInfoEnabled();
}
@Override
public boolean isTraceEnabled() {
return log.isTraceEnabled();
}
@Override
public boolean isWarnEnabled() {
return log.isWarnEnabled();
}
@Override
public void trace(Object o) {
log.trace(o);
}
@Override
public void trace(Object o, Throwable throwable) {
log.trace(o, throwable);
}
@Override
public void warn(Object o) {
log.warn(o);
}
@Override
public void warn(Object o, Throwable throwable) {
log.warn(o, throwable);
}
@Override
public void clearLogContext() {
MDC.clear();
}
}

@ -0,0 +1,294 @@
/*
* Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. 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 io.entgra.notification.logger.impl;
import io.entgra.device.mgt.extensions.logger.LogContext;
import io.entgra.device.mgt.extensions.logger.spi.EntgraLogger;
import io.entgra.notification.logger.UserLogContext;
import io.entgra.notification.logger.util.MDCContextUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
public class EntgraUserLoggerImpl implements EntgraLogger {
private static Log log = null;
public EntgraUserLoggerImpl(Class<?> clazz) {
log = LogFactory.getLog(clazz);
}
@Override
public void info(Object object, LogContext logContext) {
}
@Override
public void info(Object object, Throwable t, LogContext logContext) {
}
@Override
public void debug(Object object, LogContext logContext) {
}
@Override
public void debug(Object object, Throwable t, LogContext logContext) {
}
@Override
public void error(Object object, LogContext logContext) {
}
@Override
public void error(Object object, Throwable t, LogContext logContext) {
}
@Override
public void fatal(Object object, LogContext logContext) {
}
@Override
public void fatal(Object object, Throwable t, LogContext logContext) {
}
@Override
public void trace(Object object, LogContext logContext) {
}
@Override
public void trace(Object object, Throwable t, LogContext logContext) {
}
@Override
public void warn(Object object, LogContext logContext) {
}
@Override
public void warn(Object object, Throwable t, LogContext logContext) {
}
public void info(String message) {
}
public void info(String message, Throwable t) {
log.info(message, t);
}
@Override
public void info(String message, LogContext logContext) {
UserLogContext userLogContext = (UserLogContext) logContext;
MDCContextUtil.populateUserMDCContext(userLogContext);
log.info(message);
}
public void debug(String message) {
log.debug(message);
}
public void debug(String message, Throwable t) {
log.debug(message, t);
}
@Override
public void debug(String message, LogContext logContext) {
UserLogContext userLogContext = (UserLogContext) logContext;
MDCContextUtil.populateUserMDCContext(userLogContext);
log.debug(message);
}
public void error(String message) {
log.error(message);
}
public void error(String message, Throwable t) {
log.error(message, t);
}
@Override
public void error(String message, LogContext logContext) {
UserLogContext userLogContext = (UserLogContext) logContext;
MDCContextUtil.populateUserMDCContext(userLogContext);
log.error(message);
}
@Override
public void error(String message, Throwable t, LogContext logContext) {
UserLogContext userLogContext = (UserLogContext) logContext;
MDCContextUtil.populateUserMDCContext(userLogContext);
log.error(message, t);
}
public void warn(String message) {
log.warn(message);
}
public void warn(String message, Throwable t) {
log.warn(message, t);
}
@Override
public void warn(String message, LogContext logContext) {
UserLogContext userLogContext = (UserLogContext) logContext;
MDCContextUtil.populateUserMDCContext(userLogContext);
log.warn(message);
}
@Override
public void warn(String message, Throwable t, LogContext logContext) {
UserLogContext userLogContext = (UserLogContext) logContext;
MDCContextUtil.populateUserMDCContext(userLogContext);
log.warn(message, t);
}
public void trace(String message) {
log.trace(message);
}
public void trace(String message, Throwable t) {
log.trace(message, t);
}
@Override
public void trace(String message, LogContext logContext) {
UserLogContext userLogContext = (UserLogContext) logContext;
MDCContextUtil.populateUserMDCContext(userLogContext);
log.trace(message);
}
public void fatal(String message) {
log.fatal(message);
}
public void fatal(String message, Throwable t) {
log.fatal(message, t);
}
@Override
public void fatal(String message, LogContext logContext) {
UserLogContext userLogContext = (UserLogContext) logContext;
MDCContextUtil.populateUserMDCContext(userLogContext);
log.fatal(message);
}
@Override
public void debug(Object o) {
log.debug(o);
}
@Override
public void debug(Object o, Throwable throwable) {
log.debug(o, throwable);
}
@Override
public void error(Object o) {
log.error(o);
}
@Override
public void error(Object o, Throwable throwable) {
log.error(o, throwable);
}
@Override
public void fatal(Object o) {
log.fatal(0);
}
@Override
public void fatal(Object o, Throwable throwable) {
log.fatal(0, throwable);
}
@Override
public void info(Object o) {
log.info(o);
}
@Override
public void info(Object o, Throwable throwable) {
log.info(o, throwable);
}
@Override
public boolean isDebugEnabled() {
return log.isDebugEnabled();
}
@Override
public boolean isErrorEnabled() {
return log.isErrorEnabled();
}
@Override
public boolean isFatalEnabled() {
return log.isFatalEnabled();
}
@Override
public boolean isInfoEnabled() {
return log.isInfoEnabled();
}
@Override
public boolean isTraceEnabled() {
return log.isTraceEnabled();
}
@Override
public boolean isWarnEnabled() {
return log.isWarnEnabled();
}
@Override
public void trace(Object o) {
log.trace(o);
}
@Override
public void trace(Object o, Throwable throwable) {
log.trace(o, throwable);
}
@Override
public void warn(Object o) {
log.warn(o);
}
@Override
public void warn(Object o, Throwable throwable) {
log.warn(o, throwable);
}
@Override
public void clearLogContext() {
MDC.clear();
}
}

@ -0,0 +1,57 @@
/*
* Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. 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 io.entgra.notification.logger.util;
import io.entgra.notification.logger.DeviceLogContext;
import io.entgra.notification.logger.UserLogContext;
import org.apache.log4j.MDC;
public final class MDCContextUtil {
public static void populateDeviceMDCContext(final DeviceLogContext mdcContext) {
if (mdcContext.getDeviceName() != null) {
MDC.put("DeviceName", mdcContext.getDeviceName());
}
if (mdcContext.getDeviceType() != null) {
MDC.put("DeviceType", mdcContext.getDeviceType());
}
if (mdcContext.getOperationCode() != null) {
MDC.put("OperationCode", mdcContext.getOperationCode());
}
if (mdcContext.getTenantID() != null) {
MDC.put("TenantId", mdcContext.getTenantID());
}
}
public static void populateUserMDCContext(final UserLogContext mdcContext) {
if (mdcContext.getUserName() != null) {
MDC.put("UserName", mdcContext.getUserName());
}
if (mdcContext.getUserEmail() != null) {
MDC.put("UserEmail", mdcContext.getUserEmail());
}
if (mdcContext.getMetaInfo() != null) {
MDC.put("MetaInfo", mdcContext.getMetaInfo());
}
if (mdcContext.getTenantID() != null) {
MDC.put("TenantId", mdcContext.getTenantID());
}
}
}

@ -0,0 +1,32 @@
#
# Copyright 2023 Entgra Pvt. Ltd.. (http://entgra.io)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# This is the log4j configuration file used by Entgra Pvt. Ltd.
#
# IMPORTANT : Please do not remove or change the names of any
# of the Appenders defined here. The layout pattern & log file
# can be changed using the WSO2 Carbon Management Console, and those
# settings will override the settings in this file.
#
log4j.rootLogger=DEBUG, STD_OUT
# Redirect log messages to console
log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender
log4j.appender.STD_OUT.Target=System.out
log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
~
~ Entgra (pvt) Ltd. 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>carbon-devicemgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.21-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>logger</artifactId>
<packaging>pom</packaging>
<name>Entgra - Notification Logger Component</name>
<url>http://entgra.io</url>
<modules>
<module>io.entgra.notification.logger</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

@ -3,7 +3,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>policy-mgt</artifactId> <artifactId>policy-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -3,7 +3,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>policy-mgt</artifactId> <artifactId>policy-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>policy-mgt</artifactId> <artifactId>policy-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>policy-mgt</artifactId> <artifactId>policy-mgt</artifactId>
<version>5.0.16-SNAPSHOT</version> <version>5.0.21-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -1038,7 +1038,7 @@ public class PolicyManagerImpl implements PolicyManager {
.getInstance().getDeviceManagementService(); .getInstance().getDeviceManagementService();
List<Device> allDevices; List<Device> allDevices;
try { try {
allDevices = deviceManagementService.getAllDevices(); allDevices = deviceManagementService.getAllDevices(false);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" + throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" +
policyId + ")", e); policyId + ")", e);

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

Loading…
Cancel
Save