diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml index ee26a82c11..c8011c08f3 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml index cbbc982a0e..ad2b76aea8 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml index fc23f41f4e..2d708f2e34 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/pom.xml b/components/analytics-mgt/grafana-mgt/pom.xml index c4591f4e67..1687efce72 100644 --- a/components/analytics-mgt/grafana-mgt/pom.xml +++ b/components/analytics-mgt/grafana-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core analytics-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/pom.xml b/components/analytics-mgt/pom.xml index 1b67f931d7..00d4c90659 100644 --- a/components/analytics-mgt/pom.xml +++ b/components/analytics-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml index 9c31dea157..062250c578 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml @@ -20,7 +20,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT 4.0.0 diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml index 13ea9872f7..e3f137438d 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml index fa641ba1e3..fb993c89e1 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml index 41b4ad438e..9715d49004 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml index 4c47d11073..153009c3e8 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml index 904e5f5e8c..3a0bbffa59 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT 4.0.0 diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml index 1ef38e9c6d..9d9fc52a3c 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml index 487af21899..10bfbf4145 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 8b8048179f..8120dc4f6a 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml index 05abb93b19..ffb8a053df 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core application-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ChunkDescriptor.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ChunkDescriptor.java new file mode 100644 index 0000000000..d5c23e20ee --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ChunkDescriptor.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.common; + +import java.io.InputStream; + +public class ChunkDescriptor { + private FileDescriptor associateFileDescriptor; + private long size; + private InputStream chunk; + + public FileDescriptor getAssociateFileDescriptor() { + return associateFileDescriptor; + } + + public void setAssociateFileDescriptor(FileDescriptor associateFileDescriptor) { + this.associateFileDescriptor = associateFileDescriptor; + } + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } + + public InputStream getChunk() { + return chunk; + } + + public void setChunk(InputStream chunk) { + this.chunk = chunk; + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/FileDescriptor.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/FileDescriptor.java new file mode 100644 index 0000000000..226d8cb759 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/FileDescriptor.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.common; + +import java.io.InputStream; + +public class FileDescriptor { + private String fileName; + private String extension; + private String fullQualifiedName; + private String absolutePath; + private long actualFileSize; + private InputStream file; + + public InputStream getFile() { + return file; + } + + public void setFile(InputStream file) { + this.file = file; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public String getAbsolutePath() { + return absolutePath; + } + + public void setAbsolutePath(String absolutePath) { + this.absolutePath = absolutePath; + } + + public long getActualFileSize() { + return actualFileSize; + } + + public void setActualFileSize(long actualFileSize) { + this.actualFileSize = actualFileSize; + } + + public String getFullQualifiedName() { + return fullQualifiedName; + } + + public void setFullQualifiedName(String fullQualifiedName) { + this.fullQualifiedName = fullQualifiedName; + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/FileMetaEntry.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/FileMetaEntry.java new file mode 100644 index 0000000000..506ee3133f --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/FileMetaEntry.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.common; + +public class FileMetaEntry { + private String fileName; + private String extension; + + private long size; + private String absolutePath; + + public String getAbsolutePath() { + return absolutePath; + } + + public void setAbsolutePath(String absolutePath) { + this.absolutePath = absolutePath; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public long getSize() { + return size; + } + + public void setSize(long size) { + this.size = size; + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/TransferLink.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/TransferLink.java new file mode 100644 index 0000000000..d6d742637a --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/TransferLink.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.common; + +import java.util.Objects; + +public class TransferLink { + private static final String SCHEMA_SEPARATOR = "://"; + private static final String URL_SEPARATOR = "/"; + private static final String COLON = ":"; + private final String schema; + private final String host; + private final String port; + private final String endpoint; + private final String artifactHolderUUID; + + private TransferLink(String schema, String host, String port, String endpoint, String artifactHolderUUID) { + this.schema = schema; + this.host = host; + this.port = port; + this.endpoint = endpoint; + this.artifactHolderUUID = artifactHolderUUID; + } + + public String getDirectTransferLink() { + return schema + SCHEMA_SEPARATOR + host + COLON + port + URL_SEPARATOR + endpoint + URL_SEPARATOR + artifactHolderUUID; + } + + public String getRelativeTransferLink() { + return endpoint + URL_SEPARATOR + artifactHolderUUID; + } + + @Override + public String toString() { + return getDirectTransferLink(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + TransferLink that = (TransferLink) o; + return Objects.equals(schema, that.schema) && Objects.equals(host, that.host) && Objects.equals(port, that.port) + && Objects.equals(endpoint, that.endpoint) && Objects.equals(artifactHolderUUID, that.artifactHolderUUID); + } + + @Override + public int hashCode() { + return Objects.hash(schema, host, port, endpoint, artifactHolderUUID); + } + + public static class TransferLinkBuilder { + private static final String DEFAULT_SCHEMA = "https"; + private static final String ENDPOINT = "application-mgt-publisher/v1.0/applications/uploads"; + private static final String IOT_GW_HOST_ENV_VAR = "iot.gateway.host"; + private static final String IOT_GW_HTTPS_PORT_ENV_VAR = "iot.gateway.https.port"; + private static final String IOT_GW_HTTP_PORT_ENV_VAR = "iot.gateway.http.port"; + private String schema; + private String endpoint; + private final String artifactHolderUUID; + + public TransferLinkBuilder(String artifactHolderUUID) { + this.schema = DEFAULT_SCHEMA; + this.endpoint = ENDPOINT; + this.artifactHolderUUID = artifactHolderUUID; + } + + public TransferLinkBuilder withSchema(String schema) { + this.schema = schema; + return this; + } + + public TransferLinkBuilder withEndpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + public TransferLink build() { + return new TransferLink(this.schema, resolveHost(), resolvePort(), this.endpoint, this.artifactHolderUUID); + } + + private String resolveHost() { + return System.getProperty(IOT_GW_HOST_ENV_VAR); + } + + private String resolvePort() { + return Objects.equals(this.schema, DEFAULT_SCHEMA) ? System.getProperty(IOT_GW_HTTPS_PORT_ENV_VAR) + : System.getProperty(IOT_GW_HTTP_PORT_ENV_VAR); + } + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/exception/FileDownloaderServiceException.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/exception/FileDownloaderServiceException.java new file mode 100644 index 0000000000..c51624939f --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/exception/FileDownloaderServiceException.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.common.exception; + +public class FileDownloaderServiceException extends Exception { + public FileDownloaderServiceException(String msg) { + super(msg); + } + + public FileDownloaderServiceException(String msg, Throwable t) { + super(msg, t); + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/exception/FileTransferServiceException.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/exception/FileTransferServiceException.java new file mode 100644 index 0000000000..b2ce0aa8ba --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/exception/FileTransferServiceException.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.common.exception; + +public class FileTransferServiceException extends Exception { + public FileTransferServiceException(String msg) { + super(msg); + } + + public FileTransferServiceException(String msg, Throwable throwable) { + super(msg, throwable); + } + +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java index 57890f53eb..4a1be2ea1e 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java @@ -371,11 +371,9 @@ public interface ApplicationManager { * * @param releaseUuid UUID of the application release. * @param entAppReleaseWrapper {@link ApplicationReleaseDTO} - * @param applicationArtifact {@link ApplicationArtifact} * @return If the application release is updated correctly True returns, otherwise retuen False */ - ApplicationRelease updateEntAppRelease(String releaseUuid, EntAppReleaseWrapper entAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + ApplicationRelease updateEntAppRelease(String releaseUuid, EntAppReleaseWrapper entAppReleaseWrapper) throws ApplicationManagementException; /** @@ -383,33 +381,27 @@ public interface ApplicationManager { * * @param releaseUuid UUID of the application release. * @param publicAppReleaseWrapper {@link ApplicationReleaseDTO} - * @param applicationArtifact {@link ApplicationArtifact} * @return If the application release is updated correctly True returns, otherwise retuen False */ - ApplicationRelease updatePubAppRelease(String releaseUuid, PublicAppReleaseWrapper publicAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + ApplicationRelease updatePubAppRelease(String releaseUuid, PublicAppReleaseWrapper publicAppReleaseWrapper) throws ApplicationManagementException; /** * Use to update existing web app release * * @param releaseUuid UUID of the application release. * @param webAppReleaseWrapper {@link ApplicationReleaseDTO} - * @param applicationArtifact {@link ApplicationArtifact} * @return If the application release is updated correctly True returns, otherwise retuen False */ - ApplicationRelease updateWebAppRelease(String releaseUuid, WebAppReleaseWrapper webAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + ApplicationRelease updateWebAppRelease(String releaseUuid, WebAppReleaseWrapper webAppReleaseWrapper) throws ApplicationManagementException; /** * Use to update existing custom app release * * @param releaseUuid UUID of the application release. * @param customAppReleaseWrapper {@link ApplicationReleaseDTO} - * @param applicationArtifact {@link ApplicationArtifact} * @return If the application release is updated correctly True returns, otherwise retuen False */ - ApplicationRelease updateCustomAppRelease(String releaseUuid, CustomAppReleaseWrapper customAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + ApplicationRelease updateCustomAppRelease(String releaseUuid, CustomAppReleaseWrapper customAppReleaseWrapper) throws ApplicationManagementException; /** * To validate the application creating request @@ -546,4 +538,13 @@ public interface ApplicationManager { */ void updateAppIconInfo(ApplicationRelease applicationRelease, String oldPackageName) throws ApplicationManagementException; + + /** + * Delete all application related data of a tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementException thrown if an error occurs when deleting data + */ + void deleteApplicationDataOfTenant(int tenantId) throws ApplicationManagementException; + void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationStorageManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationStorageManager.java index 68b82facbc..698c57f55a 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationStorageManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationStorageManager.java @@ -132,4 +132,12 @@ public interface ApplicationStorageManager { * @throws StorageManagementException if errors while generating md5 string */ String getMD5(InputStream inputStream) throws StorageManagementException; + + /** + * Delete the folder containing all the app releases of a tenant + * + * @param tenantId Tenant ID + * @throws ApplicationStorageManagementException thrown if + */ + void deleteAppFolderOfTenant(int tenantId) throws ApplicationStorageManagementException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/FileDownloaderService.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/FileDownloaderService.java new file mode 100644 index 0000000000..fae56ab2d3 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/FileDownloaderService.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.common.services; + +import io.entgra.device.mgt.core.application.mgt.common.FileDescriptor; +import io.entgra.device.mgt.core.application.mgt.common.exception.FileDownloaderServiceException; + +import java.net.URL; + +public interface FileDownloaderService { + FileDescriptor download(URL downloadUrl) throws FileDownloaderServiceException; +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/FileTransferService.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/FileTransferService.java new file mode 100644 index 0000000000..1a69cf8e75 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/FileTransferService.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.common.services; + +import io.entgra.device.mgt.core.application.mgt.common.ChunkDescriptor; +import io.entgra.device.mgt.core.application.mgt.common.FileDescriptor; +import io.entgra.device.mgt.core.application.mgt.common.FileMetaEntry; +import io.entgra.device.mgt.core.application.mgt.common.TransferLink; +import io.entgra.device.mgt.core.application.mgt.common.exception.FileTransferServiceException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException; + +import java.io.InputStream; +import java.net.URL; + +public interface FileTransferService { + /** + * Create an upload link + * @param fileMetaEntry {@link FileMetaEntry} + * @return {@link TransferLink} + * @throws FileTransferServiceException Throws when error encountered while generating upload link + */ + TransferLink generateUploadLink(FileMetaEntry fileMetaEntry) throws FileTransferServiceException; + + /** + * Resolve {@link ChunkDescriptor} using artifactHolder UUID and a given chunk + * @param artifactHolder Artifact holder's UUID string + * @param chunk Data chunk + * @return {@link ChunkDescriptor} + * @throws FileTransferServiceException Throws when error encountered while resolving chunk descriptor + * @throws NotFoundException Throws when artifact holder not exists in the file system + */ + ChunkDescriptor resolve(String artifactHolder, InputStream chunk) throws FileTransferServiceException, NotFoundException; + + /** + * Write chunk of data + * @param chunkDescriptor {@link ChunkDescriptor} + * @throws FileTransferServiceException Throws when error encountered while writing chunk + */ + void writeChunk(ChunkDescriptor chunkDescriptor) throws FileTransferServiceException; + + /** + * Check if the provided download url point to a file which exists on the local env or not + * @param downloadUrl Download URL + * @return Returns true if the download URL point to a file which resides in local + * @throws FileTransferServiceException Throws when error encountered while checking + */ + boolean isExistsOnLocal(URL downloadUrl) throws FileTransferServiceException; + + /** + * Resolve {@link FileDescriptor} from a given download URL + * @param downloadUrl Download URL + * @return {@link java.io.FileDescriptor} + * @throws FileTransferServiceException Throws when error encountered while resolving file descriptor + */ + FileDescriptor resolve(URL downloadUrl) throws FileTransferServiceException; +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/CustomAppReleaseWrapper.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/CustomAppReleaseWrapper.java index af4d6b6dbd..71d210eeee 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/CustomAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/CustomAppReleaseWrapper.java @@ -83,6 +83,44 @@ public class CustomAppReleaseWrapper { @ApiModelProperty(name = "icon", value = "banner of the application") private Base64File banner; + private boolean remoteStatus; + + public boolean isRemoteStatus() { + return remoteStatus; + } + + public void setRemoteStatus(boolean remoteStatus) { + this.remoteStatus = remoteStatus; + } + + private String artifactLink; + private List screenshotLinks; + private String iconLink; + private String bannerLink; + + public String getArtifactLink() { + return artifactLink; + } + + public void setArtifactLink(String artifactLink) { + this.artifactLink = artifactLink; + } + + public List getScreenshotLinks() { + return screenshotLinks; + } + + public void setScreenshotLinks(List screenshotLinks) { + this.screenshotLinks = screenshotLinks; + } + + public String getIconLink() { + return iconLink; + } + + public void setIconLink(String iconLink) { + this.iconLink = iconLink; + } public String getReleaseType() { return releaseType; @@ -173,4 +211,12 @@ public class CustomAppReleaseWrapper { public void setBanner(Base64File banner) { this.banner = banner; } + + public String getBannerLink() { + return bannerLink; + } + + public void setBannerLink(String bannerLink) { + this.bannerLink = bannerLink; + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/EntAppReleaseWrapper.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/EntAppReleaseWrapper.java index 91ad28aae5..1a77c6d0be 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/EntAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/EntAppReleaseWrapper.java @@ -86,6 +86,44 @@ public class EntAppReleaseWrapper { @ApiModelProperty(name = "icon", value = "banner of the application") private Base64File banner; + private boolean remoteStatus; + + public boolean isRemoteStatus() { + return remoteStatus; + } + + public void setRemoteStatus(boolean remoteStatus) { + this.remoteStatus = remoteStatus; + } + + private String artifactLink; + private List screenshotLinks; + private String iconLink; + private String bannerLink; + + public String getArtifactLink() { + return artifactLink; + } + + public void setArtifactLink(String artifactLink) { + this.artifactLink = artifactLink; + } + + public List getScreenshotLinks() { + return screenshotLinks; + } + + public void setScreenshotLinks(List screenshotLinks) { + this.screenshotLinks = screenshotLinks; + } + + public String getIconLink() { + return iconLink; + } + + public void setIconLink(String iconLink) { + this.iconLink = iconLink; + } public String getReleaseType() { return releaseType; @@ -174,4 +212,12 @@ public class EntAppReleaseWrapper { public void setBanner(Base64File banner) { this.banner = banner; } + + public String getBannerLink() { + return bannerLink; + } + + public void setBannerLink(String bannerLink) { + this.bannerLink = bannerLink; + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/PublicAppReleaseWrapper.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/PublicAppReleaseWrapper.java index 0bc46c6dbd..9962ff4000 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/PublicAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/PublicAppReleaseWrapper.java @@ -86,6 +86,18 @@ public class PublicAppReleaseWrapper { @ApiModelProperty(name = "icon", value = "banner of the application") private Base64File banner; + private boolean remoteStatus; + + public boolean isRemoteStatus() { + return remoteStatus; + } + + public void setRemoteStatus(boolean remoteStatus) { + this.remoteStatus = remoteStatus; + } + private List screenshotLinks; + private String iconLink; + private String bannerLink; public String getReleaseType() { return releaseType; @@ -162,4 +174,28 @@ public class PublicAppReleaseWrapper { public void setBanner(Base64File banner) { this.banner = banner; } + + public List getScreenshotLinks() { + return screenshotLinks; + } + + public void setScreenshotLinks(List screenshotLinks) { + this.screenshotLinks = screenshotLinks; + } + + public String getIconLink() { + return iconLink; + } + + public void setIconLink(String iconLink) { + this.iconLink = iconLink; + } + + public String getBannerLink() { + return bannerLink; + } + + public void setBannerLink(String bannerLink) { + this.bannerLink = bannerLink; + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/TransferLinkWrapper.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/TransferLinkWrapper.java new file mode 100644 index 0000000000..41d9b4c25c --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/TransferLinkWrapper.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.common.wrapper; + +public class TransferLinkWrapper { + private String directTransferLink; + private String relativeTransferLink; + + public String getDirectTransferLink() { + return directTransferLink; + } + + public void setDirectTransferLink(String directTransferLink) { + this.directTransferLink = directTransferLink; + } + + public String getRelativeTransferLink() { + return relativeTransferLink; + } + + public void setRelativeTransferLink(String relativeTransferLink) { + this.relativeTransferLink = relativeTransferLink; + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/WebAppReleaseWrapper.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/WebAppReleaseWrapper.java index 10b3d75249..2eae49742c 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/WebAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/WebAppReleaseWrapper.java @@ -77,6 +77,42 @@ public class WebAppReleaseWrapper { @ApiModelProperty(name = "icon", value = "banner of the application") private Base64File banner; + private boolean remoteStatus; + + public boolean isRemoteStatus() { + return remoteStatus; + } + + public void setRemoteStatus(boolean remoteStatus) { + this.remoteStatus = remoteStatus; + } + private List screenshotLinks; + private String iconLink; + private String bannerLink; + + public List getScreenshotLinks() { + return screenshotLinks; + } + + public void setScreenshotLinks(List screenshotLinks) { + this.screenshotLinks = screenshotLinks; + } + + public String getIconLink() { + return iconLink; + } + + public void setIconLink(String iconLink) { + this.iconLink = iconLink; + } + + public String getBannerLink() { + return bannerLink; + } + + public void setBannerLink(String bannerLink) { + this.bannerLink = bannerLink; + } public String getReleaseType() { return releaseType; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml index 053d54db25..ed00b9b0f9 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core application-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml @@ -105,6 +105,9 @@ ${basedir}/target/coverage-reports/jacoco-unit.exec file:src/test/resources/log4j.properties + 8280 + 8280 + test @@ -112,7 +115,6 @@ - org.apache.httpcomponents httpclient @@ -367,6 +369,26 @@ org.wso2.carbon.ntask.core provided + + com.squareup.okhttp3 + okhttp + compile + + + com.squareup.okio + okio + + + + + com.squareup.okio + okio + + + org.wso2.carbon.multitenancy + org.wso2.carbon.tenant.mgt + compile + diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java index ffa85b260d..3d460fb4db 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationDAO.java @@ -238,4 +238,52 @@ public interface ApplicationDAO { int getApplicationCount(Filter filter, int deviceTypeId, int tenantId) throws ApplicationManagementDAOException; void deleteApplication(int appId, int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete favourite applications of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteAppFavouritesByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Application category mapping of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteApplicationCategoryMappingByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Application categories of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteApplicationCategoriesByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Application tags mapping of Tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteApplicationTagsMappingByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Application tags of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteApplicationTagsByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Applications of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteApplicationsByTenant(int tenantId) throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationReleaseDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationReleaseDAO.java index cd893979dd..8314388798 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationReleaseDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ApplicationReleaseDAO.java @@ -127,4 +127,12 @@ public interface ApplicationReleaseDAO { */ List getReleaseByPackages(List packages, int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Application releases of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteReleasesByTenant(int tenantId) throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/LifecycleStateDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/LifecycleStateDAO.java index 3f8656f858..ecf8b1e807 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/LifecycleStateDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/LifecycleStateDAO.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.application.mgt.core.dao; import io.entgra.device.mgt.core.application.mgt.common.LifecycleState; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.exception.LifeCycleManagementDAOException; import java.util.List; @@ -75,4 +76,11 @@ public interface LifecycleStateDAO { */ String getAppReleaseCreatedUsername(int appId, String uuid, int tenantId) throws LifeCycleManagementDAOException; - } + /** + * Delete Application lifecycle states of tenant + * + * @param tenantId Tenant ID + * @throws LifeCycleManagementDAOException thrown if an error occurs while deleting data + */ + void deleteAppLifecycleStatesByTenant(int tenantId) throws LifeCycleManagementDAOException; +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ReviewDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ReviewDAO.java index 9a12859b5c..8fcc3abb54 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ReviewDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/ReviewDAO.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.application.mgt.core.dao; import io.entgra.device.mgt.core.application.mgt.common.response.Review; import io.entgra.device.mgt.core.application.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.application.mgt.common.dto.ReviewDTO; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.exception.ReviewManagementDAOException; import java.util.List; @@ -119,4 +120,11 @@ import java.util.List; void deleteAllChildCommentsOfReview(int rootParentId, int tenantId) throws ReviewManagementDAOException; + /** + * Delete reviews of a tenant + * + * @param tenantId Tenant ID + * @throws ReviewManagementDAOException thrown if an error occurs while deleting data + */ + void deleteReviewsByTenant(int tenantId) throws ReviewManagementDAOException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SPApplicationDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SPApplicationDAO.java index 712a0e28b3..aa84543e6f 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SPApplicationDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SPApplicationDAO.java @@ -128,4 +128,20 @@ public interface SPApplicationDAO { * @throws ApplicationManagementDAOException if any db error occurred */ void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Identity servers of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteIdentityServerByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Service provide mapping details of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteSPApplicationMappingByTenant(int tenantId) throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java index 804a4a29e2..3213db3484 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/SubscriptionDAO.java @@ -264,4 +264,52 @@ public interface SubscriptionDAO { * @throws ApplicationManagementDAOException if error occurred while retrieving the app details */ Activity getOperationAppDetails(int operationId, int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Operation mapping details of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteOperationMappingByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete device subscriptions of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteDeviceSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete group subscriptions of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteGroupSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete role subscriptions of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteRoleSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete user subscriptions of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteUserSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete scheduled subscription details of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteScheduledSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VisibilityDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VisibilityDAO.java index 45664a9d61..49290336c4 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VisibilityDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VisibilityDAO.java @@ -17,6 +17,7 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.exception.VisibilityManagementDAOException; import java.util.List; @@ -70,4 +71,11 @@ public interface VisibilityDAO { */ void deleteAppUnrestrictedRoles(int applicationId, int tenantId) throws VisibilityManagementDAOException; + /** + * Delete app unrestricted roles of tenant + * + * @param tenantId Tenant ID + * @throws VisibilityManagementDAOException thrown if an error occurs while deleting data + */ + void deleteAppUnrestrictedRolesByTenant(int tenantId) throws VisibilityManagementDAOException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VppApplicationDAO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VppApplicationDAO.java index 02aec95174..a9b637ab86 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VppApplicationDAO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/VppApplicationDAO.java @@ -43,4 +43,28 @@ public interface VppApplicationDAO { int addAssociation(VppAssociationDTO vppAssociationDTO, int tenantId) throws ApplicationManagementDAOException; VppAssociationDTO updateAssociation(VppAssociationDTO vppAssociationDTO, int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete associations of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteAssociationByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete Vpp users of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteVppUserByTenant(int tenantId) throws ApplicationManagementDAOException; + + /** + * Delete assets of tenant + * + * @param tenantId Tenant ID + * @throws ApplicationManagementDAOException thrown if an error occurs while deleting data + */ + void deleteAssetsByTenant(int tenantId) throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index 09bea80fa5..7c71880fa6 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -1884,4 +1884,165 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic } } + @Override + public void deleteAppFavouritesByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete app of tenant of id " + tenantId + " from favourites"); + } + String sql = "DELETE FROM AP_APP_FAVOURITES " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing app from favourites of tenant " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing app of tenant of id " + tenantId + " from favourites. " + + "Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void deleteApplicationCategoryMappingByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application category mapping of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_APP_CATEGORY_MAPPING " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing application category mapping of tenant" + +tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing application category mapping of tenant of id " + tenantId + + "Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void deleteApplicationCategoriesByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application category of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_APP_CATEGORY " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing application category of tenant " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing application category of tenant of id " + tenantId + + "Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void deleteApplicationTagsMappingByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application tags mapping of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_APP_TAG_MAPPING " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing application tags mapping of tenant" + +tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing application tags mapping of tenant of id " + tenantId + + "Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void deleteApplicationTagsByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application tags of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_APP_TAG " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing application tags of tenant" + +tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing application tags of tenant of id " + tenantId + + "Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void deleteApplicationsByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete applications of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_APP " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing applications of tenant" + +tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing applications of tenant of id " + tenantId + + "Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java index 400ff9e7ef..70ad2f4e17 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java @@ -624,4 +624,30 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements throw new ApplicationManagementDAOException(msg, e); } } -} + + @Override + public void deleteReleasesByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application releases of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_APP_RELEASE " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing application release of tenant" + +tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing application release of tenant of id " + tenantId + + "Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java index 5a5b130157..0b4d14073b 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java @@ -484,4 +484,57 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } } + @Override + public void deleteIdentityServerByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete identity server of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete an identity server of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete an identity server of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteSPApplicationMappingByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete applications of tenant of id " + tenantId + + " from service providers"); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing applications of tenant" + +tenantId+ "from service providers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing applications of tenant of id " + tenantId + + "from service providers. Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java index d190d88296..993e9476f4 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java @@ -485,4 +485,57 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } } + @Override + public void deleteIdentityServerByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete identity server of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete an identity server of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete an identity server of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteSPApplicationMappingByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete applications of tenant of id " + tenantId + + " from service providers"); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing applications of tenant" + +tenantId+ "from service providers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing applications of tenant of id " + tenantId + + "from service providers. Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java index d599d0db69..bc1fc660e9 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java @@ -485,4 +485,57 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S } } + @Override + public void deleteIdentityServerByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete identity server of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete an identity server of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete an identity server of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteSPApplicationMappingByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete applications of tenant of id " + tenantId + + " from service providers"); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing applications of tenant" + +tenantId+ "from service providers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing applications of tenant of id " + tenantId + + "from service providers. Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java index 3061b96a86..5b6b2571ab 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java @@ -485,4 +485,57 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S } } + @Override + public void deleteIdentityServerByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete identity server of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete an identity server of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete an identity server of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteSPApplicationMappingByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete applications of tenant of id " + tenantId + + " from service providers"); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing applications of tenant" + +tenantId+ "from service providers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing applications of tenant of id " + tenantId + + "from service providers. Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateDAOImpl.java index f1fdece953..c32afcd79a 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateDAOImpl.java @@ -114,6 +114,32 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif } } + @Override + public void deleteAppLifecycleStatesByTenant(int tenantId) throws LifeCycleManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete app lifecycle states of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_APP_LIFECYCLE_STATE " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing app lifecycle states of tenant" + +tenantId; + log.error(msg, e); + throw new LifeCycleManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing app lifecycle states of tenant of id " + tenantId + + "Executed Query: " + sql; + log.error(msg, e); + throw new LifeCycleManagementDAOException(msg, e); + } + } + @Override public List getLifecycleStates(int appReleaseId, int tenantId) throws LifeCycleManagementDAOException { try { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/GenericReviewDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/GenericReviewDAOImpl.java index 075ba6b01f..e31db113ef 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/GenericReviewDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/review/GenericReviewDAOImpl.java @@ -602,4 +602,30 @@ public class GenericReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO { throw new ReviewManagementDAOException(msg, e); } } + + @Override + public void deleteReviewsByTenant(int tenantId) throws ReviewManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete app reviews of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_APP_REVIEW " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing app reviews of tenant " + + tenantId; + log.error(msg, e); + throw new ReviewManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing app reviews of tenant of id " + tenantId + + "Executed Query: " + sql; + log.error(msg, e); + throw new ReviewManagementDAOException(msg, e); + } + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java index 457de13bee..79e7b76660 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java @@ -1476,4 +1476,163 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc throw new ApplicationManagementDAOException(msg, e); } } + + @Override + public void deleteOperationMappingByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete operation mapping of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_APP_SUB_OP_MAPPING " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete operation mapping of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete operation mapping of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteRoleSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete role subscription of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_ROLE_SUBSCRIPTION " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete role subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete role subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void deleteUserSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete user subscription of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_USER_SUBSCRIPTION " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete user subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete user subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void deleteGroupSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete user subscription of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_GROUP_SUBSCRIPTION " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete group subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete group subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteScheduledSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete scheduled subscription of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_SCHEDULED_SUBSCRIPTION " + + "WHERE APPLICATION_UUID IN " + + "(SELECT UUID FROM AP_APP_RELEASE WHERE TENANT_ID = ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeBatch(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete scheduled subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete scheduled subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteDeviceSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete device subscription of the tenant of id: " + tenantId); + } + String sql = "DELETE FROM AP_DEVICE_SUBSCRIPTION " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete device subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete device subscription of tenant of id " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java index ea0b0fb758..1033af9bef 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java @@ -176,4 +176,32 @@ public class GenericVisibilityDAOImpl extends AbstractDAOImpl implements Visibil throw new VisibilityManagementDAOException(msg, e); } } + + @Override + public void deleteAppUnrestrictedRolesByTenant(int tenantId) throws VisibilityManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete Application unrestricted roles of tenant of ID " + + tenantId); + } + String sql = "DELETE " + + "FROM AP_UNRESTRICTED_ROLE " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete application unrestricted roles of tenant: " + + tenantId; + log.error(msg, e); + throw new VisibilityManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to delete application unrestricted roles which of" + + " tenant Id " + tenantId + ". executed query: " + sql; + log.error(msg, e); + throw new VisibilityManagementDAOException(msg, e); + } + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/GenericVppApplicationDAOImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/GenericVppApplicationDAOImpl.java index 7ff06c41eb..8cc62b4dbc 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/GenericVppApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/dao/impl/vpp/GenericVppApplicationDAOImpl.java @@ -506,4 +506,84 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp throw new ApplicationManagementDAOException(msg, e); } } + + @Override + public void deleteAssetsByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application releases of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_ASSETS " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing application release of tenant " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing application release of tenant of id " + tenantId + + " Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteVppUserByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete vpp user of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_VPP_USER " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing vpp user of tenant " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing vpp user of tenant of id " + tenantId + + "Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void deleteAssociationByTenant(int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete association of tenant of id " + tenantId); + } + String sql = "DELETE FROM AP_VPP_ASSOCIATION " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection when removing association of tenant" + + tenantId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "SQL Error occurred while removing association of tenant of id " + tenantId + + " Executed Query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/exception/FileTransferServiceHelperUtilException.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/exception/FileTransferServiceHelperUtilException.java new file mode 100644 index 0000000000..4dd05689cb --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/exception/FileTransferServiceHelperUtilException.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.core.exception; + +public class FileTransferServiceHelperUtilException extends Exception { + public FileTransferServiceHelperUtilException(String msg) { + super(msg); + } + + public FileTransferServiceHelperUtilException(String msg, Throwable t) { + super(msg, t); + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java index c897fcf65c..56567155ed 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java @@ -18,11 +18,16 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; +import io.entgra.device.mgt.core.application.mgt.common.exception.FileDownloaderServiceException; +import io.entgra.device.mgt.core.application.mgt.common.exception.FileTransferServiceException; import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; +import io.entgra.device.mgt.core.application.mgt.core.dao.*; +import io.entgra.device.mgt.core.application.mgt.core.exception.*; import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import org.apache.commons.codec.digest.DigestUtils; @@ -75,11 +80,6 @@ import io.entgra.device.mgt.core.application.mgt.common.wrapper.PublicAppWrapper import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppReleaseWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppWrapper; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; -import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; -import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationReleaseDAO; -import io.entgra.device.mgt.core.application.mgt.core.dao.LifecycleStateDAO; -import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO; -import io.entgra.device.mgt.core.application.mgt.core.dao.VisibilityDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import io.entgra.device.mgt.core.application.mgt.core.util.APIUtil; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; @@ -96,6 +96,8 @@ import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementEx import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.stratos.common.beans.TenantInfoBean; +import org.wso2.carbon.tenant.mgt.services.TenantMgtAdminService; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; @@ -103,6 +105,8 @@ import javax.ws.rs.core.Response; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -128,6 +132,8 @@ public class ApplicationManagerImpl implements ApplicationManager { private SubscriptionDAO subscriptionDAO; private LifecycleStateManager lifecycleStateManager; private SPApplicationDAO spApplicationDAO; + private VppApplicationDAO vppApplicationDAO; + private ReviewDAO reviewDAO; public ApplicationManagerImpl() { initDataAccessObjects(); @@ -141,10 +147,61 @@ public class ApplicationManagerImpl implements ApplicationManager { this.applicationReleaseDAO = ApplicationManagementDAOFactory.getApplicationReleaseDAO(); this.subscriptionDAO = ApplicationManagementDAOFactory.getSubscriptionDAO(); this.spApplicationDAO = ApplicationManagementDAOFactory.getSPApplicationDAO(); + this.vppApplicationDAO = ApplicationManagementDAOFactory.getVppApplicationDAO(); + this.reviewDAO = ApplicationManagementDAOFactory.getCommentDAO(); } @Override public Application createApplication(T app, boolean isPublished) throws ApplicationManagementException { + return createApplicationBasedOnRemoteStatus(app, isPublished); + } + + /** + * Create the application based on the release wrapper's remote status. If the remote status is true, then + * the application creation will take place asynchronously. + * @param app Application release wrapper + * @param isPublished Publish status + * @return {@link Application} + * @throws ApplicationManagementException Throws when error occurred while application creation + */ + @SuppressWarnings("unchecked") + private Application createApplicationBasedOnRemoteStatus(T app, boolean isPublished) throws ApplicationManagementException { + if (ApplicationManagementUtil.getRemoteStatus(app)) { + List releaseWrappers = ApplicationManagementUtil.deriveApplicationWithoutRelease(app); + Application createdApplication = triggerApplicationCreation(app, isPublished); + if (createdApplication == null) { + throw new ApplicationManagementException("Null retrieved for created application."); + } + try { + if (releaseWrappers != null && !releaseWrappers.isEmpty()) { + if (app instanceof ApplicationWrapper) { + ((ApplicationWrapper) app).setEntAppReleaseWrappers((List) releaseWrappers); + createApplicationReleaseBasedOnRemoteStatus(createdApplication.getId(), + ((ApplicationWrapper) app).getEntAppReleaseWrappers().get(0), isPublished); + } else if (app instanceof CustomAppWrapper) { + ((CustomAppWrapper) app).setCustomAppReleaseWrappers((List) releaseWrappers); + createApplicationReleaseBasedOnRemoteStatus(createdApplication.getId(), + ((CustomAppWrapper) app).getCustomAppReleaseWrappers().get(0), isPublished); + } else { + throw new ApplicationManagementException("Unsupported release wrapper received"); + } + } + return createdApplication; + } catch (ResourceManagementException e) { + throw new ApplicationManagementException("Error encountered while creating deploying artifact", e); + } + } + return triggerApplicationCreation(app, isPublished); + } + + /** + * Trigger the application creation process + * @param app Application release wrapper + * @param isPublished Publish status + * @return {@link Application} + * @throws ApplicationManagementException Throws when error occurred while creating the application + */ + private Application triggerApplicationCreation(T app, boolean isPublished) throws ApplicationManagementException { ApplicationDTO applicationDTO = uploadReleaseArtifactIfExist(app); try { ConnectionManagerUtil.beginDBTransaction(); @@ -172,22 +229,110 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + /** + * Create application release based on remote status. If the remote status is true, then the + * application release creation will take place asynchronously. + * @param appId Application id + * @param releaseWrapper Release wrapper + * @param isPublished Publish status + * @return {@link Application} + * @throws ApplicationManagementException Throws when error occurred while deploying the release + * @throws ResourceManagementException Throws when error occurred while deploying the release + */ + private ApplicationRelease createApplicationReleaseBasedOnRemoteStatus(int appId, T releaseWrapper, boolean isPublished) + throws ApplicationManagementException, ResourceManagementException { + if (ApplicationManagementUtil.getRemoteStatusFromWrapper(releaseWrapper)) { + triggerReleaseAsynchronously(appId, releaseWrapper, isPublished); + } else { + if (releaseWrapper instanceof EntAppReleaseWrapper) { + return triggerEntAppRelease(appId, (EntAppReleaseWrapper) releaseWrapper, isPublished); + } + + if (releaseWrapper instanceof CustomAppReleaseWrapper) { + return triggerCustomAppRelease(appId, (CustomAppReleaseWrapper) releaseWrapper, isPublished); + } + + throw new ApplicationManagementException("Unsupported release wrapper received"); + } + return new ApplicationRelease(); + } + + /** + * Trigger release creation asynchronously + * @param appId Application id + * @param releaseWrapper Release wrapper + * @param isPublished Publish status + */ + private void triggerReleaseAsynchronously(int appId, T releaseWrapper, boolean isPublished) { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + new Thread(() -> { + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); + if (releaseWrapper instanceof EntAppReleaseWrapper && + ((EntAppReleaseWrapper) releaseWrapper).isRemoteStatus()) { + triggerEntAppRelease(appId, (EntAppReleaseWrapper) releaseWrapper, isPublished); + }else if (releaseWrapper instanceof CustomAppReleaseWrapper && + ((CustomAppReleaseWrapper) releaseWrapper).isRemoteStatus()) { + triggerCustomAppRelease(appId, (CustomAppReleaseWrapper) releaseWrapper, isPublished); + } else { + throw new ApplicationManagementException("Unsupported release wrapper received"); + } + } catch (ApplicationManagementException | ResourceManagementException e) { + log.error("Error encountered while deploying remote application release", e); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + }).start(); + } + + /** + * Trigger enterprise application creation + * @param appId Application id + * @param releaseWrapper Release wrapper + * @param isPublished Publish status + * @return {@link ApplicationRelease} + * @throws ApplicationManagementException Throws when error encountered while creating enterprise application + */ + private ApplicationRelease triggerEntAppRelease(int appId, EntAppReleaseWrapper releaseWrapper, boolean isPublished) + throws ApplicationManagementException{ + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + try { + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIconLink(), releaseWrapper.getScreenshotLinks(), + releaseWrapper.getArtifactLink(), releaseWrapper.getBannerLink()); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + releaseDTO = uploadEntAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName(), true); + try { + return createRelease(applicationDTO, releaseDTO, ApplicationType.ENTERPRISE, isPublished); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating ent app release for application with the name: " + applicationDTO.getName(); + log.error(msg, e); + deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); + throw new ApplicationManagementException(msg, e); + } + } catch (MalformedURLException e) { + String msg = "Malformed URL link received as a downloadable link"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (FileDownloaderServiceException e) { + String msg = "Error encountered while downloading application release artifacts for app id " + appId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + @Override public ApplicationRelease createEntAppRelease(int appId, EntAppReleaseWrapper releaseWrapper, boolean isPublished) throws ApplicationManagementException { - ApplicationManager applicationManager = APIUtil.getApplicationManager(); - ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), releaseWrapper.getScreenshots(), - releaseWrapper.getBinaryFile(), releaseWrapper.getBanner()); - ApplicationDTO applicationDTO = applicationManager.getApplication(appId); - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); - releaseDTO = uploadEntAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName(), true); try { - return createRelease(applicationDTO, releaseDTO, ApplicationType.ENTERPRISE, isPublished); - } catch (ApplicationManagementException e) { - String msg = "Error occurred while creating ent app release for application with the name: " + applicationDTO.getName(); + return createApplicationReleaseBasedOnRemoteStatus(appId, releaseWrapper, isPublished); + } catch (ResourceManagementException e) { + String msg = "Error occurred while creating enterprise app release for the app id " + appId; log.error(msg, e); - deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); throw new ApplicationManagementException(msg, e); } } @@ -196,17 +341,27 @@ public class ApplicationManagerImpl implements ApplicationManager { public ApplicationRelease createWebAppRelease(int appId, WebAppReleaseWrapper releaseWrapper, boolean isPublished) throws ApplicationManagementException, ResourceManagementException { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - ApplicationDTO applicationDTO = applicationManager.getApplication(appId); - ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), null, releaseWrapper.getBanner()); - ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); - releaseDTO = uploadWebAppReleaseArtifacts(releaseDTO, artifact); try { - return createRelease(applicationDTO, releaseDTO, ApplicationType.WEB_CLIP, isPublished); - } catch (ApplicationManagementException e) { - String msg = "Error occurred while creating web app release for application with the name: " + applicationDTO.getName(); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIconLink(), releaseWrapper.getScreenshotLinks(), + null, releaseWrapper.getBannerLink()); + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + releaseDTO = uploadWebAppReleaseArtifacts(releaseDTO, artifact); + try { + return createRelease(applicationDTO, releaseDTO, ApplicationType.WEB_CLIP, isPublished); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating web app release for application with the name: " + applicationDTO.getName(); + log.error(msg, e); + deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); + throw new ApplicationManagementException(msg, e); + } + } catch (MalformedURLException e) { + String msg = "Malformed URL link received as a downloadable link"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (FileDownloaderServiceException e) { + String msg = "Error encountered while downloading application release artifacts"; log.error(msg, e); - deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); throw new ApplicationManagementException(msg, e); } } @@ -215,38 +370,69 @@ public class ApplicationManagerImpl implements ApplicationManager { public ApplicationRelease createPubAppRelease(int appId, PublicAppReleaseWrapper releaseWrapper, boolean isPublished) throws ResourceManagementException, ApplicationManagementException { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - ApplicationDTO applicationDTO = applicationManager.getApplication(appId); - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), null, releaseWrapper.getBanner()); - ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); - releaseDTO = uploadPubAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName()); try { - return createRelease(applicationDTO, releaseDTO, ApplicationType.PUBLIC, isPublished); - } catch (ApplicationManagementException e) { - String msg = "Error occurred while creating ent public release for application with the name: " + applicationDTO.getName(); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIconLink(), releaseWrapper.getScreenshotLinks(), + null, releaseWrapper.getBannerLink()); + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + releaseDTO = uploadPubAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName()); + try { + return createRelease(applicationDTO, releaseDTO, ApplicationType.PUBLIC, isPublished); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating ent public release for application with the name: " + applicationDTO.getName(); + log.error(msg, e); + deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); + throw new ApplicationManagementException(msg, e); + } + } catch (MalformedURLException e) { + String msg = "Malformed URL link received as a downloadable link"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (FileDownloaderServiceException e) { + String msg = "Error encountered while downloading application release artifacts"; log.error(msg, e); - deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); throw new ApplicationManagementException(msg, e); } } @Override public ApplicationRelease createCustomAppRelease(int appId, CustomAppReleaseWrapper releaseWrapper, boolean isPublished) + throws ApplicationManagementException { + try { + return createApplicationReleaseBasedOnRemoteStatus(appId, releaseWrapper, isPublished); + } catch (ResourceManagementException e) { + String msg = "Error occurred while creating enterprise app release"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + + private ApplicationRelease triggerCustomAppRelease(int appId, CustomAppReleaseWrapper releaseWrapper, boolean isPublished) throws ResourceManagementException, ApplicationManagementException { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - ApplicationDTO applicationDTO = applicationManager.getApplication(appId); - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), releaseWrapper.getBanner()); - ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); - releaseDTO = uploadCustomAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName()); try { - return createRelease(applicationDTO, releaseDTO, ApplicationType.CUSTOM, isPublished); - } catch (ApplicationManagementException e) { - String msg = "Error occurred while creating custom app release for application with the name: " + applicationDTO.getName(); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIconLink(), releaseWrapper.getScreenshotLinks(), + releaseWrapper.getArtifactLink(), releaseWrapper.getBannerLink()); + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + releaseDTO = uploadCustomAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName()); + try { + return createRelease(applicationDTO, releaseDTO, ApplicationType.CUSTOM, isPublished); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating custom app release for application with the name: " + applicationDTO.getName(); + log.error(msg, e); + deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); + throw new ApplicationManagementException(msg, e); + } + } catch (MalformedURLException e) { + String msg = "Malformed URL link received as a downloadable link"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (FileDownloaderServiceException e) { + String msg = "Error encountered while downloading application release artifacts"; log.error(msg, e); - deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); throw new ApplicationManagementException(msg, e); } } @@ -279,27 +465,27 @@ public class ApplicationManagerImpl implements ApplicationManager { if (app instanceof ApplicationWrapper) { ApplicationWrapper wrapper = (ApplicationWrapper) app; EntAppReleaseWrapper releaseWrapper = wrapper.getEntAppReleaseWrappers().get(0); - artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), releaseWrapper.getBanner()); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIconLink(), releaseWrapper.getScreenshotLinks(), + releaseWrapper.getArtifactLink(), releaseWrapper.getBannerLink()); releaseDTO = uploadEntAppReleaseArtifacts(releaseDTO, artifact, wrapper.getDeviceType(), false); } else if (app instanceof PublicAppWrapper) { PublicAppWrapper wrapper = (PublicAppWrapper) app; PublicAppReleaseWrapper releaseWrapper = wrapper.getPublicAppReleaseWrappers().get(0); - artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), null, releaseWrapper.getBanner()); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIconLink(), releaseWrapper.getScreenshotLinks(), + null, releaseWrapper.getBannerLink()); releaseDTO = uploadPubAppReleaseArtifacts(releaseDTO, artifact, wrapper.getDeviceType()); } else if (app instanceof WebAppWrapper) { WebAppWrapper wrapper = (WebAppWrapper) app; WebAppReleaseWrapper releaseWrapper = wrapper.getWebAppReleaseWrappers().get(0); - artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), null, releaseWrapper.getBanner()); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIconLink(), releaseWrapper.getScreenshotLinks(), + null, releaseWrapper.getBannerLink()); releaseDTO = uploadWebAppReleaseArtifacts(releaseDTO, artifact); } else if (app instanceof CustomAppWrapper) { CustomAppWrapper wrapper = (CustomAppWrapper) app; CustomAppReleaseWrapper releaseWrapper = wrapper.getCustomAppReleaseWrappers().get(0); - artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), releaseWrapper.getBanner()); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIconLink(), releaseWrapper.getScreenshotLinks(), + releaseWrapper.getArtifactLink(), releaseWrapper.getBannerLink()); try { releaseDTO = uploadCustomAppReleaseArtifacts(releaseDTO, artifact, wrapper.getDeviceType()); } catch (ResourceManagementException e) { @@ -316,7 +502,17 @@ public class ApplicationManagerImpl implements ApplicationManager { String msg = "Error Occurred when uploading artifacts of the web clip: " + applicationDTO.getName(); log.error(msg); throw new ApplicationManagementException(msg, e); + } catch (MalformedURLException e) { + String msg = "Malformed URL link received as a downloadable link"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (FileDownloaderServiceException e) { + String msg = "Error encountered while downloading application release artifacts"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); } + // TODO: artifact URLs are not working for Windows AppX installations https://roadmap.entgra.net/issues/11010 + //ApplicationManagementUtil.addInstallerPathToMetadata(releaseDTO); applicationDTO.getApplicationReleaseDTOs().clear(); applicationDTO.getApplicationReleaseDTOs().add(releaseDTO); return applicationDTO; @@ -857,7 +1053,8 @@ public class ApplicationManagerImpl implements ApplicationManager { ApplicationArtifact applicationArtifact, int tenantId) throws ResourceManagementException { ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); - applicationReleaseDTO.setIconName(applicationArtifact.getIconName()); + applicationReleaseDTO.setIconName(ApplicationManagementUtil.sanitizeName + (applicationArtifact.getIconName(), Constants.ICON_NAME)); applicationReleaseDTO.setBannerName(applicationArtifact.getBannerName()); Map screenshots = applicationArtifact.getScreenshots(); @@ -866,11 +1063,14 @@ public class ApplicationManagerImpl implements ApplicationManager { int counter = 1; for (String scName : screenshotNames) { if (counter == 1) { - applicationReleaseDTO.setScreenshotName1(scName); + applicationReleaseDTO.setScreenshotName1(ApplicationManagementUtil.sanitizeName + (scName, Constants.SCREENSHOT_NAME + counter)); } else if (counter == 2) { - applicationReleaseDTO.setScreenshotName2(scName); + applicationReleaseDTO.setScreenshotName2(ApplicationManagementUtil.sanitizeName + (scName, Constants.SCREENSHOT_NAME + counter)); } else if (counter == 3) { - applicationReleaseDTO.setScreenshotName3(scName); + applicationReleaseDTO.setScreenshotName3(ApplicationManagementUtil.sanitizeName + (scName, Constants.SCREENSHOT_NAME + counter)); } counter++; } @@ -898,7 +1098,8 @@ public class ApplicationManagerImpl implements ApplicationManager { applicationStorageManager .deleteAppReleaseArtifact(applicationReleaseDTO.getAppHashValue(), Constants.ICON_ARTIFACT, applicationReleaseDTO.getIconName(), tenantId); - applicationReleaseDTO.setIconName(applicationArtifact.getIconName()); + applicationReleaseDTO.setIconName(ApplicationManagementUtil.sanitizeName + (applicationArtifact.getIconName(), Constants.ICON_NAME)); } if (!StringUtils.isEmpty(applicationArtifact.getBannerName())){ applicationStorageManager @@ -921,17 +1122,20 @@ public class ApplicationManagerImpl implements ApplicationManager { applicationStorageManager .deleteAppReleaseArtifact(applicationReleaseDTO.getAppHashValue(), folderPath, applicationReleaseDTO.getScreenshotName1(), tenantId); - applicationReleaseDTO.setScreenshotName1(scName); + applicationReleaseDTO.setScreenshotName1(ApplicationManagementUtil.sanitizeName + (scName, Constants.SCREENSHOT_NAME + counter)); } else if (counter == 2) { applicationStorageManager .deleteAppReleaseArtifact(applicationReleaseDTO.getAppHashValue(), folderPath, applicationReleaseDTO.getScreenshotName2(), tenantId); - applicationReleaseDTO.setScreenshotName2(scName); + applicationReleaseDTO.setScreenshotName2(ApplicationManagementUtil.sanitizeName + (scName, Constants.SCREENSHOT_NAME + counter)); } else if (counter == 3) { applicationStorageManager .deleteAppReleaseArtifact(applicationReleaseDTO.getAppHashValue(), folderPath, applicationReleaseDTO.getScreenshotName3(), tenantId); - applicationReleaseDTO.setScreenshotName3(scName); + applicationReleaseDTO.setScreenshotName3(ApplicationManagementUtil.sanitizeName + (scName, Constants.SCREENSHOT_NAME + counter)); } counter++; } @@ -2415,20 +2619,22 @@ public class ApplicationManagerImpl implements ApplicationManager { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); ApplicationDTO applicationDTO = getApplication(applicationId); + String sanitizedName = ApplicationManagementUtil.sanitizeName(applicationUpdateWrapper.getName(), + Constants.ApplicationProperties.NAME ); try { ConnectionManagerUtil.beginDBTransaction(); - if (!StringUtils.isEmpty(applicationUpdateWrapper.getName()) && !applicationDTO.getName() - .equals(applicationUpdateWrapper.getName())) { + if (!StringUtils.isEmpty(sanitizedName) && !applicationDTO.getName() + .equals(sanitizedName)) { if (applicationDAO - .isExistingAppName(applicationUpdateWrapper.getName().trim(), applicationDTO.getDeviceTypeId(), + .isExistingAppName(sanitizedName.trim(), applicationDTO.getDeviceTypeId(), tenantId)) { - String msg = "Already an application registered with same name " + applicationUpdateWrapper.getName() + String msg = "Already an application registered with same name " + sanitizedName + ". Hence you can't update the application name from " + applicationDTO.getName() + " to " - + applicationUpdateWrapper.getName(); + + sanitizedName; log.error(msg); throw new BadRequestException(msg); } - applicationDTO.setName(applicationUpdateWrapper.getName()); + applicationDTO.setName(sanitizedName); } if (!StringUtils.isEmpty(applicationUpdateWrapper.getSubMethod()) && !applicationDTO.getSubType() .equals(applicationUpdateWrapper.getSubMethod())) { @@ -3124,11 +3330,13 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public ApplicationRelease updateEntAppRelease(String releaseUuid, EntAppReleaseWrapper entAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException { + public ApplicationRelease updateEntAppRelease(String releaseUuid, EntAppReleaseWrapper entAppReleaseWrapper) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { + ApplicationArtifact applicationArtifact = ApplicationManagementUtil. + constructApplicationArtifact(entAppReleaseWrapper.getIconLink(), entAppReleaseWrapper.getScreenshotLinks(), + entAppReleaseWrapper.getArtifactLink(), entAppReleaseWrapper.getBannerLink()); ConnectionManagerUtil.beginDBTransaction(); ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(releaseUuid, tenantId); DeviceType deviceTypeObj = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); @@ -3195,17 +3403,25 @@ public class ApplicationManagerImpl implements ApplicationManager { + "UUID:" + releaseUuid; log.error(msg, e); throw new ApplicationManagementException(msg, e); + } catch (MalformedURLException e) { + throw new ApplicationManagementException("Malformed downloadable URL received for the Public app " + + "release UUID: " + releaseUuid); + } catch (FileDownloaderServiceException e) { + throw new ApplicationManagementException("Error encountered while downloading artifact for the Public app " + + "release UUID: " + releaseUuid); } finally { ConnectionManagerUtil.closeDBConnection(); } } @Override - public ApplicationRelease updatePubAppRelease(String releaseUuid, PublicAppReleaseWrapper publicAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException { + public ApplicationRelease updatePubAppRelease(String releaseUuid, PublicAppReleaseWrapper publicAppReleaseWrapper) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { + ApplicationArtifact applicationArtifact = ApplicationManagementUtil. + constructApplicationArtifact(publicAppReleaseWrapper.getIconLink(), publicAppReleaseWrapper.getScreenshotLinks(), + null, publicAppReleaseWrapper.getBannerLink()); ConnectionManagerUtil.beginDBTransaction(); ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(releaseUuid, tenantId); validateAppReleaseUpdating(publicAppReleaseWrapper, applicationDTO, applicationArtifact, @@ -3264,17 +3480,25 @@ public class ApplicationManagerImpl implements ApplicationManager { + "release UUID:" + releaseUuid; log.error(msg, e); throw new ApplicationManagementException(msg, e); + } catch (MalformedURLException e) { + throw new ApplicationManagementException("Malformed downloadable URL received for the Public app " + + "release UUID: " + releaseUuid); + } catch (FileDownloaderServiceException e) { + throw new ApplicationManagementException("Error encountered while downloading artifact for the Public app " + + "release UUID: " + releaseUuid); } finally { ConnectionManagerUtil.closeDBConnection(); } } @Override - public ApplicationRelease updateWebAppRelease(String releaseUuid, WebAppReleaseWrapper webAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException { + public ApplicationRelease updateWebAppRelease(String releaseUuid, WebAppReleaseWrapper webAppReleaseWrapper) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { + ApplicationArtifact applicationArtifact = ApplicationManagementUtil. + constructApplicationArtifact(webAppReleaseWrapper.getIconLink(), webAppReleaseWrapper.getScreenshotLinks(), + null, webAppReleaseWrapper.getBannerLink()); ConnectionManagerUtil.beginDBTransaction(); ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(releaseUuid, tenantId); validateAppReleaseUpdating(webAppReleaseWrapper, applicationDTO, applicationArtifact, @@ -3329,18 +3553,27 @@ public class ApplicationManagerImpl implements ApplicationManager { + "release UUID:" + releaseUuid; log.error(msg, e); throw new ApplicationManagementException(msg, e); + } catch (MalformedURLException e) { + throw new ApplicationManagementException("Malformed downloadable URL received for the Public app " + + "release UUID: " + releaseUuid); + } catch (FileDownloaderServiceException e) { + throw new ApplicationManagementException("Error encountered while downloading artifact for the Public app " + + "release UUID: " + releaseUuid); } finally { ConnectionManagerUtil.closeDBConnection(); } } @Override - public ApplicationRelease updateCustomAppRelease(String releaseUuid, - CustomAppReleaseWrapper customAppReleaseWrapper, ApplicationArtifact applicationArtifact) + public ApplicationRelease updateCustomAppRelease(String releaseUuid, CustomAppReleaseWrapper customAppReleaseWrapper) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); try { + ApplicationArtifact applicationArtifact = ApplicationManagementUtil. + constructApplicationArtifact(customAppReleaseWrapper.getIconLink(), + customAppReleaseWrapper.getScreenshotLinks(), customAppReleaseWrapper.getArtifactLink(), + customAppReleaseWrapper.getBannerLink()); ConnectionManagerUtil.beginDBTransaction(); ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(releaseUuid, tenantId); AtomicReference applicationReleaseDTO = new AtomicReference<>( @@ -3459,6 +3692,12 @@ public class ApplicationManagerImpl implements ApplicationManager { + "UUID:" + releaseUuid; log.error(msg, e); throw new ApplicationManagementException(msg, e); + } catch (MalformedURLException e) { + throw new ApplicationManagementException("Malformed downloadable URL received for the Public app " + + "release UUID: " + releaseUuid); + } catch (FileDownloaderServiceException e) { + throw new ApplicationManagementException("Error encountered while downloading artifact for the Public app " + + "release UUID: " + releaseUuid); } finally { ConnectionManagerUtil.closeDBConnection(); } @@ -3894,30 +4133,24 @@ public class ApplicationManagerImpl implements ApplicationManager { public void validateEntAppReleaseCreatingRequest(EntAppReleaseWrapper releaseWrapper, String deviceType) throws RequestValidatingException, ApplicationManagementException { validateReleaseCreatingRequest(releaseWrapper, deviceType); - validateBinaryArtifact(releaseWrapper.getBinaryFile()); - validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); } @Override public void validateCustomAppReleaseCreatingRequest(CustomAppReleaseWrapper releaseWrapper, String deviceType) throws RequestValidatingException, ApplicationManagementException { validateReleaseCreatingRequest(releaseWrapper, deviceType); - validateBinaryArtifact(releaseWrapper.getBinaryFile()); - validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); } @Override public void validateWebAppReleaseCreatingRequest(WebAppReleaseWrapper releaseWrapper) throws RequestValidatingException, ApplicationManagementException { validateReleaseCreatingRequest(releaseWrapper, Constants.ANY); - validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); } @Override public void validatePublicAppReleaseCreatingRequest(PublicAppReleaseWrapper releaseWrapper, String deviceType) throws RequestValidatingException, ApplicationManagementException { validateReleaseCreatingRequest(releaseWrapper, deviceType); - validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); validatePublicAppReleasePackageName(releaseWrapper.getPackageName()); } @@ -4158,4 +4391,145 @@ public class ApplicationManagerImpl implements ApplicationManager { throw new ApplicationManagementException(msg, e); } } + + @Override + public void deleteApplicationDataOfTenant(int tenantId) throws ApplicationManagementException { + if (log.isDebugEnabled()) { + log.debug("Request is received to delete application related data of tenant with ID: " + tenantId); + } + try { + ConnectionManagerUtil.beginDBTransaction(); + + vppApplicationDAO.deleteAssociationByTenant(tenantId); + vppApplicationDAO.deleteVppUserByTenant(tenantId); + vppApplicationDAO.deleteAssetsByTenant(tenantId); + reviewDAO.deleteReviewsByTenant(tenantId); + subscriptionDAO.deleteOperationMappingByTenant(tenantId); + subscriptionDAO.deleteDeviceSubscriptionByTenant(tenantId); + subscriptionDAO.deleteGroupSubscriptionByTenant(tenantId); + subscriptionDAO.deleteRoleSubscriptionByTenant(tenantId); + subscriptionDAO.deleteUserSubscriptionByTenant(tenantId); + applicationDAO.deleteAppFavouritesByTenant(tenantId); + applicationDAO.deleteApplicationTagsMappingByTenant(tenantId); + applicationDAO.deleteApplicationTagsByTenant(tenantId); + applicationDAO.deleteApplicationCategoryMappingByTenant(tenantId); + applicationDAO.deleteApplicationCategoriesByTenant(tenantId); + subscriptionDAO.deleteScheduledSubscriptionByTenant(tenantId); + lifecycleStateDAO.deleteAppLifecycleStatesByTenant(tenantId); + applicationReleaseDAO.deleteReleasesByTenant(tenantId); + visibilityDAO.deleteAppUnrestrictedRolesByTenant(tenantId); + spApplicationDAO.deleteSPApplicationMappingByTenant(tenantId); + spApplicationDAO.deleteIdentityServerByTenant(tenantId); + applicationDAO.deleteApplicationsByTenant(tenantId); + APIUtil.getApplicationStorageManager().deleteAppFolderOfTenant(tenantId); + + ConnectionManagerUtil.commitDBTransaction(); + } catch (DBConnectionException e) { + String msg = "Error occurred while observing the database connection to delete applications for tenant with ID: " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Database access error is occurred when getting applications for tenant with ID: " + tenantId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (LifeCycleManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while deleting life-cycle state data of application releases of the tenant" + + " of ID: " + tenantId ; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ReviewManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while deleting reviews of application releases of the applications" + + " of tenant ID: " + tenantId ; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationStorageManagementException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while deleting App folder of tenant" + + " of tenant ID: " + tenantId ; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException { + int tenantId; + try{ + TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService(); + TenantInfoBean tenantInfoBean = tenantMgtAdminService.getTenant(tenantDomain); + tenantId = tenantInfoBean.getTenantId(); + + } catch (Exception e) { + String msg = "Error getting tenant ID from domain: " + + tenantDomain; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + + try { + ConnectionManagerUtil.beginDBTransaction(); + + vppApplicationDAO.deleteAssociationByTenant(tenantId); + vppApplicationDAO.deleteVppUserByTenant(tenantId); + vppApplicationDAO.deleteAssetsByTenant(tenantId); + reviewDAO.deleteReviewsByTenant(tenantId); + subscriptionDAO.deleteOperationMappingByTenant(tenantId); + subscriptionDAO.deleteDeviceSubscriptionByTenant(tenantId); + subscriptionDAO.deleteGroupSubscriptionByTenant(tenantId); + subscriptionDAO.deleteRoleSubscriptionByTenant(tenantId); + subscriptionDAO.deleteUserSubscriptionByTenant(tenantId); + applicationDAO.deleteAppFavouritesByTenant(tenantId); + applicationDAO.deleteApplicationTagsMappingByTenant(tenantId); + applicationDAO.deleteApplicationTagsByTenant(tenantId); + applicationDAO.deleteApplicationCategoryMappingByTenant(tenantId); + applicationDAO.deleteApplicationCategoriesByTenant(tenantId); + subscriptionDAO.deleteScheduledSubscriptionByTenant(tenantId); + lifecycleStateDAO.deleteAppLifecycleStatesByTenant(tenantId); + applicationReleaseDAO.deleteReleasesByTenant(tenantId); + visibilityDAO.deleteAppUnrestrictedRolesByTenant(tenantId); + spApplicationDAO.deleteSPApplicationMappingByTenant(tenantId); + spApplicationDAO.deleteIdentityServerByTenant(tenantId); + applicationDAO.deleteApplicationsByTenant(tenantId); + APIUtil.getApplicationStorageManager().deleteAppFolderOfTenant(tenantId); + + ConnectionManagerUtil.commitDBTransaction(); + } catch (DBConnectionException e) { + String msg = "Error occurred while observing the database connection to delete applications for tenant with ID: " + + tenantId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Database access error is occurred when getting applications for tenant with ID: " + tenantId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (LifeCycleManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while deleting life-cycle state data of application releases of the tenant" + + " of ID: " + tenantId ; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ReviewManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while deleting reviews of application releases of the applications" + + " of tenant ID: " + tenantId ; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationStorageManagementException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while deleting App folder of tenant" + + " of tenant ID: " + tenantId ; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java index a79a3d23ee..158361232c 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java @@ -310,4 +310,18 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager throw new StorageManagementException(msg, e); } } + + @Override + public void deleteAppFolderOfTenant(int tenantId) throws ApplicationStorageManagementException{ + String folderPath = storagePath + File.separator + tenantId; + File folder = new File(folderPath); + if (folder.exists()) { + try { + StorageManagementUtil.delete(folder); + } catch (IOException e) { + throw new ApplicationStorageManagementException( + "Error occurred while deleting App folder of tenant:" + tenantId, e); + } + } + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileDownloaderServiceProvider.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileDownloaderServiceProvider.java new file mode 100644 index 0000000000..f8fe6f2f94 --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileDownloaderServiceProvider.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.core.impl; + +import io.entgra.device.mgt.core.application.mgt.common.FileDescriptor; +import io.entgra.device.mgt.core.application.mgt.common.FileMetaEntry; +import io.entgra.device.mgt.core.application.mgt.common.TransferLink; +import io.entgra.device.mgt.core.application.mgt.common.exception.FileDownloaderServiceException; +import io.entgra.device.mgt.core.application.mgt.common.exception.FileTransferServiceException; +import io.entgra.device.mgt.core.application.mgt.common.services.FileDownloaderService; +import io.entgra.device.mgt.core.application.mgt.common.services.FileTransferService; +import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder; +import io.entgra.device.mgt.core.application.mgt.core.util.Constants; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +public class FileDownloaderServiceProvider { + private static final Log log = LogFactory.getLog(FileDownloaderServiceProvider.class); + private static final FileTransferService fileTransferService = DataHolder.getInstance().getFileTransferService(); + private static final LocalFileDownloaderService localFileDownloaderService = new LocalFileDownloaderService(); + private static final RemoteFileDownloaderService remoteFileDownloaderService = new RemoteFileDownloaderService(); + public static FileDownloaderService getFileDownloaderService(URL downloadUrl) throws FileDownloaderServiceException { + try { + if (fileTransferService.isExistsOnLocal(downloadUrl)) { + return localFileDownloaderService; + } + return remoteFileDownloaderService; + } catch (FileTransferServiceException e) { + String msg = "Error encountered while acquiring file downloader service"; + log.error(msg, e); + throw new FileDownloaderServiceException(msg, e); + } + } + + /** + * Class holing the implementation of the local file downloading service + */ + private static class LocalFileDownloaderService implements FileDownloaderService { + @Override + public FileDescriptor download(URL downloadUrl) throws FileDownloaderServiceException { + try { + return fileTransferService.resolve(downloadUrl); + } catch (FileTransferServiceException e) { + String msg = "Error encountered while downloading file pointing by " + downloadUrl; + log.error(msg, e); + throw new FileDownloaderServiceException(msg, e); + } + } + } + + /** + * Class holing the implementation of the remote file downloading service + */ + private static class RemoteFileDownloaderService implements FileDownloaderService { + private static final OkHttpClient okhttpClient = + new OkHttpClient.Builder().connectTimeout(500, TimeUnit.MILLISECONDS).build(); + @Override + public FileDescriptor download(URL downloadUrl) throws FileDownloaderServiceException { + FileMetaEntry fileMetaEntry = getFileMetaEntry(downloadUrl); + try { + TransferLink transferLink = fileTransferService.generateUploadLink(fileMetaEntry); + FileDescriptor fileDescriptor = fileTransferService.resolve(new URL(transferLink.getDirectTransferLink() + + "/" + fileMetaEntry.getFileName() + "." + fileMetaEntry.getExtension())); + FileUtils.copyURLToFile(downloadUrl, new File(fileDescriptor.getAbsolutePath()), + 15000, 3600000); + return fileDescriptor; + } catch (FileTransferServiceException | IOException e) { + String msg = "Error encountered while downloading file"; + log.error(msg, e); + throw new FileDownloaderServiceException(msg, e); + } + } + + /** + * Generate the {@link FileMetaEntry} from the remote file + * @param downloadUrl Remote file URL + * @return {@link FileMetaEntry} + * @throws FileDownloaderServiceException Throws when error encountered while generating {@link FileMetaEntry} + */ + private FileMetaEntry getFileMetaEntry(URL downloadUrl) throws FileDownloaderServiceException { + Request request = new Request.Builder().url(downloadUrl).head().build(); + try (Response response = okhttpClient.newCall(request).execute()) { + if (!response.isSuccessful()) { + throw new FileDownloaderServiceException("Unexpected response code received for the remote url " + downloadUrl); + } + String contentDisposition = response.header("Content-Disposition"); + String contentType = response.header("Content-Type"); + String[] fileNameSegments = extractFileNameSegmentsFromUrl(downloadUrl); + + // if the url parsing failed to resolve the file name segments + // falling to remote file name segment resolving + if (fileNameSegments == null) { + fileNameSegments = getFileNameSegments(contentDisposition, contentType); + } + + FileMetaEntry fileMetaEntry = new FileMetaEntry(); + fileMetaEntry.setSize(Long.parseLong(Objects.requireNonNull(response.header("Content-Length")))); + fileMetaEntry.setFileName(fileNameSegments[0]); + fileMetaEntry.setExtension(fileNameSegments[1]); + return fileMetaEntry; + } catch (IOException e) { + throw new FileDownloaderServiceException("IO error occurred while constructing file name for the remote url " + downloadUrl); + } + } + + /** + * Extracting file name segments by parsing the URL + * @param url Remote URL to extract file name segments + * @return Array containing file name segments or null when failed to extract + */ + public static String[] extractFileNameSegmentsFromUrl(URL url) { + if (url == null) { + if (log.isDebugEnabled()) { + log.debug("Null received as the remote URL"); + } + return null; + } + + String []urlSegments = url.toString().split("/"); + if (urlSegments.length < 1) { + if (log.isDebugEnabled()) { + log.debug("Cannot determine the file name for the remote file"); + } + return null; + } + + String fullQualifiedName = urlSegments[urlSegments.length - 1]; + String []fileNameSegments = fullQualifiedName.split("\\.(?=[^.]+$)"); + if (fileNameSegments.length != 2) { + if (log.isDebugEnabled()) { + log.debug("Error encountered when constructing file name"); + } + return null; + } + return fileNameSegments; + } + + /** + * Extract file name segments(filename & extensions) from content disposition header and content type header + * @param contentDisposition Content disposition header value + * @param contentType Content type header value + * @return Array of name segments + * @throws FileDownloaderServiceException Throws when error occurred while extracting name segments + */ + private static String[] getFileNameSegments(String contentDisposition, String contentType) throws FileDownloaderServiceException { + if (contentDisposition == null && contentType == null) { + throw new FileDownloaderServiceException("Cannot determine the file name for the remote file"); + } + + if (contentDisposition == null) { + String extension; + if (contentType.equals(Constants.MIME_TYPE_VND_ANDROID_PACKAGE_ARCHIVE)) { + extension = Constants.EXTENSION_APK; + } else if (contentType.equals(Constants.MIME_TYPE_OCTET_STREAM)) { + extension = Constants.EXTENSION_IPA; + } else if (contentType.equals(Constants.MIME_TYPE_VND_APPX)) { + extension = Constants.EXTENSION_APPX; + } else if (contentType.equals(Constants.MIME_TYPE_X_MS_INSTALLER) + || contentType.equals(Constants.MIME_TYPE_VND_MS_WINDOWS_MSI)) { + extension = Constants.EXTENSION_MSI; + } else { + String []contentTypeSegments = contentType.split("/"); + if (contentTypeSegments.length != 2) { + throw new FileDownloaderServiceException("Encountered wrong content type header value"); + } + extension = contentTypeSegments[contentTypeSegments.length - 1]; + } + return new String[]{ UUID.randomUUID().toString(), extension}; + } + + String []contentDispositionSegments = contentDisposition.split("="); + if (contentDispositionSegments.length != 2) { + throw new FileDownloaderServiceException("Error encountered when constructing file name"); + } + String fullQualifiedName = contentDispositionSegments[contentDispositionSegments.length - 1].replace("\"", ""); + String []fileNameSegments = fullQualifiedName.split("\\.(?=[^.]+$)"); + if (fileNameSegments.length != 2) { + throw new FileDownloaderServiceException("Error encountered when constructing file name"); + } + return fileNameSegments; + } + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileTransferServiceImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileTransferServiceImpl.java new file mode 100644 index 0000000000..52789308fd --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileTransferServiceImpl.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.core.impl; + +import io.entgra.device.mgt.core.application.mgt.common.ChunkDescriptor; +import io.entgra.device.mgt.core.application.mgt.common.FileDescriptor; +import io.entgra.device.mgt.core.application.mgt.common.FileMetaEntry; +import io.entgra.device.mgt.core.application.mgt.common.TransferLink; +import io.entgra.device.mgt.core.application.mgt.common.exception.FileTransferServiceException; +import io.entgra.device.mgt.core.application.mgt.common.services.FileTransferService; +import io.entgra.device.mgt.core.application.mgt.core.exception.FileTransferServiceHelperUtilException; +import io.entgra.device.mgt.core.application.mgt.core.util.FileTransferServiceHelperUtil; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.InputStream; +import java.net.URL; +import java.nio.file.FileSystems; +import java.nio.file.Path; + +public class FileTransferServiceImpl implements FileTransferService { + private final static Log log = LogFactory.getLog(FileTransferServiceImpl.class); + private static volatile FileTransferServiceImpl INSTANCE; + + private FileTransferServiceImpl() throws FileTransferServiceException { + try { + FileTransferServiceHelperUtil.createDefaultRootStructure(); + } catch (FileTransferServiceHelperUtilException e) { + String msg = "Error occurred while initializing file transfer service"; + log.error(msg, e); + throw new FileTransferServiceException(msg, e); + } + } + + public static FileTransferService getInstance() throws FileTransferServiceException{ + if (INSTANCE == null) { + synchronized (FileTransferServiceImpl.class) { + if (INSTANCE == null) { + INSTANCE = new FileTransferServiceImpl(); + } + } + } + return INSTANCE; + } + + @Override + public TransferLink generateUploadLink(FileMetaEntry fileMetaEntry) throws FileTransferServiceException { + try { + Path artifactHolder = FileTransferServiceHelperUtil.createNewArtifactHolder(fileMetaEntry); + String []pathSegments = artifactHolder.toString().split(FileSystems.getDefault().getSeparator()); + TransferLink.TransferLinkBuilder transferLinkBuilder = + new TransferLink.TransferLinkBuilder(pathSegments[pathSegments.length - 1]); + return transferLinkBuilder.build(); + } catch (FileTransferServiceHelperUtilException e) { + String msg = "Error encountered while generating upload link"; + log.error(msg, e); + throw new FileTransferServiceException(msg, e); + } + } + + @Override + public ChunkDescriptor resolve(String artifactHolder, InputStream chunk) throws FileTransferServiceException, NotFoundException { + ChunkDescriptor chunkDescriptor = new ChunkDescriptor(); + try { + FileTransferServiceHelperUtil.populateChunkDescriptor(artifactHolder, chunk, chunkDescriptor); + return chunkDescriptor; + } catch (FileTransferServiceHelperUtilException e) { + String msg = "Error occurred while resolving chuck descriptor for " + artifactHolder; + log.error(msg); + throw new FileTransferServiceException(msg, e); + } + } + + @Override + public void writeChunk(ChunkDescriptor chunkDescriptor) throws FileTransferServiceException { + try { + FileTransferServiceHelperUtil.writeChunk(chunkDescriptor); + } catch (FileTransferServiceHelperUtilException e) { + String msg = "Failed to write data to artifact located in " + chunkDescriptor.getAssociateFileDescriptor().getAbsolutePath(); + log.error(msg); + throw new FileTransferServiceException(msg, e); + } + } + + @Override + public boolean isExistsOnLocal(URL downloadUrl) throws FileTransferServiceException { + try { + return FileTransferServiceHelperUtil.resolve(downloadUrl) != null; + } catch (FileTransferServiceHelperUtilException e) { + String msg = "Error occurred while checking the existence of artifact on the local environment"; + log.error(msg, e); + throw new FileTransferServiceException(msg, e); + } + } + + @Override + public FileDescriptor resolve(URL downloadUrl) throws FileTransferServiceException { + try { + return FileTransferServiceHelperUtil.resolve(downloadUrl); + } catch (FileTransferServiceHelperUtilException e) { + String msg = "Error occurred while resolving file descriptor pointing from " + downloadUrl; + log.error(msg, e); + throw new FileTransferServiceException(msg, e); + } + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java index 267105e5f7..20cd9febbc 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java @@ -21,6 +21,7 @@ import io.entgra.device.mgt.core.application.mgt.common.config.LifecycleState; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStorageManager; import io.entgra.device.mgt.core.application.mgt.common.services.AppmDataHandler; +import io.entgra.device.mgt.core.application.mgt.common.services.FileTransferService; import io.entgra.device.mgt.core.application.mgt.common.services.ReviewManager; import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; @@ -28,6 +29,7 @@ import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationM import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import io.entgra.device.mgt.core.application.mgt.core.impl.AppmDataHandlerImpl; +import io.entgra.device.mgt.core.application.mgt.core.impl.FileTransferServiceImpl; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.application.mgt.core.task.ScheduledAppSubscriptionTaskManager; import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; @@ -123,6 +125,10 @@ public class ApplicationManagementServiceComponent { DataHolder.getInstance().setVppApplicationManager(vppApplicationManager); bundleContext.registerService(VPPApplicationManager.class.getName(), vppApplicationManager, null); + FileTransferService fileTransferService = FileTransferServiceImpl.getInstance(); + DataHolder.getInstance().setFileTransferService(fileTransferService); + bundleContext.registerService(FileTransferService.class.getName(), fileTransferService, null); + ScheduledAppSubscriptionTaskManager taskManager = new ScheduledAppSubscriptionTaskManager(); taskManager.scheduleCleanupTask(); diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java index b8905829ad..80416dcd59 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.application.mgt.core.internal; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStorageManager; import io.entgra.device.mgt.core.application.mgt.common.services.AppmDataHandler; +import io.entgra.device.mgt.core.application.mgt.common.services.FileTransferService; import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.ReviewManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; @@ -55,6 +56,7 @@ public class DataHolder { private AppmDataHandler configManager; private TaskService taskService; + private FileTransferService fileTransferService; private static final DataHolder applicationMgtDataHolder = new DataHolder(); @@ -153,4 +155,12 @@ public class DataHolder { public void setVppApplicationManager(VPPApplicationManager vppApplicationManager) { this.vppApplicationManager = vppApplicationManager; } + + public FileTransferService getFileTransferService() { + return fileTransferService; + } + + public void setFileTransferService(FileTransferService fileTransferService) { + this.fileTransferService = fileTransferService; + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java index e1ffb3418b..71dc4e87b0 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java @@ -59,4 +59,5 @@ public class ScheduledAppSubscriptionCleanupTask extends RandomlyAssignedSchedul public String getTaskName() { return TASK_NAME; } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTask.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTask.java index 0a1275b495..ffdce8e469 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTask.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/task/ScheduledAppSubscriptionTask.java @@ -145,4 +145,5 @@ public class ScheduledAppSubscriptionTask extends RandomlyAssignedScheduleTask { public String getTaskName() { return TASK_NAME; } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java index 6c359723e9..7c2034eb11 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/APIUtil.java @@ -74,6 +74,7 @@ public class APIUtil { private static volatile AppmDataHandler appmDataHandler; private static volatile VPPApplicationManager vppApplicationManager; private static volatile MetadataManagementService metadataManagementService; + private static volatile FileTransferService fileTransferService; public static SPApplicationManager getSPApplicationManager() { if (SPApplicationManager == null) { @@ -309,7 +310,8 @@ public class APIUtil { if (param instanceof ApplicationWrapper){ ApplicationWrapper applicationWrapper = (ApplicationWrapper) param; DeviceType deviceType = getDeviceTypeData(applicationWrapper.getDeviceType()); - applicationDTO.setName(applicationWrapper.getName()); + applicationDTO.setName(ApplicationManagementUtil.sanitizeName(applicationWrapper.getName(), + Constants.ApplicationProperties.NAME)); applicationDTO.setDescription(applicationWrapper.getDescription()); applicationDTO.setAppCategories(applicationWrapper.getCategories()); applicationDTO.setType(ApplicationType.ENTERPRISE.toString()); @@ -323,7 +325,8 @@ public class APIUtil { applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); } else if (param instanceof WebAppWrapper){ WebAppWrapper webAppWrapper = (WebAppWrapper) param; - applicationDTO.setName(webAppWrapper.getName()); + applicationDTO.setName(ApplicationManagementUtil.sanitizeName(webAppWrapper.getName(), + Constants.ApplicationProperties.NAME)); applicationDTO.setDescription(webAppWrapper.getDescription()); applicationDTO.setAppCategories(webAppWrapper.getCategories()); applicationDTO.setSubType(webAppWrapper.getSubMethod()); @@ -331,13 +334,14 @@ public class APIUtil { applicationDTO.setType(webAppWrapper.getType()); applicationDTO.setTags(webAppWrapper.getTags()); applicationDTO.setUnrestrictedRoles(webAppWrapper.getUnrestrictedRoles()); - applicationReleaseEntities = webAppWrapper.getWebAppReleaseWrappers() + applicationReleaseEntities = webAppWrapper.getWebAppReleaseWrappers() .stream().map(APIUtil::releaseWrapperToReleaseDTO).collect(Collectors.toList()); applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); } else if (param instanceof PublicAppWrapper) { PublicAppWrapper publicAppWrapper = (PublicAppWrapper) param; DeviceType deviceType = getDeviceTypeData(publicAppWrapper.getDeviceType()); - applicationDTO.setName(publicAppWrapper.getName()); + applicationDTO.setName(ApplicationManagementUtil.sanitizeName(publicAppWrapper.getName(), + Constants.ApplicationProperties.NAME)); applicationDTO.setDescription(publicAppWrapper.getDescription()); applicationDTO.setAppCategories(publicAppWrapper.getCategories()); applicationDTO.setType(ApplicationType.PUBLIC.toString()); @@ -352,7 +356,8 @@ public class APIUtil { } else if (param instanceof CustomAppWrapper){ CustomAppWrapper customAppWrapper = (CustomAppWrapper) param; DeviceType deviceType = getDeviceTypeData(customAppWrapper.getDeviceType()); - applicationDTO.setName(customAppWrapper.getName()); + applicationDTO.setName(ApplicationManagementUtil.sanitizeName(customAppWrapper.getName(), + Constants.ApplicationProperties.NAME)); applicationDTO.setDescription(customAppWrapper.getDescription()); applicationDTO.setAppCategories(customAppWrapper.getCategories()); applicationDTO.setType(ApplicationType.CUSTOM.toString()); @@ -491,7 +496,6 @@ public class APIUtil { List screenshotPaths = new ArrayList<>(); ApplicationRelease applicationRelease = new ApplicationRelease(); - UrlValidator urlValidator = new UrlValidator(); applicationRelease.setDescription(applicationReleaseDTO.getDescription()); applicationRelease.setVersion(applicationReleaseDTO.getVersion()); @@ -514,13 +518,8 @@ public class APIUtil { .getBannerName()); } - if (urlValidator.isValid(applicationReleaseDTO.getInstallerName())) { - applicationRelease.setInstallerPath(applicationReleaseDTO.getInstallerName()); - } else { - applicationRelease.setInstallerPath( - basePath + Constants.APP_ARTIFACT + Constants.FORWARD_SLASH + applicationReleaseDTO - .getInstallerName()); - } + applicationRelease.setInstallerPath(constructInstallerPath(applicationReleaseDTO.getInstallerName(), + applicationReleaseDTO.getAppHashValue())); if (!StringUtils.isEmpty(applicationReleaseDTO.getScreenshotName1())) { screenshotPaths @@ -541,6 +540,21 @@ public class APIUtil { return applicationRelease; } + /** + * Construct installer path + * @param installerName Installer name + * @param appHash Application hash + * @return Constructed installer path value + * @throws ApplicationManagementException Throws when error encountered while constructing installer path + */ + public static String constructInstallerPath(String installerName, String appHash) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + UrlValidator urlValidator = new UrlValidator(); + String basePath = getArtifactDownloadBaseURL() + tenantId + Constants.FORWARD_SLASH + appHash + Constants.FORWARD_SLASH; + return urlValidator.isValid(installerName) ? installerName + : basePath + Constants.APP_ARTIFACT + Constants.FORWARD_SLASH + installerName; + } + public static String getArtifactDownloadBaseURL() throws ApplicationManagementException { String host = System.getProperty(Constants.IOT_CORE_HOST); MDMConfig mdmConfig = ConfigurationManager.getInstance().getConfiguration().getMdmConfig(); @@ -587,4 +601,16 @@ public class APIUtil { } return metadataManagementService; } + + public static FileTransferService getFileTransferService() { + if (fileTransferService == null) { + synchronized (APIUtil.class) { + if (fileTransferService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + fileTransferService = (FileTransferService) ctx.getOSGiService(FileTransferService.class, null); + } + } + } + return fileTransferService; + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java index 36920d013c..846777c794 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java @@ -17,18 +17,27 @@ */ package io.entgra.device.mgt.core.application.mgt.core.util; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; import io.entgra.device.mgt.core.application.mgt.common.FileDataHolder; +import io.entgra.device.mgt.core.application.mgt.common.FileDescriptor; import io.entgra.device.mgt.core.application.mgt.common.LifecycleChanger; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ItuneAppDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.device.mgt.core.application.mgt.common.exception.FileDownloaderServiceException; +import io.entgra.device.mgt.core.application.mgt.common.exception.FileTransferServiceException; import io.entgra.device.mgt.core.application.mgt.common.exception.InvalidConfigurationException; import io.entgra.device.mgt.core.application.mgt.common.exception.RequestValidatingException; import io.entgra.device.mgt.core.application.mgt.common.response.Application; import io.entgra.device.mgt.core.application.mgt.common.response.Category; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStorageManager; +import io.entgra.device.mgt.core.application.mgt.common.services.FileTransferService; import io.entgra.device.mgt.core.application.mgt.common.services.ReviewManager; import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; @@ -45,15 +54,18 @@ import io.entgra.device.mgt.core.application.mgt.common.wrapper.WebAppWrapper; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.core.config.Extension; import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; +import io.entgra.device.mgt.core.application.mgt.core.impl.FileDownloaderServiceProvider; import io.entgra.device.mgt.core.application.mgt.core.impl.VppApplicationManagerImpl; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import io.entgra.device.mgt.core.device.mgt.core.common.util.FileUtil; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.MetadataManagementServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.jetbrains.annotations.NotNull; import java.io.ByteArrayOutputStream; import java.io.File; @@ -74,6 +86,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.TreeMap; /** @@ -159,6 +172,49 @@ public class ApplicationManagementUtil { return applicationArtifact; } + public static ApplicationArtifact constructApplicationArtifact(String iconLink, List screenshotLinks, String artifactLink, String bannerLink) + throws MalformedURLException, FileDownloaderServiceException { + ApplicationArtifact applicationArtifact = new ApplicationArtifact(); + FileDescriptor fileDescriptor; + if (artifactLink != null) { + URL artifactLinkUrl = new URL(artifactLink); + fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(artifactLinkUrl).download(artifactLinkUrl); + applicationArtifact.setInstallerName(fileDescriptor.getFullQualifiedName()); + applicationArtifact.setInstallerStream(fileDescriptor.getFile()); + } + + if (iconLink != null) { + URL iconLinkUrl = new URL(iconLink); + fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(iconLinkUrl).download(iconLinkUrl); + applicationArtifact.setIconName(fileDescriptor.getFullQualifiedName()); + applicationArtifact.setIconStream(fileDescriptor.getFile()); + } + + if (bannerLink != null) { + URL bannerLinkUrl = new URL(bannerLink); + fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(bannerLinkUrl).download(bannerLinkUrl); + applicationArtifact.setBannerName(fileDescriptor.getFullQualifiedName()); + applicationArtifact.setBannerStream(fileDescriptor.getFile()); + } + + if (screenshotLinks != null) { + Map screenshotData = new TreeMap<>(); + // This is to handle cases in which multiple screenshots have the same name + Map screenshotNameCount = new HashMap<>(); + URL screenshotLinkUrl; + for (String screenshotLink : screenshotLinks) { + screenshotLinkUrl = new URL(screenshotLink); + fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(screenshotLinkUrl).download(screenshotLinkUrl); + String screenshotName = fileDescriptor.getFullQualifiedName(); + screenshotNameCount.put(screenshotName, screenshotNameCount.getOrDefault(screenshotName, 0) + 1); + screenshotName = FileUtil.generateDuplicateFileName(screenshotName, screenshotNameCount.get(screenshotName)); + screenshotData.put(screenshotName, fileDescriptor.getFile()); + } + applicationArtifact.setScreenshots(screenshotData); + } + return applicationArtifact; + } + /** * * @param base64File Base64File that should be converted to FileDataHolder bean @@ -251,6 +307,41 @@ public class ApplicationManagementUtil { throw new IllegalArgumentException("Provided bean does not belong to an Application Wrapper"); } + public static boolean getRemoteStatus(T appWrapper) { + if (!isReleaseAvailable(appWrapper)) { + return false; + } + if (appWrapper instanceof ApplicationWrapper) { + return getRemoteStatusFromWrapper(((ApplicationWrapper) appWrapper).getEntAppReleaseWrappers().get(0)); + } + if (appWrapper instanceof PublicAppWrapper) { + return getRemoteStatusFromWrapper(((PublicAppWrapper) appWrapper).getPublicAppReleaseWrappers().get(0)); + } + if (appWrapper instanceof WebAppWrapper) { + return getRemoteStatusFromWrapper(((WebAppWrapper) appWrapper).getWebAppReleaseWrappers().get(0)); + } + if (appWrapper instanceof CustomAppWrapper) { + return getRemoteStatusFromWrapper(((CustomAppWrapper) appWrapper).getCustomAppReleaseWrappers().get(0)); + } + throw new IllegalArgumentException("Provided bean does not belong to an Application Wrapper"); + } + + public static boolean getRemoteStatusFromWrapper(T releaseWrapper) { + if (releaseWrapper instanceof EntAppReleaseWrapper) { + return ((EntAppReleaseWrapper) releaseWrapper).isRemoteStatus(); + } + if (releaseWrapper instanceof PublicAppReleaseWrapper) { + return ((PublicAppReleaseWrapper) releaseWrapper).isRemoteStatus(); + } + if (releaseWrapper instanceof WebAppReleaseWrapper) { + return ((WebAppReleaseWrapper) releaseWrapper).isRemoteStatus(); + } + if (releaseWrapper instanceof CustomAppReleaseWrapper) { + return ((CustomAppReleaseWrapper) releaseWrapper).isRemoteStatus(); + } + throw new IllegalArgumentException("Provided bean does not belong to an Release Wrapper"); + } + public static T getInstance(Extension extension, Class cls) throws InvalidConfigurationException { try { Class theClass = Class.forName(extension.getClassName()); @@ -279,13 +370,12 @@ public class ApplicationManagementUtil { ApplicationManager applicationManager = APIUtil.getApplicationManager(); List categories = applicationManager.getRegisteredCategories(); if (product != null && product.getVersion() != null) { - // Generate artifacts - ApplicationArtifact applicationArtifact = generateArtifacts(product); List packageNamesOfApps = new ArrayList<>(); packageNamesOfApps.add(product.getPackageName()); List existingApps = applicationManager.getApplications(packageNamesOfApps); + PublicAppReleaseWrapper publicAppReleaseWrapper = generatePublicAppReleaseWrapper(product); if (existingApps != null && existingApps.size() > 0) { Application app = existingApps.get(0); @@ -293,7 +383,6 @@ public class ApplicationManagementUtil { ApplicationUpdateWrapper applicationUpdateWrapper = generatePubAppUpdateWrapper(product, categories); applicationManager.updateApplication(app.getId(), applicationUpdateWrapper); - PublicAppReleaseWrapper publicAppReleaseWrapper = new PublicAppReleaseWrapper(); if (app.getSubMethod() .equalsIgnoreCase(Constants.ApplicationProperties.FREE_SUB_METHOD)) { publicAppReleaseWrapper.setPrice(0.0); @@ -306,56 +395,48 @@ public class ApplicationManagementUtil { publicAppReleaseWrapper.setVersion(product.getVersion()); publicAppReleaseWrapper.setSupportedOsVersions("4.0-12.3"); applicationManager.updatePubAppRelease(app.getApplicationReleases().get(0).getUuid(), - publicAppReleaseWrapper, applicationArtifact); + publicAppReleaseWrapper); return; } } else { // Generate App wrapper PublicAppWrapper publicAppWrapper = generatePubAppWrapper(product, categories); - PublicAppReleaseWrapper appReleaseWrapper = new PublicAppReleaseWrapper(); - - if (publicAppWrapper.getSubMethod() - .equalsIgnoreCase(Constants.ApplicationProperties.FREE_SUB_METHOD)) { - appReleaseWrapper.setPrice(0.0); - } else { - appReleaseWrapper.setPrice(1.0); - } - - appReleaseWrapper.setDescription(product.getDescription()); - appReleaseWrapper.setReleaseType("ga"); - appReleaseWrapper.setVersion(product.getVersion()); - appReleaseWrapper.setPackageName(product.getPackageName()); - appReleaseWrapper.setSupportedOsVersions("4.0-12.3"); publicAppWrapper.setPublicAppReleaseWrappers( - Arrays.asList(new PublicAppReleaseWrapper[]{appReleaseWrapper})); - - try { - updateImages(appReleaseWrapper, applicationArtifact.getIconName(), - applicationArtifact.getIconStream(), applicationArtifact.getScreenshots()); - - Application application = applicationManager.createApplication(publicAppWrapper, false); - if (application != null && (application.getApplicationReleases().get(0).getCurrentStatus() == null - || application.getApplicationReleases().get(0).getCurrentStatus().equals("CREATED"))) { - String uuid = application.getApplicationReleases().get(0).getUuid(); - LifecycleChanger lifecycleChanger = new LifecycleChanger(); - lifecycleChanger.setAction("IN-REVIEW"); - applicationManager.changeLifecycleState(uuid, lifecycleChanger); - lifecycleChanger.setAction("APPROVED"); - applicationManager.changeLifecycleState(uuid, lifecycleChanger); - lifecycleChanger.setAction("PUBLISHED"); - applicationManager.changeLifecycleState(uuid, lifecycleChanger); - } - } catch (IOException e) { - String msg = "Error while downloading images of release."; - log.error(msg); - throw new ApplicationManagementException(msg, e); + Arrays.asList(new PublicAppReleaseWrapper[]{publicAppReleaseWrapper})); + + Application application = applicationManager.createApplication(publicAppWrapper, false); + if (application != null && (application.getApplicationReleases().get(0).getCurrentStatus() == null + || application.getApplicationReleases().get(0).getCurrentStatus().equals("CREATED"))) { + String uuid = application.getApplicationReleases().get(0).getUuid(); + LifecycleChanger lifecycleChanger = new LifecycleChanger(); + lifecycleChanger.setAction("IN-REVIEW"); + applicationManager.changeLifecycleState(uuid, lifecycleChanger); + lifecycleChanger.setAction("APPROVED"); + applicationManager.changeLifecycleState(uuid, lifecycleChanger); + lifecycleChanger.setAction("PUBLISHED"); + applicationManager.changeLifecycleState(uuid, lifecycleChanger); } } } } + private static PublicAppReleaseWrapper generatePublicAppReleaseWrapper(ItuneAppDTO product) { + PublicAppReleaseWrapper publicAppReleaseWrapper = new PublicAppReleaseWrapper(); + publicAppReleaseWrapper.setDescription(product.getDescription()); + publicAppReleaseWrapper.setReleaseType("ga"); + publicAppReleaseWrapper.setVersion(product.getVersion()); + publicAppReleaseWrapper.setPackageName(product.getPackageName()); + publicAppReleaseWrapper.setSupportedOsVersions("4.0-12.3"); + publicAppReleaseWrapper.setIconLink(product.getIconURL()); + publicAppReleaseWrapper.setRemoteStatus(false); + List screenshotUrls = new ArrayList<>(Collections.nCopies(3, product.getIconURL())); + publicAppReleaseWrapper.setScreenshotLinks(screenshotUrls); + publicAppReleaseWrapper.setPrice(1.0); + return publicAppReleaseWrapper; + } + private static PublicAppWrapper generatePubAppWrapper(ItuneAppDTO product, List categories) { PublicAppWrapper publicAppWrapper = new PublicAppWrapper(); publicAppWrapper.setName(product.getTitle()); @@ -535,4 +616,102 @@ public class ApplicationManagementUtil { packageNamesOfApps.add(adamId); return applicationManager.getApplications(packageNamesOfApps); } + + /** + * Sanitize app names and shorten icon/screenshot file names + * + * @param originalName Original name of the file which is being uploaded + * @param type Type - Name/Artifact(Icon, Screenshot, etc.) + * @return Sanitized and shortened file name + */ + public static String sanitizeName(String originalName, String type) { + String sanitizedName = originalName.replaceAll(Constants.APP_NAME_REGEX, ""); + if (Constants.ApplicationProperties.NAME.equals(type) && sanitizedName.length() > Constants.MAX_APP_NAME_CHARACTERS) { + sanitizedName = sanitizedName.substring(0, Constants.MAX_APP_NAME_CHARACTERS); + return sanitizedName; + } else if (Constants.ICON_NAME.equals(type) || Constants.SCREENSHOT_NAME.equals(type)) { + // Shortening icon/screenshot names + String fileExtension = ""; + int dotIndex = originalName.lastIndexOf('.'); + if (dotIndex >= 0) { + fileExtension = originalName.substring(dotIndex); + } + return type + fileExtension; + } else { + return sanitizedName; + } + } + + public static List deriveApplicationWithoutRelease(T app) { + List releaseWrappers = null; + if (app instanceof ApplicationWrapper) { + ApplicationWrapper applicationWrapper = (ApplicationWrapper) app; + releaseWrappers = applicationWrapper.getEntAppReleaseWrappers(); + applicationWrapper.setEntAppReleaseWrappers(Collections.emptyList()); + } + if (app instanceof CustomAppWrapper) { + CustomAppWrapper applicationWrapper = (CustomAppWrapper) app; + releaseWrappers = applicationWrapper.getCustomAppReleaseWrappers(); + applicationWrapper.setCustomAppReleaseWrappers(Collections.emptyList()); + } + return releaseWrappers; + } + + /** + * Add installer path metadata value to windows applications + * @param applicationReleaseDTO {@link ApplicationReleaseDTO} + * @throws ApplicationManagementException Throws when error encountered while updating the app metadata + */ + public static void addInstallerPathToMetadata(ApplicationReleaseDTO applicationReleaseDTO) + throws ApplicationManagementException { + if (applicationReleaseDTO.getMetaData() == null) return; + Gson gson = new Gson(); + String installerPath = APIUtil.constructInstallerPath(applicationReleaseDTO.getInstallerName(), applicationReleaseDTO.getAppHashValue()); + String[] fileNameSegments = extractNameSegments(applicationReleaseDTO, installerPath); + String extension = fileNameSegments[fileNameSegments.length - 1]; + if (!Objects.equals(extension, "appx") && !Objects.equals(extension, "msi")) { + return; + } + + String installerPaths = "[ {" + + "\"key\": \"Content_Uri\", " + + "\"value\" : \"" + installerPath + "\"" + + "}]"; + + if (Objects.equals(extension, "appx")) { + installerPaths = "[ {" + + "\"key\": \"Package_Url\", " + + "\"value\" : \"" + installerPath + "\"" + + "}]"; + } + + JsonArray parsedMetadataList = gson.fromJson(applicationReleaseDTO.getMetaData(), JsonArray.class); + JsonArray installerPathsArray = gson.fromJson(installerPaths, JsonArray.class); + parsedMetadataList.addAll(installerPathsArray); + applicationReleaseDTO.setMetaData(gson.toJson(parsedMetadataList)); + } + + /** + * Extract name segments from installer path + * @param applicationReleaseDTO {@link ApplicationReleaseDTO} + * @param installerPath Installer path + * @return Extracted file name segments + * @throws ApplicationManagementException Throws when error encountered while extracting name segments from installer path + */ + private static String[] extractNameSegments(ApplicationReleaseDTO applicationReleaseDTO, String installerPath) + throws ApplicationManagementException { + String []installerPathSegments = installerPath.split("/"); + if (installerPathSegments.length == 0) { + throw new ApplicationManagementException("Received malformed url for installer path of the app : " + + applicationReleaseDTO.getInstallerName()); + } + String fullQualifiedName = installerPathSegments[installerPathSegments.length - 1]; + String []fileNameSegments = fullQualifiedName.split("\\.(?=[^.]+$)"); + if (fileNameSegments.length != 2) { + throw new ApplicationManagementException("Received malformed url for installer path of the app : " + + applicationReleaseDTO.getInstallerName()); + } + return fileNameSegments; + } + } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java index 767b5e2bd2..b5b5fd5154 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java @@ -214,4 +214,20 @@ public class Constants { public static final String ASSOCIATION_DEVICE = "ASSOCIATION_DEVICE"; public static final String ASSOCIATION_USER = "ASSOCIATION_USER"; } + + /** + * App name sanitization related constants + */ + public static final int MAX_APP_NAME_CHARACTERS = 350; + public static final String APP_NAME_REGEX = "[^a-zA-Z0-9.\\s-]"; + + public static final String EXTENSION_APK = ".apk"; + public static final String EXTENSION_IPA = ".ipa"; + public static final String EXTENSION_MSI = ".msi"; + public static final String EXTENSION_APPX = ".appx"; + public static final String MIME_TYPE_OCTET_STREAM = "application/octet-stream"; + public static final String MIME_TYPE_VND_ANDROID_PACKAGE_ARCHIVE = "application/vnd.android.package-archive"; + public static final String MIME_TYPE_VND_MS_WINDOWS_MSI = "application/vnd.ms-windows.msi"; + public static final String MIME_TYPE_X_MS_INSTALLER = "application/x-ms-installer"; + public static final String MIME_TYPE_VND_APPX = "application/vnd.appx"; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java new file mode 100644 index 0000000000..570998ebef --- /dev/null +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java @@ -0,0 +1,237 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.application.mgt.core.util; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.application.mgt.common.ChunkDescriptor; +import io.entgra.device.mgt.core.application.mgt.common.FileDescriptor; +import io.entgra.device.mgt.core.application.mgt.common.FileMetaEntry; +import io.entgra.device.mgt.core.application.mgt.core.exception.FileTransferServiceHelperUtilException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.Objects; +import java.util.UUID; + +public class FileTransferServiceHelperUtil { + private static final Log log = LogFactory.getLog(FileTransferServiceHelperUtil.class); + private static final String ROOT = "iot-artifact-holder"; + private static final String SYSTEM_PROPERTY_TEMP_DIR = "java.io.tmpdir"; + private static final String META_ENTRY_FILE_NAME = ".meta.json"; + private static final Gson gson = new Gson(); + public static void createDefaultRootStructure() throws FileTransferServiceHelperUtilException { + try { + Path root = Paths.get(System.getProperty(SYSTEM_PROPERTY_TEMP_DIR), ROOT); + if (Files.notExists(root)) { + setMinimumPermissions(Files.createDirectory(root)); + } + + if (!Files.isDirectory(root)) { + throw new FileTransferServiceHelperUtilException(root.toAbsolutePath() + " is not a directory"); + } + setMinimumPermissions(root); + } catch (IOException e) { + String msg = "Error encountered while creating default artifact root structure"; + log.error(msg, e); + throw new FileTransferServiceHelperUtilException(msg, e); + } + } + + public static Path createNewArtifactHolder(FileMetaEntry fileMetaEntry) throws FileTransferServiceHelperUtilException { + try { + Path artifactHolder = Paths.get(System.getProperty(SYSTEM_PROPERTY_TEMP_DIR), ROOT, UUID.randomUUID().toString()); + if (Files.exists(artifactHolder)) { + throw new FileTransferServiceHelperUtilException("Artifact holder already exists in " + artifactHolder); + } + setMinimumPermissions(Files.createDirectory(artifactHolder)); + createMetaEntry(fileMetaEntry, artifactHolder); + createArtifactFile(fileMetaEntry, artifactHolder); + return artifactHolder; + } catch (IOException e) { + String msg = "Error occurred while creating artifact holder"; + log.error(msg, e); + throw new FileTransferServiceHelperUtilException(msg, e); + } + } + + public static void populateChunkDescriptor(String artifactHolder, InputStream chunk, ChunkDescriptor chunkDescriptor) + throws FileTransferServiceHelperUtilException, NotFoundException { + Path holder = locateArtifactHolder(artifactHolder); + Path metaEntry = locateMetaEntry(holder); + chunkDescriptor.setChunk(chunk); + FileDescriptor fileDescriptor = new FileDescriptor(); + populateFileDescriptor(metaEntry, holder, fileDescriptor); + chunkDescriptor.setAssociateFileDescriptor(fileDescriptor); + } + + public static void populateFileDescriptor(String artifactHolder, FileDescriptor fileDescriptor) + throws FileTransferServiceHelperUtilException, NotFoundException { + Path holder = locateArtifactHolder(artifactHolder); + Path metaEntry = locateMetaEntry(holder); + populateFileDescriptor(metaEntry, holder, fileDescriptor); + } + + public static void populateFileDescriptor(Path metaEntry, Path artifactHolder, FileDescriptor fileDescriptor) throws FileTransferServiceHelperUtilException { + try { + byte []metaEntryByteContent = Files.readAllBytes(metaEntry); + FileMetaEntry fileMetaEntry = gson.fromJson(new String(metaEntryByteContent, StandardCharsets.UTF_8), FileMetaEntry.class); + fileDescriptor.setFileName(fileMetaEntry.getFileName()); + fileDescriptor.setActualFileSize(fileMetaEntry.getSize()); + fileDescriptor.setFullQualifiedName(fileMetaEntry.getFileName() + "." + fileMetaEntry.getExtension()); + Path artifact = artifactHolder.resolve(fileDescriptor.getFullQualifiedName()); + fileDescriptor.setAbsolutePath(artifact.toAbsolutePath().toString()); + fileDescriptor.setExtension(fileMetaEntry.getExtension()); + fileDescriptor.setFile(Files.newInputStream(artifact)); + } catch (IOException e) { + String msg = "Error encountered while populating chuck descriptor"; + log.error(msg, e); + throw new FileTransferServiceHelperUtilException(msg, e); + } + } + + private static Path locateArtifactHolder(String artifactHolder) throws FileTransferServiceHelperUtilException, NotFoundException { + Path holder = Paths.get(System.getProperty(SYSTEM_PROPERTY_TEMP_DIR), ROOT, artifactHolder); + if (Files.notExists(holder)) { + throw new NotFoundException(holder.toAbsolutePath() + " is not exists"); + } + + if (!Files.isDirectory(holder)) { + throw new FileTransferServiceHelperUtilException(holder.toFile().getAbsolutePath() + " is not a directory"); + } + return holder; + } + + private static Path locateMetaEntry(Path artifactHolder) throws FileTransferServiceHelperUtilException { + Path metaEntry = artifactHolder.resolve(META_ENTRY_FILE_NAME); + if (Files.notExists(metaEntry) || Files.isDirectory(metaEntry)) { + throw new FileTransferServiceHelperUtilException("Can't locate " + META_ENTRY_FILE_NAME); + } + + if (!Files.isReadable(metaEntry)) { + throw new FileTransferServiceHelperUtilException("Unreadable " + META_ENTRY_FILE_NAME); + } + return metaEntry; + } + + public static void writeChunk(ChunkDescriptor chunkDescriptor) throws FileTransferServiceHelperUtilException { + if (chunkDescriptor == null) { + throw new FileTransferServiceHelperUtilException("Received null for chuck descriptor"); + } + FileDescriptor fileDescriptor = chunkDescriptor.getAssociateFileDescriptor(); + if (fileDescriptor == null) { + throw new FileTransferServiceHelperUtilException("Target file descriptor is missing for retrieved chunk"); + } + Path artifact = Paths.get(fileDescriptor.getAbsolutePath()); + try { + InputStream chuckStream = chunkDescriptor.getChunk(); + byte []chunk = new byte[chuckStream.available()]; + chuckStream.read(chunk); + Files.write(artifact, chunk, StandardOpenOption.CREATE, StandardOpenOption.SYNC, StandardOpenOption.APPEND); + } catch (IOException e) { + String msg = "Error encountered while writing to the " + artifact; + log.error(msg, e); + throw new FileTransferServiceHelperUtilException(msg, e); + } + } + + public static FileDescriptor resolve(URL downloadUrl) throws FileTransferServiceHelperUtilException { + if (downloadUrl == null) { + throw new FileTransferServiceHelperUtilException("Received null for download url"); + } + + if (!Objects.equals(System.getProperty("iot.gateway.host"), downloadUrl.getHost()) && + !Objects.equals(System.getProperty("iot.core.host"), downloadUrl.getHost())) { + if (log.isDebugEnabled()) { + log.debug("Download URL " + downloadUrl + " contains not matching host"); + } + return null; + } + + String []urlPathSegments = downloadUrl.getPath().split("/"); + if (urlPathSegments.length < 2) { + if (log.isDebugEnabled()) { + log.debug("URL patch segments contain less than 2 segments"); + } + return null; + } + + String file = urlPathSegments[urlPathSegments.length - 1]; + String artifactHolder = urlPathSegments[urlPathSegments.length - 2]; + try { + FileDescriptor fileDescriptor = new FileDescriptor(); + populateFileDescriptor(artifactHolder, fileDescriptor); + if (!Objects.equals(file, fileDescriptor.getFullQualifiedName())) { + if (log.isDebugEnabled()) { + log.debug("File name not equal to the file exists in the local"); + } + return null; + } + return fileDescriptor; + } catch (NotFoundException e) { + if (log.isDebugEnabled()) { + log.debug("Local URL not found in the system"); + } + return null; + } + } + + private static void setMinimumPermissions(Path path) throws FileTransferServiceHelperUtilException { + File file = path.toFile(); + if (!file.setReadable(true, true)) { + throw new FileTransferServiceHelperUtilException("Failed to set read permission for " + file.getAbsolutePath()); + } + + if (!file.setWritable(true, true)) { + throw new FileTransferServiceHelperUtilException("Failed to set write permission for " + file.getAbsolutePath()); + } + } + + private static void createMetaEntry(FileMetaEntry fileMetaEntry, Path artifactHolder) throws FileTransferServiceHelperUtilException { + try { + Path metaEntry = artifactHolder.resolve(META_ENTRY_FILE_NAME); + String fileMetaJsonContent = gson.toJson(fileMetaEntry); + Files.write(metaEntry, fileMetaJsonContent.getBytes(StandardCharsets.UTF_8), + StandardOpenOption.CREATE, StandardOpenOption.SYNC); + } catch (IOException e) { + throw new FileTransferServiceHelperUtilException("Error encountered while creating meta entry", e); + } + } + + private static void createArtifactFile(FileMetaEntry fileMetaEntry, Path artifactHolder) throws FileTransferServiceHelperUtilException { + try { + Path artifactFile = artifactHolder.resolve(fileMetaEntry.getFileName() + "." + fileMetaEntry.getExtension()); + fileMetaEntry.setAbsolutePath(artifactFile.toAbsolutePath().toString()); + Files.createFile(artifactFile); + setMinimumPermissions(artifactFile); + } catch (IOException e) { + throw new FileTransferServiceHelperUtilException("Error encountered while creating artifact file", e); + } + } +} diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/management/ApplicationManagementTest.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/management/ApplicationManagementTest.java index 9eac36785e..793b28d0f9 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/management/ApplicationManagementTest.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/test/java/io/entgra/device/mgt/core/application/mgt/core/management/ApplicationManagementTest.java @@ -19,8 +19,13 @@ package io.entgra.device.mgt.core.application.mgt.core.management; import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; import io.entgra.device.mgt.core.application.mgt.common.ApplicationList; +import io.entgra.device.mgt.core.application.mgt.common.ChunkDescriptor; +import io.entgra.device.mgt.core.application.mgt.common.FileMetaEntry; import io.entgra.device.mgt.core.application.mgt.common.Filter; import io.entgra.device.mgt.core.application.mgt.common.LifecycleState; +import io.entgra.device.mgt.core.application.mgt.common.TransferLink; +import io.entgra.device.mgt.core.application.mgt.common.services.FileTransferService; +import io.entgra.device.mgt.core.application.mgt.core.impl.FileTransferServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.cxf.jaxrs.ext.multipart.Attachment; @@ -52,6 +57,10 @@ import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceTypeVersion; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl; import java.io.File; +import java.io.FileInputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -98,32 +107,72 @@ public class ApplicationManagementTest extends BaseTestCase { EntAppReleaseWrapper releaseWrapper = new EntAppReleaseWrapper(); releaseWrapper.setDescription("First release"); releaseWrapper.setIsSharedWithAllTenants(false); - releaseWrapper.setMetaData("Just meta data"); + releaseWrapper.setMetaData("[{\"key\": \"Just a metadata\"}]"); releaseWrapper.setReleaseType("free"); releaseWrapper.setPrice(5.7); releaseWrapper.setSupportedOsVersions("4.0-7.0"); - File banner = new File("src/test/resources/samples/app1/banner1.jpg"); - File icon = new File("src/test/resources/samples/app1/icon.png"); - File ss1 = new File("src/test/resources/samples/app1/shot1.png"); - File ss2 = new File("src/test/resources/samples/app1/shot2.png"); - File ss3 = new File("src/test/resources/samples/app1/shot3.png"); - - Base64File bannerBase64 = new Base64File("banner", FileUtil.fileToBase64String(banner)); - Base64File iconBase64 = new Base64File("icon", FileUtil.fileToBase64String(icon)); - Base64File ss1Base64 = new Base64File("ss1", FileUtil.fileToBase64String(ss1)); - Base64File ss2Base64 = new Base64File("ss2", FileUtil.fileToBase64String(ss2)); - Base64File ss3Base64 = new Base64File("ss3", FileUtil.fileToBase64String(ss3)); - - File apk = new File("src/test/resources/samples/app1/sample.apk"); - Base64File apkBase64 = new Base64File("apk", FileUtil.fileToBase64String(apk)); - - - releaseWrapper.setBanner(bannerBase64); - releaseWrapper.setIcon(iconBase64); - releaseWrapper.setBinaryFile(apkBase64); - releaseWrapper.setScreenshots(Arrays.asList(ss1Base64, ss2Base64, ss3Base64)); + FileTransferService fileTransferService = FileTransferServiceImpl.getInstance(); + DataHolder.getInstance().setFileTransferService(fileTransferService); + + FileMetaEntry metaEntry = new FileMetaEntry(); + TransferLink transferLink; + String []segments; + ChunkDescriptor chunkDescriptor; + + metaEntry.setFileName("banner1"); + metaEntry.setExtension("jpg"); + metaEntry.setSize(179761); + transferLink = fileTransferService.generateUploadLink(metaEntry); + segments = transferLink.getRelativeTransferLink().split("/"); + chunkDescriptor = fileTransferService. + resolve(segments[segments.length-1], Files.newInputStream( + Paths.get("src/test/resources/samples/app1/banner1.jpg"))); + fileTransferService.writeChunk(chunkDescriptor); + releaseWrapper.setBannerLink(transferLink.getDirectTransferLink() + "/banner1.jpg"); + + metaEntry.setFileName("icon"); + metaEntry.setExtension("png"); + metaEntry.setSize(41236); + transferLink = fileTransferService.generateUploadLink(metaEntry); + segments = transferLink.getRelativeTransferLink().split("/"); + chunkDescriptor = fileTransferService. + resolve(segments[segments.length-1], Files.newInputStream( + Paths.get("src/test/resources/samples/app1/icon.png"))); + fileTransferService.writeChunk(chunkDescriptor); + releaseWrapper.setIconLink(transferLink.getDirectTransferLink() + "/icon.png"); + + List screenshotPaths = Arrays.asList("src/test/resources/samples/app1/shot1.png", + "src/test/resources/samples/app1/shot2.png", "src/test/resources/samples/app1/shot3.png"); + List screenshotLinks = new ArrayList<>(); + String []pathSegments; + for (String path: screenshotPaths) { + pathSegments = path.split("/"); + String fullQualifiedName = pathSegments[pathSegments.length - 1]; + String []nameSegments = fullQualifiedName.split("\\.(?=[^.]+$)"); + metaEntry.setFileName(nameSegments[0]); + metaEntry.setExtension(nameSegments[1]); + metaEntry.setSize(41236); + transferLink = fileTransferService.generateUploadLink(metaEntry); + segments = transferLink.getRelativeTransferLink().split("/"); + chunkDescriptor = fileTransferService. + resolve(segments[segments.length-1], Files.newInputStream(Paths.get(path))); + fileTransferService.writeChunk(chunkDescriptor); + screenshotLinks.add(transferLink.getDirectTransferLink() + "/" + fullQualifiedName); + } + releaseWrapper.setScreenshotLinks(screenshotLinks); + + metaEntry.setFileName("sample"); + metaEntry.setExtension("apk"); + metaEntry.setSize(6259412); + TransferLink apkTransferLink = fileTransferService.generateUploadLink(metaEntry); + segments = apkTransferLink.getRelativeTransferLink().split("/"); + chunkDescriptor = fileTransferService. + resolve(segments[segments.length-1], Files.newInputStream(Paths.get("src/test/resources/samples/app1/sample.apk"))); + fileTransferService.writeChunk(chunkDescriptor); + releaseWrapper.setArtifactLink(apkTransferLink.getDirectTransferLink() + "/sample.apk"); + releaseWrapper.setRemoteStatus(false); entAppReleaseWrappers.add(releaseWrapper); applicationWrapper.setEntAppReleaseWrappers(entAppReleaseWrappers); diff --git a/components/application-mgt/pom.xml b/components/application-mgt/pom.xml index 94fc1273a5..360dad0a6c 100644 --- a/components/application-mgt/pom.xml +++ b/components/application-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.admin.api/pom.xml b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.admin.api/pom.xml index 239156f4d9..254c6ad535 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.admin.api/pom.xml +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.admin.api/pom.xml @@ -18,13 +18,11 @@ ~ --> - + io.entgra.device.mgt.core cea-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.common/pom.xml b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.common/pom.xml index f2649e8498..2e6e9efc5b 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.common/pom.xml +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.common/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core cea-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/pom.xml b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/pom.xml index a3954bbef3..ec906b7507 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/pom.xml +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core cea-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/pom.xml b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/pom.xml index ffa7a98455..09822882ff 100644 --- a/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/pom.xml +++ b/components/cea-mgt/io.entgra.device.mgt.core.cea.mgt.enforce/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core cea-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/cea-mgt/pom.xml b/components/cea-mgt/pom.xml index 7b7bfab5ab..665b30df0c 100644 --- a/components/cea-mgt/pom.xml +++ b/components/cea-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml index c4676c9aab..29bef57226 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml index 76d2647cd6..03b8374637 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml index 0561e65955..53c8057109 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core certificate-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index 79c1fb366c..62ba9f87aa 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml index c8f938a217..07e7b949c5 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/pom.xml index 21fd9d2457..55aea2d343 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/api/DeviceOrganizationMgtService.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/api/DeviceOrganizationMgtService.java index cfc669c767..699bf81370 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/api/DeviceOrganizationMgtService.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/api/DeviceOrganizationMgtService.java @@ -346,14 +346,14 @@ public interface DeviceOrganizationMgtService { Response getDeviceOrganizationLeafs( @ApiParam( name = "offset", - value = "The starting pagination index for the complete list of qualified items", + value = "leaf node offset", required = false, defaultValue = "0") @DefaultValue("0") @QueryParam("offset") int offset, @ApiParam( name = "limit", - value = "Provide how many policy details you require from the starting pagination index/offset.", + value = "leaf node limit", required = false, defaultValue = "5") @DefaultValue("20") @QueryParam("limit") @@ -369,8 +369,8 @@ public interface DeviceOrganizationMgtService { @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", - value = "Retrieve leaf Device Organizations", - notes = "Get a list of leaf device organizations.", + value = "Retrieve root Device Organizations", + notes = "Get a list of root device organizations.", tags = "Device Organization Management", extensions = { @Extension(properties = { @@ -414,19 +414,97 @@ public interface DeviceOrganizationMgtService { Response getDeviceOrganizationRoots( @ApiParam( name = "offset", - value = "The starting pagination index for the complete list of qualified items", + value = "root node offset", required = false, defaultValue = "0") @DefaultValue("0") @QueryParam("offset") int offset, @ApiParam( name = "limit", - value = "Provide how many policy details you require from the starting pagination index/offset.", + value = "root node limit", required = false, - defaultValue = "5") + defaultValue = "20") @DefaultValue("20") @QueryParam("limit") int limit); + /** + * Retrieves a list of root device organizations. + * + * @return A response containing a list of root device organizations. + */ + @GET + @Path("roots/children") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Retrieve children for root Device Organizations", + notes = "Get a list of children for root device organizations.", + tags = "Device Organization Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "dm:device-org:view") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the all devices.", + 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"), + @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 " + + "list of supported device types.", + response = ErrorResponse.class) + }) + Response getDeviceOrganizationChildrenForRoots( + @ApiParam( + name = "offset", + value = "root offset", + required = false, + defaultValue = "0") + @DefaultValue("0") @QueryParam("offset") + int offset, + @ApiParam( + name = "limit", + value = "root limit.", + required = false, + defaultValue = "20") + @DefaultValue("20") @QueryParam("limit") + int limit, + @ApiParam( + name= "maxDepth", + value = "The maximum depth of child nodes to retrieve for each root.", + required = true) @QueryParam("maxDepth") + int maxDepth, + @ApiParam( + name= "includeDevice", + value = "Indicates whether to include device information in the retrieved child nodes.", + required = true) @QueryParam("includeDevice") + boolean includeDevice); + /** * Retrieves a specific device organization by its organization ID. * diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/api/DeviceOrganizationMgtServiceImpl.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/api/DeviceOrganizationMgtServiceImpl.java index 9a4b2590be..6b801d1fe7 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/api/DeviceOrganizationMgtServiceImpl.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/api/DeviceOrganizationMgtServiceImpl.java @@ -24,6 +24,7 @@ import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api.u import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceNodeResult; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.RootChildrenRequest; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtPluginException; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.spi.DeviceOrganizationService; import org.apache.commons.logging.Log; @@ -124,6 +125,7 @@ public class DeviceOrganizationMgtServiceImpl implements DeviceOrganizationMgtSe @DefaultValue("20") @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationParameters(offset, limit); try { + RequestValidationUtil.validatePaginationParameters(offset, limit); DeviceOrganizationService deviceOrganizationService = DeviceOrgAPIUtils.getDeviceOrganizationService(); PaginationRequest request = new PaginationRequest(offset, limit); List organizations = deviceOrganizationService.getDeviceOrganizationLeafs(request); @@ -143,6 +145,7 @@ public class DeviceOrganizationMgtServiceImpl implements DeviceOrganizationMgtSe @DefaultValue("20") @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationParameters(offset, limit); try { + RequestValidationUtil.validatePaginationParameters(offset, limit); DeviceOrganizationService deviceOrganizationService = DeviceOrgAPIUtils.getDeviceOrganizationService(); PaginationRequest request = new PaginationRequest(offset, limit); List organizations = deviceOrganizationService.getDeviceOrganizationRoots(request); @@ -154,6 +157,30 @@ public class DeviceOrganizationMgtServiceImpl implements DeviceOrganizationMgtSe } } + @GET + @Path("roots/children") + @Override + public Response getDeviceOrganizationChildrenForRoots( + @DefaultValue("0") @QueryParam("offset") int offset, + @DefaultValue("20") @QueryParam("limit") int limit, + @QueryParam("maxDepth") int maxDepth, + @QueryParam("includeDevice") boolean includeDevice) { + RequestValidationUtil.validatePaginationParameters(offset, limit); + try { + RequestValidationUtil.validatePaginationParameters(offset, limit); + DeviceOrganizationService deviceOrganizationService = DeviceOrgAPIUtils.getDeviceOrganizationService(); + RootChildrenRequest request = new RootChildrenRequest(offset, limit); + request.setMaxDepth(maxDepth); + request.setIncludeDevice(includeDevice); + List nodeResultList = deviceOrganizationService.getAllDeviceOrganizationsForRoots(request); + return Response.status(Response.Status.OK).entity(nodeResultList).build(); + } catch (DeviceOrganizationMgtPluginException e) { + String errorMessage = "get children for root organizations failed"; + log.error(errorMessage); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } + } + @GET @Override @Path("{organizationId}") diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/pom.xml index 77aa526c4e..92cbacef55 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/DeviceOrganizationDAO.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/DeviceOrganizationDAO.java index 084585676b..4c4ab54bf0 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/DeviceOrganizationDAO.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/DeviceOrganizationDAO.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/DeviceOrganizationDAOFactory.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/DeviceOrganizationDAOFactory.java index bfbd665d49..3994a32c05 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/DeviceOrganizationDAOFactory.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/DeviceOrganizationDAOFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/impl/DeviceOrganizationDAOImpl.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/impl/DeviceOrganizationDAOImpl.java index 432af7ff77..50da8c0bc1 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/impl/DeviceOrganizationDAOImpl.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/impl/DeviceOrganizationDAOImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/impl/DeviceOrganizationMysqlDAOImpl.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/impl/DeviceOrganizationMysqlDAOImpl.java index 55a141b9ad..efbd192641 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/impl/DeviceOrganizationMysqlDAOImpl.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dao/impl/DeviceOrganizationMysqlDAOImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/AdditionResult.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/AdditionResult.java index dbebff85d6..df5d58e168 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/AdditionResult.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/AdditionResult.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto; public class AdditionResult { diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceNode.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceNode.java index 3ec106543e..14d15f7c65 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceNode.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceNode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceNodeResult.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceNodeResult.java index 94673c84d3..f32f725e26 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceNodeResult.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceNodeResult.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceOrganization.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceOrganization.java index ea912a9611..5794e51ab8 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceOrganization.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/DeviceOrganization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/PaginationRequest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/PaginationRequest.java index 18db134545..83ccec27cb 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/PaginationRequest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/PaginationRequest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/RootChildrenRequest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/RootChildrenRequest.java new file mode 100644 index 0000000000..6f2638a266 --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/dto/RootChildrenRequest.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto; + +public class RootChildrenRequest extends PaginationRequest{ + + int maxDepth; + boolean includeDevice; + + public RootChildrenRequest(int start, int limit) { + super(start, limit); + } + + public int getMaxDepth() { + return maxDepth; + } + + public void setMaxDepth(int maxDepth) { + if (maxDepth < 0) { + throw new IllegalArgumentException("maxDepth cannot be negative"); + } + this.maxDepth = maxDepth; + } + + public boolean isIncludeDevice() { + return includeDevice; + } + + public void setIncludeDevice(boolean includeDevice) { + this.includeDevice = includeDevice; + } +} diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/BadRequestDaoException.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/BadRequestDaoException.java index dee4e83d6b..e034d657c7 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/BadRequestDaoException.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/BadRequestDaoException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/BadRequestException.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/BadRequestException.java index 0a87897426..2f7cfec4cc 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/BadRequestException.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/BadRequestException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DBConnectionException.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DBConnectionException.java index 69818565ae..993b002523 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DBConnectionException.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DBConnectionException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DeviceOrganizationMgtDAOException.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DeviceOrganizationMgtDAOException.java index 2f728aa833..0c3039b552 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DeviceOrganizationMgtDAOException.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DeviceOrganizationMgtDAOException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DeviceOrganizationMgtPluginException.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DeviceOrganizationMgtPluginException.java index 98a95e4d41..cf1cee1e21 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DeviceOrganizationMgtPluginException.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/DeviceOrganizationMgtPluginException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/UnsupportedDatabaseEngineException.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/UnsupportedDatabaseEngineException.java index 32c9ed3ac2..08f158a14d 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/UnsupportedDatabaseEngineException.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/exception/UnsupportedDatabaseEngineException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/impl/DeviceOrganizationServiceImpl.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/impl/DeviceOrganizationServiceImpl.java index 1cc4838d97..999ce4cc3c 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/impl/DeviceOrganizationServiceImpl.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/impl/DeviceOrganizationServiceImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 @@ -20,10 +20,11 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.organization.impl import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAO; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.DeviceOrganizationDAOFactory; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.util.ConnectionManagerUtil; -import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.AdditionResult; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceNodeResult; -import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization; +import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.RootChildrenRequest; +import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.AdditionResult; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.BadRequestException; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DBConnectionException; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtDAOException; @@ -33,7 +34,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import java.sql.Connection; +import java.util.ArrayList; import java.util.List; public class DeviceOrganizationServiceImpl implements DeviceOrganizationService { @@ -164,6 +165,34 @@ public class DeviceOrganizationServiceImpl implements DeviceOrganizationService } } + /** + * {@inheritDoc} + */ + @Override + public List getAllDeviceOrganizationsForRoots(RootChildrenRequest request) throws DeviceOrganizationMgtPluginException { + List allDeviceOrganizations = new ArrayList<>(); + + try { + // Get all root device organizations + PaginationRequest paginationRequest = new PaginationRequest(request.getOffSet(), request.getLimit()); + List roots = getDeviceOrganizationRoots(paginationRequest); + + // Iterate over each root and fetch its children + for (DeviceOrganization root : roots) { + DeviceNodeResult childrenResult = getChildrenOfDeviceNode(root.getDeviceId(), request.getMaxDepth(), request.isIncludeDevice()); + if (childrenResult != null) { + allDeviceOrganizations.add(childrenResult); + } + } + return allDeviceOrganizations; + } catch (DeviceOrganizationMgtPluginException e) { + String msg = "Error occurred while retrieving all device organizations for roots."; + log.error(msg, e); + throw new DeviceOrganizationMgtPluginException(msg, e); + } + } + + /** * {@inheritDoc} */ diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtDataHolder.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtDataHolder.java index d6a5bb2545..d75a83e7b6 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtDataHolder.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtDataHolder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtServiceComponent.java index b7a84ca31a..f33cbdcd01 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtServiceComponent.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/internal/DeviceOrganizationMgtServiceComponent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/spi/DeviceOrganizationService.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/spi/DeviceOrganizationService.java index b69e386773..fa3265289d 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/spi/DeviceOrganizationService.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/spi/DeviceOrganizationService.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.organization.spi; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceNodeResult; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.RootChildrenRequest; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtPluginException; import java.util.List; @@ -71,6 +72,15 @@ public interface DeviceOrganizationService { */ List getAllDeviceOrganizations() throws DeviceOrganizationMgtPluginException; + /** + * Retrieves a list of all device organizations for roots. + * @param request + * @return + * @throws DeviceOrganizationMgtPluginException + */ + List getAllDeviceOrganizationsForRoots(RootChildrenRequest request) + throws DeviceOrganizationMgtPluginException; + /** * Retrieves device Organization Leafs * diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DAONegativeTest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DAONegativeTest.java index 1df01c4983..2d8e3b66c5 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DAONegativeTest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DAONegativeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DAOTest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DAOTest.java index 57154985f5..5cf14e5ea8 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DAOTest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DAOTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DataSourceConfig.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DataSourceConfig.java index 240633038a..c3d37de986 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DataSourceConfig.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/DataSourceConfig.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/ServiceNegativeTest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/ServiceNegativeTest.java index 3f2b125f1b..47764bdbfc 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/ServiceNegativeTest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/ServiceNegativeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/ServiceTest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/ServiceTest.java index 351b21d537..c46f035c50 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/ServiceTest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/ServiceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 @@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dao.D import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceNodeResult; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.DeviceOrganization; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.PaginationRequest; +import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.dto.RootChildrenRequest; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.exception.DeviceOrganizationMgtPluginException; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.impl.DeviceOrganizationServiceImpl; import io.entgra.device.mgt.core.device.mgt.extensions.device.organization.mock.BaseDeviceOrganizationTest; @@ -285,6 +286,21 @@ public class ServiceTest extends BaseDeviceOrganizationTest { Assert.assertFalse(organizations.isEmpty(), "List of organizations should not be empty"); } + @Test(dependsOnMethods = "testAddDeviceOrganizationWithNullParent") + public void testGetAllOrganizationsForRoots() throws DeviceOrganizationMgtPluginException { + + int offSet = 0; + int limit = 100; + boolean includeDevice = true; + int maxDepth =100; + RootChildrenRequest request = new RootChildrenRequest(offSet, limit); + request.setMaxDepth(maxDepth); + request.setIncludeDevice(includeDevice); + List nodeResultList = deviceOrganizationService.getAllDeviceOrganizationsForRoots(request); + Assert.assertNotNull(nodeResultList, "Cannot be null"); + Assert.assertFalse(nodeResultList.isEmpty(), "List of node result should not be empty"); + } + @Test(dependsOnMethods = "testAddDeviceOrganizationWithNullParent") public void testGetRootOrganizations() throws DeviceOrganizationMgtPluginException { int offset = 0; diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/TestUtils.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/TestUtils.java index 9dcac705be..b48518e515 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/TestUtils.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/TestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/BaseDeviceOrganizationTest.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/BaseDeviceOrganizationTest.java index ec7cf1efe5..30d75ecf34 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/BaseDeviceOrganizationTest.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/BaseDeviceOrganizationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockConnection.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockConnection.java index 86db883873..47d2fe8529 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockConnection.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockDataSource.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockDataSource.java index 8b266cd85f..975cafc901 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockDataSource.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockDatabaseMetaData.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockDatabaseMetaData.java index a1229e28a4..566aaee6c0 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockDatabaseMetaData.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockDatabaseMetaData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockJDBCDriver.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockJDBCDriver.java index 24944a3b39..74a8b39962 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockJDBCDriver.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockJDBCDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockResultSet.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockResultSet.java index 08b4beb4f7..671b40923b 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockResultSet.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockResultSet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockStatement.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockStatement.java index 50d199b424..d09e7410d9 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockStatement.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/device/organization/mock/MockStatement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * Copyright (c) 2018 - 2024, 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 diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml index 726693fe54..cce520cc68 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml index 133b0a6aab..34427cb7de 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml @@ -21,7 +21,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml index 8d20cef3b4..90e4d05ed7 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml index 51f7412758..ffb529ef29 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml index ce179db561..8909230131 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml index a91b23cf49..167b1dcc67 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml index cfad90f1f8..6546e5d8f2 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml index a24874f435..efe179f503 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml index 3c2389ca60..4c0f550469 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index ab1876a908..5912b6f830 100644 --- a/components/device-mgt-extensions/pom.xml +++ b/components/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml index ddc2ac42d1..d975ad3715 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml @@ -22,7 +22,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/BasicUserInfo.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/BasicUserInfo.java index fa1e5612ce..56499d4e98 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/BasicUserInfo.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/beans/BasicUserInfo.java @@ -35,6 +35,8 @@ public class BasicUserInfo { private String createdDate; @ApiModelProperty(name = "modifiedDate", value = "User modifiedDate date." ) private String modifiedDate; + @ApiModelProperty(name = "isRemovable", value = "User's removable status." ) + private boolean isRemovable; public String getUsername() { return username; @@ -84,4 +86,11 @@ public class BasicUserInfo { this.modifiedDate = modifiedDate; } + public boolean isRemovable() { + return isRemovable; + } + + public void setRemovable(boolean removable) { + isRemovable = removable; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java index a62341756e..5d324aeb02 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java @@ -61,6 +61,13 @@ import javax.ws.rs.core.Response; key = "um:admin:users:remove", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/users/delete"} + ), + @Scope( + name = "Delete Tenant Information", + description = "Delete tenant details", + key = "um:admin:tenants:remove", + roles = {"Internal/devicemgt-admin"}, + permissions = {"/device-mgt/admin/tenants/delete"} ) } ) @@ -258,5 +265,41 @@ public interface UserManagementAdminService { @Size(max = 45) String deviceId); + @DELETE + @Path("/domain/{tenantDomain}") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "Delete a tenant by tenant domain.", + notes = "This API allows the deletion of a tenant by providing the tenant domain.", + tags = "Tenant details remove", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "um:admin:tenants:remove") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Tenant has been deleted successfully."), + @ApiResponse( + code = 404, + message = "Not Found. \n The tenant with the provided domain does not exist.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while removing the tenant.", + response = ErrorResponse.class) + }) + Response deleteTenantByDomain( + @ApiParam( + name = "tenantDomain", + value = "The domain of the tenant to be deleted.", + required = true) + + @PathParam("tenantDomain") + String tenantDomain); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java index 820503eb30..43c98523a5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java @@ -252,7 +252,7 @@ public class UserManagementServiceImpl implements UserManagementService { BasicUserInfo user = this.getBasicUserInfo(username); return Response.status(Response.Status.OK).entity(user).build(); - } catch (UserStoreException e) { + } catch (UserStoreException | DeviceManagementException e) { String msg = "Error occurred while retrieving information of the user '" + username + "'"; log.error(msg, e); return Response.serverError().entity( @@ -334,7 +334,7 @@ public class UserManagementServiceImpl implements UserManagementService { BasicUserInfo updatedUserInfo = this.getBasicUserInfo(username); return Response.ok().entity(updatedUserInfo).build(); - } catch (UserStoreException e) { + } catch (UserStoreException | DeviceManagementException e) { String msg = "Error occurred while trying to update user '" + username + "'"; log.error(msg, e); return Response.serverError().entity( @@ -495,7 +495,7 @@ public class UserManagementServiceImpl implements UserManagementService { result.setCount(userList.size()); return Response.status(Response.Status.OK).entity(result).build(); - } catch (UserStoreException e) { + } catch (UserStoreException | DeviceManagementException e) { String msg = "Error occurred while retrieving the list of users."; log.error(msg, e); return Response.serverError().entity( @@ -574,6 +574,7 @@ public class UserManagementServiceImpl implements UserManagementService { basicUserInfo.setEmailAddress(getClaimValue(user, Constants.USER_CLAIM_EMAIL_ADDRESS)); basicUserInfo.setFirstname(getClaimValue(user, Constants.USER_CLAIM_FIRST_NAME)); basicUserInfo.setLastname(getClaimValue(user, Constants.USER_CLAIM_LAST_NAME)); + basicUserInfo.setRemovable(isUserRemovable(user)); filteredUserList.add(basicUserInfo); } } @@ -598,7 +599,7 @@ public class UserManagementServiceImpl implements UserManagementService { result.setCount(commonUsers != null ? commonUsers.size() : 0); return Response.status(Response.Status.OK).entity(result).build(); - } catch (UserStoreException e) { + } catch (UserStoreException | DeviceManagementException e) { String msg = "Error occurred while retrieving the list of users."; log.error(msg, e); return Response.serverError().entity( @@ -1249,7 +1250,7 @@ public class UserManagementServiceImpl implements UserManagementService { return initialUserPassword.toString(); } - private BasicUserInfo getBasicUserInfo(String username) throws UserStoreException { + private BasicUserInfo getBasicUserInfo(String username) throws UserStoreException, DeviceManagementException { BasicUserInfo userInfo = new BasicUserInfo(); userInfo.setUsername(username); userInfo.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); @@ -1257,9 +1258,21 @@ public class UserManagementServiceImpl implements UserManagementService { userInfo.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); userInfo.setCreatedDate(getClaimValue(username, Constants.USER_CLAIM_CREATED)); userInfo.setModifiedDate(getClaimValue(username, Constants.USER_CLAIM_MODIFIED)); + userInfo.setRemovable(isUserRemovable(username)); return userInfo; } + /** + * Check if the user can be removed or not + * @param username Username of the user + * @return True when user can be removed, otherwise false + * @throws DeviceManagementException Throws when error occurred while getting device count + */ + private boolean isUserRemovable(String username) throws DeviceManagementException { + DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); + return deviceManagementProviderService.getDeviceCount(username.contains("/") ? username.split("/")[1] : username) == 0; + } + private String getClaimValue(String username, String claimUri) throws UserStoreException { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); return userStoreManager.getUserClaimValue(username, claimUri, null); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java index 26cd8c4c54..d4f34d8e4a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java @@ -17,6 +17,8 @@ */ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin; +import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; @@ -25,6 +27,11 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.PasswordResetWrapper import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.admin.UserManagementAdminService; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.CredentialManagementResponseBuilder; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.stratos.common.exception.StratosException; +import org.wso2.carbon.tenant.mgt.services.TenantMgtAdminService; +import org.wso2.carbon.user.api.UserStoreException; import javax.validation.constraints.Size; import javax.ws.rs.*; @@ -81,4 +88,38 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic } } + @DELETE + @Path("/domain/{tenantDomain}") + @Override + public Response deleteTenantByDomain(@PathParam("tenantDomain") String tenantDomain) { + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + if (tenantId != MultitenantConstants.SUPER_TENANT_ID){ + String msg = "Only super tenants are allowed to delete tenants"; + log.error(msg); + return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); + } else { + DeviceMgtAPIUtils.getApplicationManager().deleteApplicationDataByTenantDomain(tenantDomain); + DeviceMgtAPIUtils.getDeviceManagementService().deleteDeviceDataByTenantDomain(tenantDomain); + TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService(); + tenantMgtAdminService.deleteTenant(tenantDomain); + String msg = "Tenant Deletion process has been initiated for tenant:" + tenantDomain; + return Response.status(Response.Status.OK).entity(msg).build(); + } + + } catch (StratosException | UserStoreException e) { + String msg = "Error deleting tenant: " + tenantDomain; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (ApplicationManagementException e) { + String msg = "Error deleting application data of tenant: " + tenantDomain; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (DeviceManagementException e) { + String msg = "Error deleting device data of tenant: " + tenantDomain; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java index 3c5e5e3fa1..f25a37c9e7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImplTest.java @@ -119,8 +119,9 @@ public class UserManagementServiceImplTest { PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) .toReturn(carbonContext); Mockito.when(carbonContext.getTenantId()).thenReturn(-1234); - Mockito.when(carbonContext.getUsername()).thenReturn("admin"); Mockito.when(carbonContext.getTenantDomain()).thenReturn("carbon.super"); + Mockito.when(carbonContext.getUsername()).thenReturn("admin"); + Mockito.doReturn(0).when(deviceManagementProviderService).getDeviceCount(TEST_USERNAME); Mockito.doAnswer(new Answer() { private int count = 0; @@ -156,9 +157,17 @@ public class UserManagementServiceImplTest { @Test(description = "This method tests the getUser method of UserManagementService", dependsOnMethods = "testAddUser") - public void testGetUser() throws UserStoreException { + public void testGetUser() throws UserStoreException, DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + CarbonContext carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(carbonContext); + Mockito.when(carbonContext.getTenantId()).thenReturn(-1234); + Mockito.when(carbonContext.getTenantDomain()).thenReturn("carbon.super"); + Mockito.doReturn(0).when(deviceManagementProviderService).getDeviceCount(TEST_USERNAME); Response response = userManagementService.getUser(TEST_USERNAME, null, null); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "User retrieval failed"); BasicUserInfo userInfo = (BasicUserInfo) response.getEntity(); @@ -173,15 +182,18 @@ public class UserManagementServiceImplTest { @Test(description = "This method tests the updateUser method of UserManagementService", dependsOnMethods = {"testGetUser"}) - public void testUpdateUser() throws UserStoreException { + public void testUpdateUser() throws UserStoreException, DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) .toReturn(this.userStoreManager); CarbonContext carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS); PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) .toReturn(carbonContext); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); Mockito.when(carbonContext.getTenantId()).thenReturn(-1234); - Mockito.when(carbonContext.getUsername()).thenReturn("admin"); Mockito.when(carbonContext.getTenantDomain()).thenReturn("carbon.super"); + Mockito.when(carbonContext.getUsername()).thenReturn("admin"); + Mockito.doReturn(0).when(deviceManagementProviderService).getDeviceCount(TEST_USERNAME); Response response = userManagementService.updateUser(TEST2_USERNAME, null, null); Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), "Non-existing user was successfully updated"); @@ -250,10 +262,18 @@ public class UserManagementServiceImplTest { @Test(description = "This method tests the getUsers method of UserManagementService", dependsOnMethods = {"testGetUserNames"}) - public void testGetUsers() { + public void testGetUsers() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) .toReturn(userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); Response response = userManagementService.getUsers(null, "00", 0, 10, null); + CarbonContext carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(carbonContext); + Mockito.when(carbonContext.getTenantId()).thenReturn(-1234); + Mockito.when(carbonContext.getTenantDomain()).thenReturn("carbon.super"); + Mockito.doReturn(0).when(deviceManagementProviderService).getDeviceCount(TEST_USERNAME); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "GetUsers request failed"); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml index 1adfa2fa49..a472beedad 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml @@ -21,7 +21,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml index 7cc0b72533..115bdc04a6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml @@ -22,7 +22,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml index e77f9ec802..9827ec7084 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml @@ -365,13 +365,6 @@ org.wso2.orbit.javax.xml.bind jaxb-api - 2.3.1.wso2v1 - compile - - - org.wso2.orbit.javax.xml.bind - jaxb-api - 2.3.1.wso2v1 compile diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java index fec70931a4..368157ca48 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java @@ -19,6 +19,7 @@ package io.entgra.device.mgt.core.device.mgt.core.app.mgt; import com.google.gson.Gson; +import io.entgra.device.mgt.core.device.mgt.core.report.mgt.ReportingPublisherManager; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -286,8 +287,9 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem deviceDetailsWrapper.setTenantId(tenantId); deviceDetailsWrapper.setDevice(device); deviceDetailsWrapper.setApplications(newApplications); - HttpReportingUtil.invokeApi(deviceDetailsWrapper.getJSONString(), - reportingHost + DeviceManagementConstants.Report.APP_USAGE_ENDPOINT); + ReportingPublisherManager reportingManager = new ReportingPublisherManager(); + reportingManager.publishData(deviceDetailsWrapper, DeviceManagementConstants + .Report.APP_USAGE_ENDPOINT); } } catch (DeviceManagementDAOException e) { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceManagementDAOFactory.java index 7b105df14d..b7768f9c52 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -139,6 +139,22 @@ public class DeviceManagementDAOFactory { throw new IllegalStateException("Database engine has not initialized properly."); } + public static TenantDAO getTenantDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new TenantDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + public static TrackerDAO getTrackerDAO() { if (databaseEngine != null) { switch (databaseEngine) { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TenantDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TenantDAO.java new file mode 100644 index 0000000000..372df2583a --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/TenantDAO.java @@ -0,0 +1,431 @@ +package io.entgra.device.mgt.core.device.mgt.core.dao; + +public interface TenantDAO { + + /** + * Delete device certificates of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceCertificateByTenantId(int tenantId)throws DeviceManagementDAOException; + + /** + * Delete groups of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteGroupByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete role-group mapping data of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteRoleGroupMapByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete devices of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device properties of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDevicePropertiesByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete group properties of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteGroupPropertiesByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device-group mapping details of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceGroupMapByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete operations of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteOperationByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete enrolments of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteEnrolmentByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device statuses of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceStatusByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete enrolment mapping of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteEnrolmentOpMappingByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device operation responses of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceOperationResponseByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete large-device operations responses of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceOperationResponseLargeByTenantId(int tenantId) throws DeviceManagementDAOException; + + // Delete policy related tables + + /** + * Delete applications of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteApplicationByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete policy compliance features of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deletePolicyComplianceFeaturesByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete policy change management data of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deletePolicyChangeManagementByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete policy compliance statuses of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deletePolicyComplianceStatusByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete policy criteria properties of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deletePolicyCriteriaPropertiesByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete policy criteria of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deletePolicyCriteriaByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete policies of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deletePolicyByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete role policies of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteRolePolicyByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete user policies of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteUserPolicyByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device policies of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDevicePolicyAppliedByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete criteria of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteCriteriaByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device type properties of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceTypePolicyByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device policies of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDevicePolicyByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete profile features of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteProfileFeaturesByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete policy corrective actions of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deletePolicyCorrectiveActionByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete profiles of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteProfileByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete app icons of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteAppIconsByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device group policies of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceGroupPolicyByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete notifications of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteNotificationByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device information of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceInfoByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device location of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceLocationByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device history of last seven days of a tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceHistoryLastSevenDaysByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device details of a tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceDetailByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete metadata of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteMetadataByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete OTP data of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteOTPDataByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete geo fences of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteGeofenceByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete geo fence group mapping data of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteGeofenceGroupMappingByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device events of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceEventByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device event group mapping of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceEventGroupMappingByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete geo fence event mapping of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteGeofenceEventMappingByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete external group mapping of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteExternalGroupMappingByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete External device mapping of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteExternalDeviceMappingByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete external permission mapping of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteExternalPermissionMapping(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete dynamic tasks of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDynamicTaskByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete dynamic task properties of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDynamicTaskPropertiesByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device subtypes of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceSubTypeByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete traccar unsynced devices of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteTraccarUnsyncedDevicesByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete sub operation templates of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteSubOperationTemplate(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete device organizations of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteDeviceOrganizationByTenantId(int tenantId) throws DeviceManagementDAOException; + + /** + * Delete CEA policies of tenant + * + * @param tenantId Tenant ID + * @throws DeviceManagementDAOException thrown if there is an error when deleting data + */ + void deleteCEAPoliciesByTenantId(int tenantId) throws DeviceManagementDAOException; + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/TenantDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/TenantDAOImpl.java new file mode 100644 index 0000000000..5aec24752b --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/TenantDAOImpl.java @@ -0,0 +1,939 @@ +package io.entgra.device.mgt.core.device.mgt.core.dao.impl; + +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; +import io.entgra.device.mgt.core.device.mgt.core.dao.TenantDAO; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + + +public class TenantDAOImpl implements TenantDAO { + + private static final Log log = LogFactory.getLog(TenantDAOImpl.class); + + + @Override + public void deleteDeviceCertificateByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting certificates for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteGroupByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_GROUP WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting groups for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteRoleGroupMapByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_ROLE_GROUP_MAP WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting role group mapping for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting devices for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDevicePropertiesByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_PROPERTIES WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device properties for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + @Override + public void deleteGroupPropertiesByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM GROUP_PROPERTIES WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting group properties for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceGroupMapByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device group mapping for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteOperationByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_OPERATION WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting operations for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteEnrolmentByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_ENROLMENT WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting enrolment for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceStatusByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_STATUS WHERE ENROLMENT_ID IN " + + "(SELECT ID FROM DM_ENROLMENT WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device status for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteEnrolmentOpMappingByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_ENROLMENT_OP_MAPPING WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting enrolment op mapping for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceOperationResponseByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_OPERATION_RESPONSE WHERE EN_OP_MAP_ID IN " + + "(SELECT ID FROM DM_ENROLMENT_OP_MAPPING WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device operation response for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceOperationResponseLargeByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_OPERATION_RESPONSE_LARGE WHERE EN_OP_MAP_ID IN "+ + "(SELECT ID FROM DM_ENROLMENT_OP_MAPPING WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device operation response large for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteApplicationByTenantId(int tenantId) throws DeviceManagementDAOException{ + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_APPLICATION WHERE DEVICE_ID IN " + + "(SELECT ID FROM DM_DEVICE WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting applications for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + + } + + @Override + public void deletePolicyComplianceFeaturesByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_POLICY_COMPLIANCE_FEATURES WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting policy compliance features for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deletePolicyChangeManagementByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_POLICY_CHANGE_MGT WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting policy change management for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deletePolicyComplianceStatusByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_POLICY_COMPLIANCE_STATUS WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting policy compliance status for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deletePolicyCriteriaPropertiesByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_POLICY_CRITERIA_PROPERTIES WHERE POLICY_CRITERION_ID IN " + + "(SELECT ID FROM DM_POLICY_CRITERIA WHERE POLICY_ID IN " + + "(SELECT ID FROM DM_POLICY WHERE TENANT_ID = ?))"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting policy criteria properties for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deletePolicyCriteriaByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_POLICY_CRITERIA WHERE POLICY_ID IN " + + "(SELECT ID FROM DM_POLICY WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting policy criteria for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deletePolicyByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_POLICY WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting policy for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteRolePolicyByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_ROLE_POLICY WHERE POLICY_ID IN " + + "(SELECT ID FROM DM_POLICY WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting role policy for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteUserPolicyByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_USER_POLICY WHERE POLICY_ID IN " + + "(SELECT ID FROM DM_POLICY WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting user policy for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDevicePolicyAppliedByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_POLICY_APPLIED WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting policy applied for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteCriteriaByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_CRITERIA WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting criteria for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceTypePolicyByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_TYPE_POLICY WHERE POLICY_ID IN " + + "(SELECT ID FROM DM_POLICY WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device type policy for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + @Override + public void deleteDevicePolicyByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_POLICY WHERE POLICY_ID IN " + + "(SELECT ID FROM DM_POLICY WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device policy for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteProfileFeaturesByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_PROFILE_FEATURES WHERE PROFILE_ID IN " + + "(SELECT ID FROM DM_PROFILE WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting profile features for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deletePolicyCorrectiveActionByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_POLICY_CORRECTIVE_ACTION WHERE POLICY_ID IN " + + "(SELECT ID FROM DM_POLICY WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting policy corrective action for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteProfileByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_PROFILE WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting profile for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteAppIconsByTenantId(int tenantId) throws DeviceManagementDAOException{ + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_APP_ICONS WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting App Icons for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceGroupPolicyByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_GROUP_POLICY WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device group policy for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteNotificationByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_NOTIFICATION WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting notifications for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceInfoByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_INFO WHERE ENROLMENT_ID IN " + + "(SELECT ID FROM DM_ENROLMENT WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device info for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceLocationByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_LOCATION WHERE ENROLMENT_ID IN " + + "(SELECT ID FROM DM_ENROLMENT WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device location for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceHistoryLastSevenDaysByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_HISTORY_LAST_SEVEN_DAYS WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device history for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceDetailByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_DETAIL WHERE ENROLMENT_ID IN " + + "(SELECT ID FROM DM_ENROLMENT WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device detail for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteMetadataByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_METADATA WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting metadata for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteOTPDataByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_OTP_DATA WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting OTP data for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteGeofenceByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_GEOFENCE WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting geo fence for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteGeofenceGroupMappingByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_GEOFENCE_GROUP_MAPPING WHERE FENCE_ID IN " + + "(SELECT ID FROM DM_GEOFENCE WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting geo fence group mapping for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceEventByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_EVENT WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device event for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceEventGroupMappingByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_EVENT_GROUP_MAPPING WHERE EVENT_ID IN " + + "(SELECT ID FROM DM_DEVICE_EVENT WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device event group mapping for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteGeofenceEventMappingByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_GEOFENCE_EVENT_MAPPING WHERE FENCE_ID IN " + + "(SELECT ID FROM DM_GEOFENCE WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting geo fence event mapping for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteExternalGroupMappingByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_EXT_GROUP_MAPPING WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting external group mapping for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteExternalDeviceMappingByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_EXT_DEVICE_MAPPING WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting external device mapping for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteExternalPermissionMapping(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_USER_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting ext permission mapping for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + + } + + @Override + public void deleteDynamicTaskByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DYNAMIC_TASK WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting dynamic task for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDynamicTaskPropertiesByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DYNAMIC_TASK_PROPERTIES WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting dynamic task properties for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceSubTypeByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_SUB_TYPE WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device sub types for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteTraccarUnsyncedDevicesByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_TRACCAR_UNSYNCED_DEVICES WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting Traccar unsynced devices for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteSubOperationTemplate(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM SUB_OPERATION_TEMPLATE WHERE SUB_TYPE_ID IN " + + "(SELECT SUB_TYPE_ID FROM DM_DEVICE_SUB_TYPE WHERE TENANT_ID = ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting sub operation template for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteDeviceOrganizationByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_DEVICE_ORGANIZATION WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting device organization for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } + + @Override + public void deleteCEAPoliciesByTenantId(int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_CEA_POLICIES WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting CEA policies for Tenant ID " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index fcb1799568..df408422b6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -1268,33 +1268,36 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnershipProvided = false; boolean isSerialProvided = false; - StringJoiner joiner = new StringJoiner(",", - "SELECT " - + "DM_DEVICE.ID AS DEVICE_ID, " - + "DM_DEVICE.NAME AS DEVICE_NAME, " - + "DM_DEVICE.DESCRIPTION AS DESCRIPTION, " - + "DM_DEVICE.DEVICE_TYPE_ID, " - + "DM_DEVICE.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, " - + "e.ID AS ENROLMENT_ID, " - + "e.OWNER, " - + "e.OWNERSHIP, " - + "e.DATE_OF_ENROLMENT, " - + "e.DATE_OF_LAST_UPDATE, " - + "e.STATUS, " - + "e.IS_TRANSFERRED, " - + "device_types.NAME AS DEVICE_TYPE " - + "FROM DM_DEVICE " - + "INNER JOIN DM_ENROLMENT e ON " - + "DM_DEVICE.ID = e.DEVICE_ID AND " - + "DM_DEVICE.TENANT_ID = e.TENANT_ID " - + "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON " - + "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID " - + "INNER JOIN DM_DEVICE_INFO i ON " - + "DM_DEVICE.ID = i.DEVICE_ID " - + "AND i.KEY_FIELD = 'serial' " - + "WHERE DM_DEVICE.ID IN (", + query = "SELECT " + + "DM_DEVICE.ID AS DEVICE_ID, " + + "DM_DEVICE.NAME AS DEVICE_NAME, " + + "DM_DEVICE.DESCRIPTION AS DESCRIPTION, " + + "DM_DEVICE.DEVICE_TYPE_ID, " + + "DM_DEVICE.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, " + + "e.ID AS ENROLMENT_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.DATE_OF_ENROLMENT, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "device_types.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE " + + "INNER JOIN DM_ENROLMENT e ON " + + "DM_DEVICE.ID = e.DEVICE_ID AND " + + "DM_DEVICE.TENANT_ID = e.TENANT_ID " + + "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON " + + "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID "; + + if (null != serial && !serial.isEmpty()) { // Only if serial is provided, join with device info table + query = query.concat("INNER JOIN DM_DEVICE_INFO i ON " + + "DM_DEVICE.ID = i.DEVICE_ID " + + "AND i.KEY_FIELD = 'serial' "); + isSerialProvided = true; + } + query = query.concat("WHERE DM_DEVICE.ID IN ("); + StringJoiner joiner = new StringJoiner(",", query , ") AND DM_DEVICE.TENANT_ID = ? AND e.STATUS != ?"); - deviceIds.stream().map(ignored -> "?").forEach(joiner::add); query = joiner.toString(); @@ -1306,9 +1309,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { query += " AND e.OWNERSHIP = ?"; isOwnershipProvided = true; } - if (serial != null && !serial.isEmpty()) { + if (isSerialProvided) { query += " AND i.VALUE_FIELD LIKE ?" ; - isSerialProvided = true; } if (user != null && !user.isEmpty()) { query += " AND e.OWNER = ?"; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index e8a8fa6e89..ff81879563 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -19,6 +19,7 @@ package io.entgra.device.mgt.core.device.mgt.core.device.details.mgt.impl; import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; +import io.entgra.device.mgt.core.device.mgt.core.report.mgt.ReportingPublisherManager; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -30,7 +31,6 @@ import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceDetailsW import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceLocation; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.EventPublishingException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; @@ -55,6 +55,8 @@ import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; public class DeviceInformationManagerImpl implements DeviceInformationManager { @@ -87,6 +89,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { DeviceDetailsWrapper deviceDetailsWrapper = new DeviceDetailsWrapper(); deviceDetailsWrapper.setDeviceInfo(deviceInfo); + //Asynchronous call to publish the device information to the reporting service. Hence, response is ignored. publishEvents(device, deviceDetailsWrapper, DeviceManagementConstants.Report.DEVICE_INFO_PARAM); DeviceManagementDAOFactory.beginTransaction(); @@ -204,12 +207,34 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { getDeviceManagementProvider().getDevice(deviceIdentifier, false); DeviceDetailsWrapper deviceDetailsWrapper = new DeviceDetailsWrapper(); deviceDetailsWrapper.setEvents(payload); - return publishEvents(device, deviceDetailsWrapper, eventType); + Future apiCallback = publishEvents(device, deviceDetailsWrapper, eventType); + if (null != apiCallback) { + boolean isDebugEnabled = log.isDebugEnabled(); + while(!apiCallback.isDone()) { + if (isDebugEnabled) { + log.debug("Waiting for the response from the API for the reporting data " + + "publishing for the device " + deviceId + ". Event payload: " + payload); + } + } + return apiCallback.get(); + } + return 0; // If the event publishing is disabled. } catch (DeviceManagementException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Event publishing error. Could not get device " + deviceId; log.error(msg, e); throw new DeviceDetailsMgtException(msg, e); + } catch (ExecutionException e) { + //Exceptions thrown in ReportingPublisherManager will be wrapped under this exception + String message = "Failed while publishing device information data to the reporting service for the device " + + deviceId; + log.error(message, e); + throw new DeviceDetailsMgtException(message, e); + } catch (InterruptedException e) { + String message = "Failed while publishing device information data to the reporting service. Thread " + + "interrupted while waiting for the response from the API for the Device " + deviceId; + log.error(message, e); + throw new DeviceDetailsMgtException(message, e); } } @@ -218,7 +243,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { * @param device Device that is sending event * @param deviceDetailsWrapper Payload to send(example, deviceinfo, applist, raw events) */ - private int publishEvents(Device device, DeviceDetailsWrapper deviceDetailsWrapper, String + private Future publishEvents(Device device, DeviceDetailsWrapper deviceDetailsWrapper, String eventType) { String reportingHost = HttpReportingUtil.getReportingHost(); if (!StringUtils.isBlank(reportingHost) @@ -255,9 +280,8 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { String eventUrl = reportingHost + DeviceManagementConstants.Report .REPORTING_CONTEXT + DeviceManagementConstants.URL_SEPERATOR + eventType; - return HttpReportingUtil.invokeApi(deviceDetailsWrapper.getJSONString(), eventUrl); - } catch (EventPublishingException e) { - log.error("Error occurred while sending events", e); + ReportingPublisherManager reportingManager = new ReportingPublisherManager(); + return reportingManager.publishData(deviceDetailsWrapper, eventUrl); } catch (GroupManagementException e) { log.error("Error occurred while getting group list", e); } catch (UserStoreException e) { @@ -273,7 +297,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { + DeviceManagerUtil.getTenantId()); } } - return 0; + return null; } @Override diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java index 157795aa5a..1ef473e4d1 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java @@ -18,9 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.timeout.task.impl; import com.google.gson.Gson; -import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.ActivityStatus; @@ -29,75 +26,85 @@ import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.OperationManage import io.entgra.device.mgt.core.device.mgt.core.config.operation.timeout.OperationTimeout; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; -import io.entgra.device.mgt.core.device.mgt.core.task.impl.DynamicPartitionedScheduleTask; +import io.entgra.device.mgt.core.device.mgt.core.task.impl.RandomlyAssignedScheduleTask; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.util.ArrayList; import java.util.List; +import java.util.Map; -public class OperationTimeoutTask extends DynamicPartitionedScheduleTask { +public class OperationTimeoutTask extends RandomlyAssignedScheduleTask { private static final Log log = LogFactory.getLog(OperationTimeoutTask.class); + public static final String OPERATION_TIMEOUT_TASK = "OPERATION_TIMEOUT_TASK"; + private Map properties; + + @Override + public final void setProperties(Map properties) { + this.properties = properties; + } + + public final String getProperty(String name) { + if (properties == null) { + return null; + } + return properties.get(name); + } + @Override protected void setup() { } @Override - protected void executeDynamicTask() { - if (isQualifiedToExecuteTask()) { // this task will run only in one node when the deployment has multiple nodes - String operationTimeoutTaskConfigStr = getProperty( - OperationTimeoutTaskManagerServiceImpl.OPERATION_TIMEOUT_TASK_CONFIG); - Gson gson = new Gson(); - OperationTimeout operationTimeoutConfig = gson.fromJson(operationTimeoutTaskConfigStr, OperationTimeout.class); - try { - long timeMillis = System.currentTimeMillis() - (long) operationTimeoutConfig.getTimeout(); - List deviceTypes = new ArrayList<>(); - if (operationTimeoutConfig.getDeviceTypes().size() == 1 && - "ALL".equals(operationTimeoutConfig.getDeviceTypes().get(0))) { - try { - List deviceTypeList = DeviceManagementDataHolder.getInstance() - .getDeviceManagementProvider().getDeviceTypes(); - for (DeviceType deviceType : deviceTypeList) { - deviceTypes.add(deviceType.getName()); - } - } catch (DeviceManagementException e) { - log.error("Error occurred while reading device types", e); + public String getTaskName() { + return OPERATION_TIMEOUT_TASK; + } + + @Override + protected void executeRandomlyAssignedTask() { + // this task will run only in one node when the deployment has multiple nodes + String operationTimeoutTaskConfigStr = getProperty( + OperationTimeoutTaskManagerServiceImpl.OPERATION_TIMEOUT_TASK_CONFIG); + Gson gson = new Gson(); + OperationTimeout operationTimeoutConfig = gson.fromJson(operationTimeoutTaskConfigStr, OperationTimeout.class); + try { + long timeMillis = System.currentTimeMillis() - (long) operationTimeoutConfig.getTimeout(); + List deviceTypes = new ArrayList<>(); + if (operationTimeoutConfig.getDeviceTypes().size() == 1 && + "ALL".equals(operationTimeoutConfig.getDeviceTypes().get(0))) { + try { + List deviceTypeList = DeviceManagementDataHolder.getInstance() + .getDeviceManagementProvider().getDeviceTypes(); + for (DeviceType deviceType : deviceTypeList) { + deviceTypes.add(deviceType.getName()); } - } else { - deviceTypes = operationTimeoutConfig.getDeviceTypes(); + } catch (DeviceManagementException e) { + log.error("Error occurred while reading device types", e); } - List activities = DeviceManagementDataHolder.getInstance().getOperationManager() - .getActivities(deviceTypes, operationTimeoutConfig.getCode(), timeMillis, - operationTimeoutConfig.getInitialStatus()); - for (Activity activity : activities) { - for (ActivityStatus activityStatus : activity.getActivityStatus()) { - String operationId = activity.getActivityId().replace("ACTIVITY_", ""); - Operation operation = DeviceManagementDataHolder.getInstance().getOperationManager() - .getOperation(Integer.parseInt(operationId)); - operation.setStatus(Operation.Status.valueOf(operationTimeoutConfig.getNextStatus())); - DeviceManagementDataHolder.getInstance().getOperationManager() - .updateOperation(activityStatus.getDeviceIdentifier(), operation); - } + } else { + deviceTypes = operationTimeoutConfig.getDeviceTypes(); + } + List activities = DeviceManagementDataHolder.getInstance().getOperationManager() + .getActivities(deviceTypes, operationTimeoutConfig.getCode(), timeMillis, + operationTimeoutConfig.getInitialStatus()); + String operationId; + Operation operation; + for (Activity activity : activities) { + operationId = activity.getActivityId().replace("ACTIVITY_", ""); + for (ActivityStatus activityStatus : activity.getActivityStatus()) { + operation = DeviceManagementDataHolder.getInstance().getOperationManager() + .getOperation(Integer.parseInt(operationId)); + operation.setStatus(Operation.Status.valueOf(operationTimeoutConfig.getNextStatus())); + DeviceManagementDataHolder.getInstance().getOperationManager() + .updateOperation(activityStatus.getDeviceIdentifier(), operation); } - - } catch (OperationManagementException e) { - String msg = "Error occurred while retrieving operations."; - log.error(msg, e); } + } catch (OperationManagementException e) { + String msg = "Error occurred while retrieving operations."; + log.error(msg, e); } - } - private boolean isQualifiedToExecuteTask() { - if (isDynamicTaskEligible()) { - try { - return DeviceManagementDataHolder.getInstance().getHeartBeatService().isQualifiedToExecuteTask(); - } catch (HeartBeatManagementException e) { - log.error("Error while checking is qualified to execute task", e); - } - } else { - return true; - } - return false; - } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/ReportingPublisherManager.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/ReportingPublisherManager.java new file mode 100644 index 0000000000..b6e3bf5ae1 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/report/mgt/ReportingPublisherManager.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2018 - 2024, 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 io.entgra.device.mgt.core.device.mgt.core.report.mgt; + +import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceDetailsWrapper; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.EventPublishingException; +import org.apache.commons.logging.Log; +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.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.protocol.HTTP; + +import java.io.IOException; +import java.net.ConnectException; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class ReportingPublisherManager { + + private static final Log log = LogFactory.getLog(ReportingPublisherManager.class); + private final static ExecutorService executorService; + private DeviceDetailsWrapper payload; + private String endpoint; + private static final PoolingHttpClientConnectionManager poolingManager; + + static { + executorService = Executors.newFixedThreadPool(10); //todo make this configurable + poolingManager = new PoolingHttpClientConnectionManager(); + poolingManager.setMaxTotal(10); //todo make this configurable + poolingManager.setDefaultMaxPerRoute(10); + } + + public Future publishData(DeviceDetailsWrapper deviceDetailsWrapper, String eventUrl) { + this.payload = deviceDetailsWrapper; + this.endpoint = eventUrl; + return executorService.submit(new ReportingPublisher()); + } + + private class ReportingPublisher implements Callable { + @Override + public Integer call() throws EventPublishingException { + try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(poolingManager).build()) { + HttpPost apiEndpoint = new HttpPost(endpoint); + apiEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); + StringEntity requestEntity = new StringEntity(payload.getJSONString(), ContentType.APPLICATION_JSON); + apiEndpoint.setEntity(requestEntity); + HttpResponse response = client.execute(apiEndpoint); + int statusCode = response.getStatusLine().getStatusCode(); + if (log.isDebugEnabled()) { + log.debug("Published data to the reporting backend: " + endpoint + ", Response code: " + statusCode); + } + return statusCode; + } catch (ConnectException e) { + String message = "Connection refused while publishing reporting data to the API: " + endpoint; + log.error(message, e); + throw new EventPublishingException(message, e); + } catch (IOException e) { + String message = "Error occurred when publishing reporting data to the API: " + endpoint; + log.error(message, e); + throw new EventPublishingException(message, e); + } + } + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java index 44f6fe15dd..683971472b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java @@ -1070,4 +1070,5 @@ public interface DeviceManagementProviderService { List getInstalledApplicationsOnDevice(Device device) throws DeviceManagementException; List getEnrolledDevicesSince(Date since) throws DeviceManagementException; List getEnrolledDevicesPriorTo(Date before) throws DeviceManagementException; + void deleteDeviceDataByTenantDomain(String tenantDomain) throws DeviceManagementException; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 5c8a8eb28e..7aad6f8f2e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -21,6 +21,7 @@ package io.entgra.device.mgt.core.device.mgt.core.service; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; +import io.entgra.device.mgt.core.device.mgt.core.dao.TenantDAO; import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; import io.entgra.device.mgt.core.notification.logger.DeviceEnrolmentLogContext; import io.entgra.device.mgt.core.notification.logger.impl.EntgraDeviceEnrolmentLoggerImpl; @@ -160,7 +161,6 @@ import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.*; -import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, @@ -178,6 +178,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv private final ApplicationDAO applicationDAO; private MetadataDAO metadataDAO; private final DeviceStatusDAO deviceStatusDAO; + private final TenantDAO tenantDao; int count = 0; public DeviceManagementProviderServiceImpl() { @@ -188,6 +189,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv this.enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO(); this.deviceStatusDAO = DeviceManagementDAOFactory.getDeviceStatusDAO(); + this.tenantDao = DeviceManagementDAOFactory.getTenantDAO(); /* Registering a listener to retrieve events when some device management service plugin is installed after * the component is done getting initialized */ @@ -5187,4 +5189,94 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } return devices; } + + @Override + public void deleteDeviceDataByTenantDomain(String tenantDomain) throws DeviceManagementException { + int tenantId; + try{ + TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService(); + TenantInfoBean tenantInfoBean = tenantMgtAdminService.getTenant(tenantDomain); + tenantId = tenantInfoBean.getTenantId(); + + } catch (Exception e) { + String msg = "Error getting tenant ID from domain: " + + tenantDomain; + log.error(msg); + throw new DeviceManagementException(msg, e); + } + + try { + DeviceManagementDAOFactory.beginTransaction(); + + tenantDao.deleteExternalPermissionMapping(tenantId); + tenantDao.deleteExternalDeviceMappingByTenantId(tenantId); + tenantDao.deleteExternalGroupMappingByTenantId(tenantId); + // TODO: Check whether deleting DM_DEVICE_ORGANIZATION table data is necessary +// tenantDao.deleteDeviceOrganizationByTenantId(tenantId); + tenantDao.deleteDeviceHistoryLastSevenDaysByTenantId(tenantId); + tenantDao.deleteDeviceDetailByTenantId(tenantId); + tenantDao.deleteDeviceLocationByTenantId(tenantId); + tenantDao.deleteDeviceInfoByTenantId(tenantId); + tenantDao.deleteNotificationByTenantId(tenantId); + tenantDao.deleteAppIconsByTenantId(tenantId); + tenantDao.deleteTraccarUnsyncedDevicesByTenantId(tenantId); + tenantDao.deleteDeviceEventGroupMappingByTenantId(tenantId); + tenantDao.deleteGeofenceEventMappingByTenantId(tenantId); + tenantDao.deleteDeviceEventByTenantId(tenantId); + tenantDao.deleteGeofenceGroupMappingByTenantId(tenantId); + tenantDao.deleteGeofenceByTenantId(tenantId); + tenantDao.deleteDeviceGroupPolicyByTenantId(tenantId); + tenantDao.deleteDynamicTaskPropertiesByTenantId(tenantId); + tenantDao.deleteDynamicTaskByTenantId(tenantId); + tenantDao.deleteMetadataByTenantId(tenantId); + tenantDao.deleteOTPDataByTenantId(tenantId); + tenantDao.deleteSubOperationTemplate(tenantId); + tenantDao.deleteDeviceSubTypeByTenantId(tenantId); + tenantDao.deleteCEAPoliciesByTenantId(tenantId); + + tenantDao.deleteApplicationByTenantId(tenantId); + tenantDao.deletePolicyCriteriaPropertiesByTenantId(tenantId); + tenantDao.deletePolicyCriteriaByTenantId(tenantId); + tenantDao.deleteCriteriaByTenantId(tenantId); + tenantDao.deletePolicyChangeManagementByTenantId(tenantId); + tenantDao.deletePolicyComplianceFeaturesByTenantId(tenantId); + tenantDao.deletePolicyComplianceStatusByTenantId(tenantId); + tenantDao.deleteRolePolicyByTenantId(tenantId); + tenantDao.deleteUserPolicyByTenantId(tenantId); + tenantDao.deleteDeviceTypePolicyByTenantId(tenantId); + tenantDao.deleteDevicePolicyAppliedByTenantId(tenantId); + tenantDao.deleteDevicePolicyByTenantId(tenantId); + tenantDao.deletePolicyCorrectiveActionByTenantId(tenantId); + tenantDao.deletePolicyByTenantId(tenantId); + tenantDao.deleteProfileFeaturesByTenantId(tenantId); + tenantDao.deleteProfileByTenantId(tenantId); + + tenantDao.deleteDeviceOperationResponseLargeByTenantId(tenantId); + tenantDao.deleteDeviceOperationResponseByTenantId(tenantId); + tenantDao.deleteEnrolmentOpMappingByTenantId(tenantId); + tenantDao.deleteDeviceStatusByTenantId(tenantId); + tenantDao.deleteEnrolmentByTenantId(tenantId); + tenantDao.deleteOperationByTenantId(tenantId); + tenantDao.deleteDeviceGroupMapByTenantId(tenantId); + tenantDao.deleteGroupPropertiesByTenantId(tenantId); + tenantDao.deleteDevicePropertiesByTenantId(tenantId); + tenantDao.deleteDeviceByTenantId(tenantId); + tenantDao.deleteRoleGroupMapByTenantId(tenantId); + tenantDao.deleteGroupByTenantId(tenantId); + tenantDao.deleteDeviceCertificateByTenantId(tenantId); + + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error deleting data of tenant of ID: '" + tenantId + "'"; + log.error(msg); + throw new DeviceManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error while initiating transaction when trying to delete tenant info of '" + tenantId + "'"; + log.error(msg); + throw new DeviceManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivalTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivalTask.java index bd1b614ca6..f4048ac905 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivalTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivalTask.java @@ -23,16 +23,16 @@ import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.core.archival.ArchivalException; import io.entgra.device.mgt.core.device.mgt.core.archival.ArchivalService; import io.entgra.device.mgt.core.device.mgt.core.archival.ArchivalServiceImpl; -import org.wso2.carbon.ntask.core.Task; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.concurrent.TimeUnit; -public class ArchivalTask implements Task { +public class ArchivalTask extends RandomlyAssignedScheduleTask { private static final Log log = LogFactory.getLog(ArchivalTask.class); + private static final String TASK_NAME = "DATA_ARCHIVAL_TASK"; private ArchivalService archivalService; @@ -42,12 +42,12 @@ public class ArchivalTask implements Task { } @Override - public void init() { + protected void setup() { this.archivalService = new ArchivalServiceImpl(); } @Override - public void execute() { + protected void executeRandomlyAssignedTask() { log.info("Executing ArchivalTask at " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date())); long startTime = System.currentTimeMillis(); try { @@ -60,6 +60,11 @@ public class ArchivalTask implements Task { log.info("ArchivalTask completed. Total execution time: " + getDurationBreakdown(difference)); } + @Override + public String getTaskName() { + return TASK_NAME; + } + private String getDurationBreakdown(long millis) { if (millis < 0) { throw new IllegalArgumentException("Duration must be greater than zero!"); @@ -74,4 +79,5 @@ public class ArchivalTask implements Task { return (days + " Days " + hours + " Hours " + minutes + " Minutes " + seconds + " Seconds"); } + } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivedDataDeletionTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivedDataDeletionTask.java index 5282467a91..ce507ed52b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivedDataDeletionTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/ArchivedDataDeletionTask.java @@ -29,9 +29,10 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; -public class ArchivedDataDeletionTask implements Task { +public class ArchivedDataDeletionTask extends RandomlyAssignedScheduleTask { - private static Log log = LogFactory.getLog(ArchivedDataDeletionTask.class); + private static final Log log = LogFactory.getLog(ArchivedDataDeletionTask.class); + private static final String TASK_NAME = "ARCHIVED_DATA_CLEANUP_TASK"; private ArchivalService archivalService; @@ -41,12 +42,12 @@ public class ArchivedDataDeletionTask implements Task { } @Override - public void init() { + public void setup() { this.archivalService = new ArchivalServiceImpl(); } @Override - public void execute() { + protected void executeRandomlyAssignedTask() { log.info("Executing DataDeletionTask at " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date())); long startTime = System.nanoTime(); try { @@ -58,4 +59,10 @@ public class ArchivedDataDeletionTask implements Task { long difference = (endTime - startTime) / (1000000 * 1000); log.info("DataDeletionTask completed. Total execution time: " + difference + " seconds"); } + + @Override + public String getTaskName() { + return TASK_NAME; + } + } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java index e267bf4353..9ddeea4e7a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java @@ -109,4 +109,5 @@ public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask { protected void setup() { } + } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java index 9a5338bf35..6ca728cd13 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java @@ -53,7 +53,7 @@ public abstract class DynamicPartitionedScheduleTask implements Task { public final void init() { try { boolean dynamicTaskEnabled = DeviceManagementDataHolder.getInstance().getHeartBeatService().isTaskPartitioningEnabled(); - if(dynamicTaskEnabled){ + if (dynamicTaskEnabled) { taskContext = new DynamicTaskContext(); taskContext.setPartitioningEnabled(true); } else { @@ -75,9 +75,9 @@ public abstract class DynamicPartitionedScheduleTask implements Task { 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 (localHashIndex == null) { if (log.isDebugEnabled()) { - log.debug("Executing startup scheduled task (" + getTaskName() + ") with class: " + + log.debug("Executing startup scheduled task (" + getTaskName() + ") with class: " + this.getClass().getName()); } executeDynamicTask(); @@ -116,7 +116,7 @@ public abstract class DynamicPartitionedScheduleTask implements Task { private void updateContext() throws HeartBeatManagementException { ServerCtxInfo ctxInfo = DeviceManagementDataHolder.getInstance().getHeartBeatService().getServerCtxInfo(); - if(ctxInfo != null) { + if (ctxInfo != null) { populateContext(ctxInfo); } else { log.info("Dynamic Task Context not present. Tasks will run on regular worker/manager mode."); @@ -127,10 +127,10 @@ public abstract class DynamicPartitionedScheduleTask implements Task { taskContext.setActiveServerCount(ctxInfo.getActiveServerCount()); taskContext.setServerHashIndex(ctxInfo.getLocalServerHashIdx()); - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("Initiating execution of dynamic task for server : " + taskContext.getServerHashIndex() + - " where active server count is : " + taskContext.getActiveServerCount() + - " partitioning task enabled : " + taskContext.isPartitioningEnabled()); + " where active server count is : " + taskContext.getActiveServerCount() + + " partitioning task enabled : " + taskContext.isPartitioningEnabled()); } } @@ -142,7 +142,8 @@ public abstract class DynamicPartitionedScheduleTask implements Task { return taskContext; } - public static boolean isDynamicTaskEligible(){ + @Deprecated + public static boolean isDynamicTaskEligible() { return taskContext != null && taskContext.isPartitioningEnabled(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java index 959b2965e1..93c52d8fd0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java @@ -28,8 +28,6 @@ import org.wso2.carbon.ntask.core.Task; public abstract class RandomlyAssignedScheduleTask implements Task { private static final Log log = LogFactory.getLog(RandomlyAssignedScheduleTask.class); - - private static String taskName = "UNSPECIFIED"; private static boolean qualifiedToExecuteTask = false; private static boolean dynamicTaskEnabled = false; @@ -38,32 +36,32 @@ public abstract class RandomlyAssignedScheduleTask implements Task { try { dynamicTaskEnabled = DeviceManagementDataHolder.getInstance().getHeartBeatService().isTaskPartitioningEnabled(); } catch (HeartBeatManagementException e) { - log.error("Error Instantiating Variables necessary for Randomly Assigned Task Scheduling." , e); + log.error("Error Instantiating Variables necessary for Randomly Assigned Task Scheduling.", e); } - //This is done so that sub class extending this abstract class is forced to specify a task name. - taskName = getTaskName(); setup(); } @Override public final void execute() { refreshContext(); - executeRandomlyAssignedTask(); + if (isQualifiedToExecuteTask()) { + executeRandomlyAssignedTask(); + } } - public void refreshContext(){ - if(dynamicTaskEnabled) { + public void refreshContext() { + if (dynamicTaskEnabled) { try { qualifiedToExecuteTask = DeviceManagementDataHolder.getInstance().getHeartBeatService().isQualifiedToExecuteTask(); - log.info("## NODE Qualified to execute Randomly Assigned Task : " + taskName); - DeviceManagementDataHolder.getInstance().getHeartBeatService().updateTaskExecutionAcknowledgement(taskName); } catch (HeartBeatManagementException e) { - log.error("Error refreshing Variables necessary for Randomly Assigned Scheduled Task. " + - "Dynamic Tasks will not function.", e); + log.error("Error refreshing variables necessary for " + + "Randomly Assigned Scheduled Task: " + getTaskName(), e); } } else { qualifiedToExecuteTask = true; } + log.info("Node is " + (qualifiedToExecuteTask ? "" : "not") + + " qualified to execute Randomly Assigned Task : " + getTaskName()); } protected abstract void setup(); @@ -75,4 +73,5 @@ public abstract class RandomlyAssignedScheduleTask implements Task { } public abstract String getTaskName(); + } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java index 288d0c0fc5..ad7a7bf67d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/HttpReportingUtil.java @@ -27,6 +27,7 @@ import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HTTP; import org.json.JSONObject; import io.entgra.device.mgt.core.device.mgt.common.exceptions.EventPublishingException; @@ -49,24 +50,6 @@ public class HttpReportingUtil { return System.getProperty(DeviceManagementConstants.Report.REPORTING_EVENT_HOST); } - public static int invokeApi(String payload, String endpoint) throws EventPublishingException { - try (CloseableHttpClient client = HttpClients.createDefault()) { - HttpPost apiEndpoint = new HttpPost(endpoint); - apiEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - StringEntity requestEntity = new StringEntity( - payload, ContentType.APPLICATION_JSON); - apiEndpoint.setEntity(requestEntity); - HttpResponse response = client.execute(apiEndpoint); - return response.getStatusLine().getStatusCode(); - } catch (ConnectException e) { - log.error("Connection refused to API endpoint: " + endpoint, e); - return HttpStatus.SC_SERVICE_UNAVAILABLE; - } catch (IOException e) { - throw new EventPublishingException("Error occurred when " + - "invoking API. API endpoint: " + endpoint, e); - } - } - public static boolean isPublishingEnabledForTenant() { Object configuration = DeviceManagerUtil.getConfiguration(IS_EVENT_PUBLISHING_ENABLED); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/operation/mdm-ui-config.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/operation/mdm-ui-config.xml index 8b5eba6efa..27ee95b690 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/operation/mdm-ui-config.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/config/operation/mdm-ui-config.xml @@ -379,6 +379,11 @@ win:ops:lock-reset win:ops:reboot win:ops:location + win:ops:apps + win:ops:scan + win:ops:device-info + win:ops:security-info + win:ops:firewall-info admin:tenant:view dm:admin:devices:usage:view and:ops:clear-app diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml index 0a4994969c..5d5d3d252f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml @@ -22,7 +22,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml index 9a127f68c8..a99497bcb7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml @@ -23,7 +23,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index 4101512800..e3ff16a185 100644 --- a/components/device-mgt/pom.xml +++ b/components/device-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml index bb63b53416..d4a1423579 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core heartbeat-management - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java index ca3cc09610..ffd536d232 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java @@ -22,7 +22,6 @@ import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.HeartBeatBeaconC import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.InvalidConfigurationStateException; -import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.ClusterFormationChangedNotifier; import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java index 1706535a6b..fcdee6e5cc 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -147,7 +147,7 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { } } catch (SQLException e) { String msg = "Error occurred while updating task list of elected server : '" + - uuid + "' and task list " + taskList; + uuid + "' and task list " + taskList; log.error(msg, e); throw new HeartBeatDAOException(msg, e); } @@ -187,7 +187,7 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { } } } catch (SQLException e) { - String msg = "Error occurred checking existense of UUID" + uuid + + String msg = "Error occurred checking existence of UUID" + uuid + " amongst heartbeat meta info."; log.error(msg, e); throw new HeartBeatDAOException(msg, e); diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java index bcadf4afe7..6323605b40 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java @@ -65,7 +65,7 @@ public class HeartBeatExecutor implements ServerStartupObserver { Executors.newSingleThreadScheduledExecutor(); if (CONFIG == null) { - String msg = "Error while initiating schedule taks for recording heartbeats."; + String msg = "Error while initiating schedule tasks for recording heartbeats."; log.error(msg); throw new HeartBeatBeaconConfigurationException(msg); } @@ -78,15 +78,15 @@ public class HeartBeatExecutor implements ServerStartupObserver { } int timeOutIntervalInSeconds = CONFIG.getServerTimeOutIntervalInSeconds(); int timeSkew = CONFIG.getTimeSkew(); - int cumilativeTimeOut = timeOutIntervalInSeconds + timeSkew; + int cumulativeTimeOut = timeOutIntervalInSeconds + timeSkew; final String designatedUUID = uuid; HeartBeatBeaconDataHolder.getInstance().setLocalServerUUID(designatedUUID); Runnable periodicTask = new Runnable() { public void run() { try { recordHeartBeat(designatedUUID); - electDynamicTaskExecutionCandidate(cumilativeTimeOut); - notifyClusterFormationChanged(cumilativeTimeOut); + electDynamicTaskExecutionCandidate(cumulativeTimeOut); + notifyClusterFormationChanged(cumulativeTimeOut); } catch (Exception e) { log.error("Error while executing record heart beat task. This will result in schedule operation malfunction.", e); } @@ -97,7 +97,7 @@ public class HeartBeatExecutor implements ServerStartupObserver { CONFIG.getNotifierFrequency() != 0 ? CONFIG.getNotifierFrequency() : DEFAULT__NOTIFIER_INTERVAL, TimeUnit.SECONDS); } catch (HeartBeatManagementException e) { - String msg = "Error occured while updating initial server context."; + String msg = "Error occurred while updating initial server context."; log.error(msg); throw new HeartBeatBeaconConfigurationException(msg, e); } catch (IOException e) { @@ -111,13 +111,14 @@ public class HeartBeatExecutor implements ServerStartupObserver { HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().recordHeartBeat(new HeartBeatEvent(uuid)); } - static void electDynamicTaskExecutionCandidate(int cumilativeTimeOut) + static void electDynamicTaskExecutionCandidate(int cumulativeTimeOut) throws HeartBeatManagementException { - HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().electCandidate(cumilativeTimeOut); + HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().electCandidate(cumulativeTimeOut); } - static void notifyClusterFormationChanged(int cumilativeTimeOut) throws HeartBeatManagementException { - HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().notifyClusterFormationChanged(cumilativeTimeOut); + static void notifyClusterFormationChanged(int cumulativeTimeOut) throws HeartBeatManagementException { + HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService() + .notifyClusterFormationChanged(cumulativeTimeOut); } } diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 6c737c0b2f..c243d4e9b6 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/src/main/java/io/entgra/device/mgt/core/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -50,6 +50,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic private static int lastActiveCount = -1; private static int lastHashIndex = -1; + private static volatile boolean isQualified = false; public HeartBeatManagementServiceImpl() { this.heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); @@ -58,17 +59,17 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic @Override public ServerCtxInfo getServerCtxInfo() throws HeartBeatManagementException { - int hashIndex = -1; - ServerContext localServerCtx = null; + int hashIndex; + ServerContext localServerCtx; ServerCtxInfo serverCtxInfo = null; if (HeartBeatBeaconConfig.getInstance().isEnabled()) { try { HeartBeatBeaconDAOFactory.openConnection(); int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); int timeSkew = HeartBeatBeaconConfig.getInstance().getTimeSkew(); - int cumilativeTimeOut = timeOutIntervalInSeconds + timeSkew; + int cumulativeTimeOut = timeOutIntervalInSeconds + timeSkew; String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); - Map serverCtxMap = heartBeatDAO.getActiveServerDetails(cumilativeTimeOut); + Map serverCtxMap = heartBeatDAO.getActiveServerDetails(cumulativeTimeOut); if (!serverCtxMap.isEmpty()) { localServerCtx = serverCtxMap.get(localServerUUID); if (localServerCtx != null) { @@ -97,7 +98,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic @Override public boolean isTaskPartitioningEnabled() throws HeartBeatManagementException { - boolean enabled = false; + boolean enabled; if (HeartBeatBeaconConfig.getInstance() != null) { enabled = HeartBeatBeaconConfig.getInstance().isEnabled(); } else { @@ -111,7 +112,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic @Override public String updateServerContext(ServerContext ctx) throws HeartBeatManagementException { - String uuid = null; + String uuid; if (HeartBeatBeaconConfig.getInstance().isEnabled()) { try { HeartBeatBeaconDAOFactory.beginTransaction(); @@ -121,12 +122,13 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic HeartBeatBeaconDAOFactory.commitTransaction(); } } catch (HeartBeatDAOException e) { - String msg = "Error Occured while retrieving server context."; + String msg = "Error Occurred while retrieving server context."; log.error(msg, e); throw new HeartBeatManagementException(msg, e); } catch (TransactionManagementException e) { HeartBeatBeaconDAOFactory.rollbackTransaction(); - String msg = "Error occurred while updating server context. Issue in opening a connection to the underlying data source"; + String msg = "Error occurred while updating server context. Issue in opening a connection to the " + + "underlying data source"; log.error(msg, e); throw new HeartBeatManagementException(msg, e); } finally { @@ -141,35 +143,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } @Override - public boolean isQualifiedToExecuteTask() throws HeartBeatManagementException { - boolean isQualified = false; - if (HeartBeatBeaconConfig.getInstance().isEnabled()) { - try { - String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); - HeartBeatBeaconDAOFactory.openConnection(); - ElectedCandidate candidate = heartBeatDAO.retrieveCandidate(); - if (candidate != null && candidate.getServerUUID().equalsIgnoreCase(localServerUUID)) { - isQualified = true; - if (log.isDebugEnabled()) { - log.debug("Node : " + localServerUUID + " Qualified to execute randomly assigned task."); - } - } - } catch (HeartBeatDAOException e) { - String msg = "Error occurred while checking if server is qualified to execute randomly designated task."; - log.error(msg, e); - throw new HeartBeatManagementException(msg, e); - } catch (SQLException e) { - String msg = "Error occurred while opening a connection to the underlying data source"; - log.error(msg, e); - throw new HeartBeatManagementException(msg, e); - } finally { - HeartBeatBeaconDAOFactory.closeConnection(); - } - } else { - String msg = "Heart Beat Configuration Disabled. Error occurred while checking if server is qualified to execute randomly designated task."; - log.error(msg); - throw new HeartBeatManagementException(msg); - } + public boolean isQualifiedToExecuteTask() { return isQualified; } @@ -229,7 +203,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic if (presentCandidate != null) { //if candidate is older than stipulated elapsed-time, purge and re-elect if (presentCandidate.getTimeOfElection().before(new Timestamp(System.currentTimeMillis() - - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds)))) { + - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds)))) { heartBeatDAO.purgeCandidates(); electCandidate(servers); } @@ -240,13 +214,24 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } HeartBeatBeaconDAOFactory.commitTransaction(); } + ElectedCandidate candidate = heartBeatDAO.retrieveCandidate(); + String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); + if (candidate != null && candidate.getServerUUID().equalsIgnoreCase(localServerUUID)) { + isQualified = true; + if (log.isDebugEnabled()) { + log.debug("Node : " + localServerUUID + " is qualified to execute randomly assigned task."); + } + } else { + isQualified = false; + } } catch (HeartBeatDAOException e) { String msg = "Error occurred while electing candidate for dynamic task execution."; log.error(msg, e); throw new HeartBeatManagementException(msg, e); } catch (TransactionManagementException e) { HeartBeatBeaconDAOFactory.rollbackTransaction(); - String msg = "Error occurred while electing candidate for dynamic task execution. Issue in opening a connection to the underlying data source"; + String msg = "Error occurred while electing candidate for dynamic task execution. " + + "Issue in opening a connection to the underlying data source"; log.error(msg, e); throw new HeartBeatManagementException(msg, e); } finally { @@ -258,6 +243,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic throw new HeartBeatManagementException(msg); } } + @Override public void notifyClusterFormationChanged(int elapsedTimeInSeconds) throws HeartBeatManagementException { if (HeartBeatBeaconConfig.getInstance().isEnabled()) { @@ -278,7 +264,8 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic lastHashIndex = serverContext.getIndex(); lastActiveCount = servers.size(); - ClusterFormationChangedNotifierRepository repository = HeartBeatBeaconDataHolder.getInstance().getClusterFormationChangedNotifierRepository(); + ClusterFormationChangedNotifierRepository repository = HeartBeatBeaconDataHolder.getInstance() + .getClusterFormationChangedNotifierRepository(); Map notifiers = repository.getNotifiers(); for (String type : notifiers.keySet()) { ClusterFormationChangedNotifier notifier = notifiers.get(type); @@ -372,8 +359,8 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic HeartBeatBeaconDAOFactory.openConnection(); int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); int timeSkew = HeartBeatBeaconConfig.getInstance().getTimeSkew(); - int cumilativeTimeOut = timeOutIntervalInSeconds + timeSkew; - Map serverCtxMap = heartBeatDAO.getActiveServerDetails(cumilativeTimeOut); + int cumulativeTimeOut = timeOutIntervalInSeconds + timeSkew; + Map serverCtxMap = heartBeatDAO.getActiveServerDetails(cumulativeTimeOut); for (String uuid : serverCtxMap.keySet()) { ServerContext serverContext = serverCtxMap.get(uuid); activeServers.put(serverContext.getIndex(), serverContext); @@ -396,4 +383,5 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } return activeServers; } + } diff --git a/components/heartbeat-management/pom.xml b/components/heartbeat-management/pom.xml index c60383a29c..144a391a6f 100644 --- a/components/heartbeat-management/pom.xml +++ b/components/heartbeat-management/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml index 11b3fa0f6c..f9e469335b 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core identity-extensions - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml index eb84d0655a..3c44fc89af 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core identity-extensions - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index 9c1505344d..9d9d13a9eb 100644 --- a/components/identity-extensions/pom.xml +++ b/components/identity-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml b/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml index 588f8c8cfa..26e29d584d 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core logger - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT io.entgra.device.mgt.core.notification.logger diff --git a/components/logger/pom.xml b/components/logger/pom.xml index 9bd16c78f0..28f050bcd1 100644 --- a/components/logger/pom.xml +++ b/components/logger/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml index ba494c6bef..a1f8fd8ca1 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core operation-template-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/operation-template-mgt/pom.xml b/components/operation-template-mgt/pom.xml index 17b743ed33..57d6048b31 100644 --- a/components/operation-template-mgt/pom.xml +++ b/components/operation-template-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml index 35decb5751..e979327e53 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml index 850d105f35..f9d89bdcab 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml index fafd38128f..7e6c53db05 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml index 7592611d0e..1b25b8d1d1 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/DelegationTask.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/DelegationTask.java index c1bdd4fba7..dfa5ae4f5e 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/DelegationTask.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/enforcement/DelegationTask.java @@ -64,7 +64,7 @@ public class DelegationTask extends DynamicPartitionedScheduleTask { try { devices = new ArrayList<>(); toBeNotified = new ArrayList<>(); - if (isDynamicTaskEligible()) { + if(getTaskContext() != null && getTaskContext().isPartitioningEnabled()){ devices.addAll(service.getAllocatedDevices(deviceType, getTaskContext().getActiveServerCount(), getTaskContext().getServerHashIndex())); diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyAdministratorPointImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyAdministratorPointImpl.java index 7ead0213c9..cf06ff2668 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyAdministratorPointImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/impl/PolicyAdministratorPointImpl.java @@ -154,6 +154,10 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { //Check whether the TaskType is already registered. If not we'll register it here. if (!registeredTaskTypes.contains(PolicyManagementConstants.DELEGATION_TASK_TYPE)) { taskService.registerTaskType(PolicyManagementConstants.DELEGATION_TASK_TYPE); + // Delete init task if exists + if (taskManager.isTaskScheduled(taskName)) { + taskManager.deleteTask(taskName); + } } TaskInfo registeredTaskInfo = null; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/MonitoringTask.java index 8836b00892..42b6e745ab 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/task/MonitoringTask.java @@ -105,7 +105,7 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { PolicyManagementDataHolder.getInstance().getDeviceManagementService() .getPolicyMonitoringManager(deviceType); List devices; - if(isDynamicTaskEligible()){ + if (getTaskContext() != null && getTaskContext().isPartitioningEnabled()) { devices = deviceManagementProviderService .getAllocatedDevices(deviceType, getTaskContext().getActiveServerCount(), getTaskContext().getServerHashIndex()); diff --git a/components/policy-mgt/pom.xml b/components/policy-mgt/pom.xml index 9653276a94..44c54eddd7 100644 --- a/components/policy-mgt/pom.xml +++ b/components/policy-mgt/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml index 87088c9b7e..69bce27091 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core subtype-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java index c6d8c0e69d..7bf985e5b9 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/cache/GetDeviceSubTypeCacheLoader.java @@ -19,20 +19,19 @@ package io.entgra.device.mgt.core.subtype.mgt.cache; import com.google.common.cache.CacheLoader; -import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubTypeCacheKey; import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAO; import io.entgra.device.mgt.core.subtype.mgt.dao.DeviceSubTypeDAOFactory; import io.entgra.device.mgt.core.subtype.mgt.dao.util.ConnectionManagerUtil; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; +import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubTypeCacheKey; import io.entgra.device.mgt.core.subtype.mgt.exception.DBConnectionException; import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtDAOException; import io.entgra.device.mgt.core.subtype.mgt.exception.SubTypeMgtPluginException; -import io.entgra.device.mgt.core.subtype.mgt.util.DeviceSubTypeMgtUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -public class GetDeviceSubTypeCacheLoader extends CacheLoader { +public class GetDeviceSubTypeCacheLoader extends CacheLoader { private static final Log log = LogFactory.getLog(GetDeviceSubTypeCacheLoader.class); @@ -43,14 +42,13 @@ public class GetDeviceSubTypeCacheLoader extends CacheLoader deviceSubTypeCache = CacheBuilder.newBuilder() - .expireAfterWrite(15, TimeUnit.MINUTES).build(new GetDeviceSubTypeCacheLoader()); + private static final LoadingCache deviceSubTypeCache + = CacheBuilder.newBuilder() + .expireAfterWrite(15, TimeUnit.MINUTES) + .build(new GetDeviceSubTypeCacheLoader()); private final DeviceSubTypeDAO deviceSubTypeDAO; public DeviceSubTypeServiceImpl() { @@ -52,7 +55,7 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { @Override public boolean addDeviceSubType(DeviceSubType deviceSubType) throws SubTypeMgtPluginException { - String msg = ""; + String msg; int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); deviceSubType.setTenantId(tenantId); @@ -72,9 +75,6 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { throw new SubTypeMgtPluginException(msg); } ConnectionManagerUtil.commitDBTransaction(); - String key = DeviceSubTypeMgtUtil.setDeviceSubTypeCacheKey(tenantId, deviceSubType.getSubTypeId(), - deviceSubType.getDeviceType()); - deviceSubTypeCache.put(key, deviceSubType); return true; } catch (DBConnectionException e) { msg = "Error occurred while obtaining the database connection to add device subtype for " + @@ -89,6 +89,10 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { throw new SubTypeMgtPluginException(msg, e); } finally { ConnectionManagerUtil.closeDBConnection(); + DeviceSubTypeCacheKey key = DeviceSubTypeMgtUtil.getDeviceSubTypeCacheKey(tenantId, + deviceSubType.getSubTypeId(), + deviceSubType.getDeviceType()); + deviceSubTypeCache.refresh(key); } } @@ -96,7 +100,7 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { public boolean updateDeviceSubType(String subTypeId, int tenantId, String deviceType, String subTypeName, String typeDefinition) throws SubTypeMgtPluginException { - String msg = ""; + String msg; DeviceSubType deviceSubTypeOld = getDeviceSubType(subTypeId, tenantId, deviceType); if (deviceSubTypeOld == null) { @@ -133,7 +137,7 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { throw new SubTypeMgtPluginException(msg, e); } finally { ConnectionManagerUtil.closeDBConnection(); - String key = DeviceSubTypeMgtUtil.setDeviceSubTypeCacheKey(tenantId, subTypeId, deviceType); + DeviceSubTypeCacheKey key = DeviceSubTypeMgtUtil.getDeviceSubTypeCacheKey(tenantId, subTypeId, deviceType); deviceSubTypeCache.refresh(key); } } @@ -142,7 +146,7 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { public DeviceSubType getDeviceSubType(String subTypeId, int tenantId, String deviceType) throws SubTypeMgtPluginException { try { - String key = DeviceSubTypeMgtUtil.setDeviceSubTypeCacheKey(tenantId, subTypeId, deviceType); + DeviceSubTypeCacheKey key = DeviceSubTypeMgtUtil.getDeviceSubTypeCacheKey(tenantId, subTypeId, deviceType); return deviceSubTypeCache.get(key); } catch (CacheLoader.InvalidCacheLoadException e) { String msg = "Not having any" + deviceType + " subtype for subtype id: " + subTypeId; @@ -179,12 +183,7 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService { @Override public int getDeviceSubTypeCount(String deviceType) throws SubTypeMgtPluginException { try { - int result = deviceSubTypeDAO.getDeviceSubTypeCount(deviceType); - if (result <= 0) { - String msg = "There are no any subtypes for device type: " + deviceType; - log.error(msg); - } - return result; + return deviceSubTypeDAO.getDeviceSubTypeCount(deviceType); } catch (SubTypeMgtDAOException e) { String msg = "Error occurred in the database level while retrieving device subtypes count for " + deviceType + " subtypes"; diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/util/DeviceSubTypeMgtUtil.java b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/util/DeviceSubTypeMgtUtil.java index 1d84bbf0f9..748846cd7f 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/util/DeviceSubTypeMgtUtil.java +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/main/java/io/entgra/device/mgt/core/subtype/mgt/util/DeviceSubTypeMgtUtil.java @@ -19,23 +19,15 @@ package io.entgra.device.mgt.core.subtype.mgt.util; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubTypeCacheKey; -import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; public class DeviceSubTypeMgtUtil { - public static String setDeviceSubTypeCacheKey(int tenantId, String subTypeId, String deviceType) { - return tenantId + "|" + subTypeId + "|" + deviceType.toString(); - } - - public static DeviceSubTypeCacheKey getDeviceSubTypeCacheKey(String key) { - String[] keys = key.split("\\|"); - int tenantId = Integer.parseInt(keys[0]); - String subTypeId = keys[1]; - String deviceType = keys[2]; + public static DeviceSubTypeCacheKey getDeviceSubTypeCacheKey(int tenantId, String subTypeId, String deviceType) { DeviceSubTypeCacheKey deviceSubTypesCacheKey = new DeviceSubTypeCacheKey(); deviceSubTypesCacheKey.setTenantId(tenantId); deviceSubTypesCacheKey.setSubTypeId(subTypeId); deviceSubTypesCacheKey.setDeviceType(deviceType); return deviceSubTypesCacheKey; } + } diff --git a/components/subtype-mgt/pom.xml b/components/subtype-mgt/pom.xml index 71c7667165..51dc884b45 100644 --- a/components/subtype-mgt/pom.xml +++ b/components/subtype-mgt/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/task-mgt/pom.xml b/components/task-mgt/pom.xml index 0864633471..4b447f0e38 100755 --- a/components/task-mgt/pom.xml +++ b/components/task-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml index 1d944492e6..3f47201bf8 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml @@ -20,7 +20,7 @@ task-manager io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/constant/TaskMgtConstants.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/constant/TaskMgtConstants.java index e5458b6a06..0a6e33379e 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/constant/TaskMgtConstants.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/constant/TaskMgtConstants.java @@ -49,5 +49,6 @@ public class TaskMgtConstants { public static final String TENANT_ID_PROP = "__TENANT_ID_PROP__"; public static final String LOCAL_HASH_INDEX = "__LOCAL_HASH_INDEX__"; public static final String LOCAL_TASK_NAME = "__LOCAL_TASK_NAME__"; + public static final String DYNAMIC_TASK_ID = "__DYNAMIC_TASK_ID__"; } } diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/spi/TaskManagementService.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/spi/TaskManagementService.java index f07cb49083..ab8a02199f 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/spi/TaskManagementService.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/src/main/java/io/entgra/device/mgt/core/task/mgt/common/spi/TaskManagementService.java @@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.task.mgt.common.exception.TaskNotFoundException import io.entgra.device.mgt.core.task.mgt.common.exception.TaskManagementException; import java.util.List; +import java.util.Map; public interface TaskManagementService { @@ -37,7 +38,9 @@ public interface TaskManagementService { List getAllDynamicTasks() throws TaskManagementException; - DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementException; + Map> getDynamicTasksForAllTenants() throws TaskManagementException; + + DynamicTask getDynamicTask(int dynamicTaskId) throws TaskManagementException; List getActiveDynamicTasks() throws TaskManagementException; } diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml index 63cac6e61e..583e05bfeb 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-manager - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/DynamicTaskDAO.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/DynamicTaskDAO.java index 759de555b4..7493e9a025 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/DynamicTaskDAO.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/DynamicTaskDAO.java @@ -27,16 +27,18 @@ import java.util.List; */ public interface DynamicTaskDAO { - int addTask(DynamicTask dynamicTask) throws TaskManagementDAOException; + int addTask(DynamicTask dynamicTask, int tenantId) throws TaskManagementDAOException; - boolean updateDynamicTask(DynamicTask dynamicTask) throws TaskManagementDAOException; + boolean updateDynamicTask(DynamicTask dynamicTask, int tenantId) throws TaskManagementDAOException; - void deleteDynamicTask(int dynamicTaskId) throws TaskManagementDAOException; + void deleteDynamicTask(int dynamicTaskId, int tenantId) throws TaskManagementDAOException; - DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementDAOException; + DynamicTask getDynamicTask(int dynamicTaskId, int tenantId) throws TaskManagementDAOException; List getAllDynamicTasks() throws TaskManagementDAOException; - List getActiveDynamicTasks() throws TaskManagementDAOException; + List getAllDynamicTasks(int tenantId) throws TaskManagementDAOException; + + List getActiveDynamicTasks(int tenantId) throws TaskManagementDAOException; } diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/DynamicTaskPropDAO.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/DynamicTaskPropDAO.java index 7a448da0fa..1ef3fd5a91 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/DynamicTaskPropDAO.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/DynamicTaskPropDAO.java @@ -26,10 +26,11 @@ import java.util.Map; */ public interface DynamicTaskPropDAO { - void addTaskProperties(int dynamicTaskId, Map properties) throws TaskManagementDAOException; + void addTaskProperties(int dynamicTaskId, Map properties, int tenantId) + throws TaskManagementDAOException; - Map getDynamicTaskProps(int dynamicTaskId) throws TaskManagementDAOException; + Map getDynamicTaskProps(int dynamicTaskId, int tenantId) throws TaskManagementDAOException; - void updateDynamicTaskProps(int dynamicTaskId, Map properties) + void updateDynamicTaskProps(int dynamicTaskId, Map properties, int tenantId) throws TaskManagementDAOException; } diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java index 7c0aa2ff0b..e70e41689b 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/common/TaskManagementDAOFactory.java @@ -103,18 +103,22 @@ public class TaskManagementDAOFactory { conn.setAutoCommit(false); currentConnection.set(conn); } catch (SQLException e) { - throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e); + throw new TransactionManagementException("Error occurred while retrieving datasource connection", e); } } - public static void openConnection() throws SQLException { + public static void openConnection() throws TransactionManagementException { Connection conn = currentConnection.get(); if (conn != null) { throw new IllegalTransactionStateException("A transaction is already active within the context of " + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + "transaction is already active is a sign of improper transaction handling"); } - conn = dataSource.getConnection(); + try { + conn = dataSource.getConnection(); + } catch (SQLException e) { + throw new TransactionManagementException("Error occurred while retrieving datasource connection", e); + } currentConnection.set(conn); } diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskDAOImpl.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskDAOImpl.java index f115176717..843b5c9189 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskDAOImpl.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskDAOImpl.java @@ -17,16 +17,19 @@ */ package io.entgra.device.mgt.core.task.mgt.core.dao.impl; -import io.entgra.device.mgt.core.task.mgt.core.dao.common.TaskManagementDAOFactory; -import io.entgra.device.mgt.core.task.mgt.core.dao.util.TaskManagementDAOUtil; import io.entgra.device.mgt.core.task.mgt.common.bean.DynamicTask; import io.entgra.device.mgt.core.task.mgt.common.exception.TaskManagementDAOException; import io.entgra.device.mgt.core.task.mgt.core.dao.DynamicTaskDAO; +import io.entgra.device.mgt.core.task.mgt.core.dao.common.TaskManagementDAOFactory; +import io.entgra.device.mgt.core.task.mgt.core.dao.util.TaskManagementDAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import java.sql.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; import java.util.List; @@ -34,9 +37,9 @@ public class DynamicTaskDAOImpl implements DynamicTaskDAO { private static final Log log = LogFactory.getLog(DynamicTaskDAOImpl.class); @Override - public int addTask(DynamicTask dynamicTask) throws TaskManagementDAOException { + public int addTask(DynamicTask dynamicTask, int tenantId) throws TaskManagementDAOException { PreparedStatement stmt = null; - ResultSet rs = null; + ResultSet rs; int taskId = -1; try { Connection conn = TaskManagementDAOFactory.getConnection(); @@ -48,13 +51,14 @@ public class DynamicTaskDAOImpl implements DynamicTaskDAO { stmt.setString(2, dynamicTask.getName()); stmt.setBoolean(3, dynamicTask.isEnabled()); stmt.setString(4, dynamicTask.getTaskClassName()); - stmt.setInt(5, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.setInt(5, tenantId); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if (rs.next()) { taskId = rs.getInt(1); } + dynamicTask.setDynamicTaskId(taskId); return taskId; } catch (SQLException e) { String msg = "Error occurred while inserting task '" + dynamicTask.getName() + "'"; @@ -66,16 +70,17 @@ public class DynamicTaskDAOImpl implements DynamicTaskDAO { } @Override - public boolean updateDynamicTask(DynamicTask dynamicTask) throws TaskManagementDAOException { + public boolean updateDynamicTask(DynamicTask dynamicTask, int tenantId) throws TaskManagementDAOException { PreparedStatement stmt = null; int rows; try { Connection conn = TaskManagementDAOFactory.getConnection(); - String sql = "UPDATE DYNAMIC_TASK SET CRON = ?,IS_ENABLED = ? WHERE DYNAMIC_TASK_ID = ?"; + String sql = "UPDATE DYNAMIC_TASK SET CRON = ?,IS_ENABLED = ? WHERE DYNAMIC_TASK_ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, dynamicTask.getCronExpression()); stmt.setBoolean(2, dynamicTask.isEnabled()); stmt.setInt(3, dynamicTask.getDynamicTaskId()); + stmt.setInt(4, tenantId); rows = stmt.executeUpdate(); return (rows > 0); } catch (SQLException e) { @@ -87,9 +92,8 @@ public class DynamicTaskDAOImpl implements DynamicTaskDAO { } } - @Override - public void deleteDynamicTask(int dynamicTaskId) throws TaskManagementDAOException { + public void deleteDynamicTask(int dynamicTaskId, int tenantId) throws TaskManagementDAOException { if (log.isDebugEnabled()) { log.debug("Request received in DAO Layer to delete dynamic task with the id: " + dynamicTaskId); } @@ -98,7 +102,7 @@ public class DynamicTaskDAOImpl implements DynamicTaskDAO { Connection conn = TaskManagementDAOFactory.getConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { stmt.setInt(1, dynamicTaskId); - stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.setInt(2, tenantId); stmt.executeUpdate(); } } catch (SQLException e) { @@ -110,7 +114,7 @@ public class DynamicTaskDAOImpl implements DynamicTaskDAO { } @Override - public DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementDAOException { + public DynamicTask getDynamicTask(int dynamicTaskId, int tenantId) throws TaskManagementDAOException { DynamicTask dynamicTask = null; try { Connection conn = TaskManagementDAOFactory.getConnection(); @@ -118,7 +122,7 @@ public class DynamicTaskDAOImpl implements DynamicTaskDAO { try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, dynamicTaskId); - stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.setInt(2, tenantId); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { dynamicTask = TaskManagementDAOUtil.loadDynamicTask(rs); @@ -155,13 +159,35 @@ public class DynamicTaskDAOImpl implements DynamicTaskDAO { } @Override - public List getActiveDynamicTasks() throws TaskManagementDAOException { - List dynamicTasks = null; + public List getAllDynamicTasks(int tenantId) throws TaskManagementDAOException { + List dynamicTasks; + try { + Connection conn = TaskManagementDAOFactory.getConnection(); + String sql = "SELECT * FROM DYNAMIC_TASK WHERE TENANT_ID = ?"; + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + dynamicTasks = TaskManagementDAOUtil.loadDynamicTasks(rs); + } + } + } catch (SQLException e) { + String msg = "Error occurred while getting all dynamic task data "; + log.error(msg, e); + throw new TaskManagementDAOException(msg, e); + } + return dynamicTasks; + } + + @Override + public List getActiveDynamicTasks(int tenantId) throws TaskManagementDAOException { + List dynamicTasks; try { Connection conn = TaskManagementDAOFactory.getConnection(); - String sql = "SELECT * FROM DYNAMIC_TASK WHERE IS_ENABLED = 'true' "; + String sql = "SELECT * FROM DYNAMIC_TASK WHERE IS_ENABLED = 'true' AND TENANT_ID = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); try (ResultSet rs = stmt.executeQuery()) { dynamicTasks = TaskManagementDAOUtil.loadDynamicTasks(rs); } @@ -173,4 +199,5 @@ public class DynamicTaskDAOImpl implements DynamicTaskDAO { } return dynamicTasks; } + } diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java index 10d502f322..5979832130 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/dao/impl/DynamicTaskPropDAOImpl.java @@ -38,9 +38,9 @@ public class DynamicTaskPropDAOImpl implements DynamicTaskPropDAO { private static final Log log = LogFactory.getLog(DynamicTaskPropDAOImpl.class); @Override - public void addTaskProperties(int taskId, Map properties) + public void addTaskProperties(int taskId, Map properties, int tenantId) throws TaskManagementDAOException { - Connection conn = null; + Connection conn; PreparedStatement stmt = null; try { conn = TaskManagementDAOFactory.getConnection(); @@ -51,7 +51,7 @@ public class DynamicTaskPropDAOImpl implements DynamicTaskPropDAO { stmt.setInt(1, taskId); stmt.setString(2, propertyKey); stmt.setString(3, properties.get(propertyKey)); - stmt.setInt(4, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.setInt(4, tenantId); stmt.addBatch(); } stmt.executeBatch(); @@ -64,17 +64,17 @@ public class DynamicTaskPropDAOImpl implements DynamicTaskPropDAO { } } - - public Map getDynamicTaskProps(int dynamicTaskId) throws TaskManagementDAOException { - Connection conn = null; + public Map getDynamicTaskProps(int dynamicTaskId, int tenantId) throws TaskManagementDAOException { + Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; Map properties; try { conn = TaskManagementDAOFactory.getConnection(); stmt = conn.prepareStatement( - "SELECT * FROM DYNAMIC_TASK_PROPERTIES WHERE DYNAMIC_TASK_ID = ?"); + "SELECT * FROM DYNAMIC_TASK_PROPERTIES WHERE DYNAMIC_TASK_ID = ? AND TENANT_ID = ?"); stmt.setInt(1, dynamicTaskId); + stmt.setInt(2, tenantId); resultSet = stmt.executeQuery(); properties = new HashMap<>(); while (resultSet.next()) { @@ -92,7 +92,7 @@ public class DynamicTaskPropDAOImpl implements DynamicTaskPropDAO { } @Override - public void updateDynamicTaskProps(int dynamicTaskId, Map properties) + public void updateDynamicTaskProps(int dynamicTaskId, Map properties, int tenantId) throws TaskManagementDAOException { if (properties.isEmpty()) { if (log.isDebugEnabled()) { @@ -105,12 +105,13 @@ public class DynamicTaskPropDAOImpl implements DynamicTaskPropDAO { try { conn = TaskManagementDAOFactory.getConnection(); stmt = conn.prepareStatement("UPDATE DYNAMIC_TASK_PROPERTIES SET PROPERTY_VALUE = ? " + - "WHERE DYNAMIC_TASK_ID = ? AND PROPERTY_NAME = ?"); + "WHERE DYNAMIC_TASK_ID = ? AND PROPERTY_NAME = ? AND TENANT_ID = ?"); for (Map.Entry entry : properties.entrySet()) { stmt.setString(1, entry.getValue()); stmt.setInt(2, dynamicTaskId); stmt.setString(3, entry.getKey()); + stmt.setInt(4, tenantId); stmt.addBatch(); } stmt.executeBatch(); @@ -121,4 +122,5 @@ public class DynamicTaskPropDAOImpl implements DynamicTaskPropDAO { TaskManagementDAOUtil.cleanupResources(stmt, null); } } + } diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/service/TaskManagementServiceImpl.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/service/TaskManagementServiceImpl.java index 4a8252a36b..c794a4e934 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/service/TaskManagementServiceImpl.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/service/TaskManagementServiceImpl.java @@ -17,10 +17,6 @@ */ package io.entgra.device.mgt.core.task.mgt.core.service; -import io.entgra.device.mgt.core.task.mgt.core.dao.DynamicTaskPropDAO; -import io.entgra.device.mgt.core.task.mgt.core.dao.common.TaskManagementDAOFactory; -import io.entgra.device.mgt.core.task.mgt.core.internal.TaskManagerDataHolder; -import io.entgra.device.mgt.core.task.mgt.core.util.TaskManagementUtil; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.device.mgt.core.task.mgt.common.bean.DynamicTask; import io.entgra.device.mgt.core.task.mgt.common.constant.TaskMgtConstants; @@ -30,14 +26,21 @@ import io.entgra.device.mgt.core.task.mgt.common.exception.TaskNotFoundException import io.entgra.device.mgt.core.task.mgt.common.exception.TransactionManagementException; import io.entgra.device.mgt.core.task.mgt.common.spi.TaskManagementService; import io.entgra.device.mgt.core.task.mgt.core.dao.DynamicTaskDAO; +import io.entgra.device.mgt.core.task.mgt.core.dao.DynamicTaskPropDAO; +import io.entgra.device.mgt.core.task.mgt.core.dao.common.TaskManagementDAOFactory; +import io.entgra.device.mgt.core.task.mgt.core.internal.TaskManagerDataHolder; +import io.entgra.device.mgt.core.task.mgt.core.util.TaskManagementUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.TaskInfo; import org.wso2.carbon.ntask.core.TaskManager; import org.wso2.carbon.ntask.core.service.TaskService; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -78,42 +81,44 @@ public class TaskManagementServiceImpl implements TaskManagementService { @Override public void createTask(DynamicTask dynamicTask) throws TaskManagementException { - String taskId; + String nTaskName; + int dynamicTaskId; + int serverHashIdx; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { // add into the dynamic task tables TaskManagementDAOFactory.beginTransaction(); - int dynamicTaskId = dynamicTaskDAO.addTask(dynamicTask); - - Map taskProperties = dynamicTask.getProperties(); - dynamicTaskPropDAO.addTaskProperties(dynamicTaskId, taskProperties); - - // add into the ntask core - taskId = TaskManagementUtil.generateTaskId(dynamicTaskId); + dynamicTaskId = dynamicTaskDAO.addTask(dynamicTask, tenantId); + dynamicTask.setDynamicTaskId(dynamicTaskId); + dynamicTaskPropDAO.addTaskProperties(dynamicTaskId, dynamicTask.getProperties(), tenantId); try { - int serverHashIdx = TaskManagerDataHolder.getInstance().getHeartBeatService() + serverHashIdx = TaskManagerDataHolder.getInstance().getHeartBeatService() .getServerCtxInfo().getLocalServerHashIdx(); - taskProperties.put(TaskMgtConstants.Task.LOCAL_HASH_INDEX, String.valueOf(serverHashIdx)); - taskProperties.put(TaskMgtConstants.Task.LOCAL_TASK_NAME, taskId); + nTaskName = TaskManagementUtil.generateNTaskName(dynamicTaskId, serverHashIdx); } catch (HeartBeatManagementException e) { String msg = "Unexpected exception when getting server hash index."; log.error(msg, e); throw new TaskManagementException(msg, e); } - if (!isTaskExists(taskId)) { - TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); - triggerInfo.setCronExpression(dynamicTask.getCronExpression()); - TaskInfo taskInfo = new TaskInfo(taskId, dynamicTask.getTaskClassName(), taskProperties, triggerInfo); - taskManager.registerTask(taskInfo); - taskManager.scheduleTask(taskId); - if (!dynamicTask.isEnabled()) { - taskManager.pauseTask(taskId); - } - } else { - String msg = "Task '" + taskId + "' is already exists in the ntask core " - + "Hence not creating another task for the same name."; - log.error(msg); + if (isTaskExists(nTaskName)) { + String msg = "Task '" + nTaskName + "' is already exists in the ntask core. " + + "Hence removing existing task from nTask before adding new one."; + log.warn(msg); + taskManager.deleteTask(nTaskName); + } + + // add into the ntask core + Map taskProperties = TaskManagementUtil + .populateNTaskProperties(dynamicTask, nTaskName, serverHashIdx); + TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); + triggerInfo.setCronExpression(dynamicTask.getCronExpression()); + TaskInfo taskInfo = new TaskInfo(nTaskName, dynamicTask.getTaskClassName(), taskProperties, triggerInfo); + taskManager.registerTask(taskInfo); + taskManager.scheduleTask(nTaskName); + if (!dynamicTask.isEnabled()) { + taskManager.pauseTask(nTaskName); } TaskManagementDAOFactory.commitTransaction(); @@ -137,19 +142,20 @@ public class TaskManagementServiceImpl implements TaskManagementService { } @Override - public void updateTask(int dynamicTaskId, DynamicTask dynamicTask) throws TaskManagementException - , TaskNotFoundException { + public void updateTask(int dynamicTaskId, DynamicTask dynamicTask) + throws TaskManagementException, TaskNotFoundException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { //Update dynamic task table TaskManagementDAOFactory.beginTransaction(); - DynamicTask existingTask = dynamicTaskDAO.getDynamicTaskById(dynamicTaskId); + DynamicTask existingTask = dynamicTaskDAO.getDynamicTask(dynamicTaskId, tenantId); if (existingTask != null) { existingTask.setEnabled(dynamicTask.isEnabled()); existingTask.setCronExpression(dynamicTask.getCronExpression()); - dynamicTaskDAO.updateDynamicTask(existingTask); + dynamicTaskDAO.updateDynamicTask(existingTask, tenantId); if (!dynamicTask.getProperties().isEmpty()) { - dynamicTaskPropDAO.updateDynamicTaskProps(dynamicTaskId, dynamicTask.getProperties()); + dynamicTaskPropDAO.updateDynamicTaskProps(dynamicTaskId, dynamicTask.getProperties(), tenantId); } } else { String msg = "Task '" + dynamicTaskId + "' is not exists in the dynamic task table."; @@ -158,12 +164,14 @@ public class TaskManagementServiceImpl implements TaskManagementService { } // Update task in the ntask core - String taskId = TaskManagementUtil.generateTaskId(existingTask.getDynamicTaskId()); - if (isTaskExists(taskId)) { - TaskInfo taskInfo = taskManager.getTask(taskId); - if (!dynamicTask.getProperties().isEmpty()) { - taskInfo.setProperties(dynamicTask.getProperties()); - } + String nTaskName = TaskManagementUtil.generateNTaskName(existingTask.getDynamicTaskId()); + if (isTaskExists(nTaskName)) { + TaskInfo taskInfo = taskManager.getTask(nTaskName); + + Map taskProperties = TaskManagementUtil + .populateNTaskProperties(dynamicTask, nTaskName); + taskInfo.setProperties(taskProperties); + TaskInfo.TriggerInfo triggerInfo; if (taskInfo.getTriggerInfo() == null) { triggerInfo = new TaskInfo.TriggerInfo(); @@ -173,9 +181,9 @@ public class TaskManagementServiceImpl implements TaskManagementService { triggerInfo.setCronExpression(dynamicTask.getCronExpression()); taskInfo.setTriggerInfo(triggerInfo); taskManager.registerTask(taskInfo); - taskManager.rescheduleTask(taskId); + taskManager.rescheduleTask(nTaskName); } else { - String msg = "Task '" + taskId + "' is not exists in the n task core " + String msg = "Task '" + nTaskName + "' is not exists in the n task core " + "Hence cannot update the task."; log.error(msg); } @@ -200,16 +208,17 @@ public class TaskManagementServiceImpl implements TaskManagementService { } @Override - public void toggleTask(int dynamicTaskId, boolean isEnabled) throws TaskManagementException - , TaskNotFoundException { + public void toggleTask(int dynamicTaskId, boolean isEnabled) + throws TaskManagementException, TaskNotFoundException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { //update dynamic task table TaskManagementDAOFactory.beginTransaction(); - DynamicTask existingTask = dynamicTaskDAO.getDynamicTaskById(dynamicTaskId); + DynamicTask existingTask = dynamicTaskDAO.getDynamicTask(dynamicTaskId, tenantId); if (existingTask != null) { existingTask.setEnabled(isEnabled); - dynamicTaskDAO.updateDynamicTask(existingTask); + dynamicTaskDAO.updateDynamicTask(existingTask, tenantId); } else { String msg = "Task '" + dynamicTaskId + "' is not exists."; log.error(msg); @@ -217,15 +226,15 @@ public class TaskManagementServiceImpl implements TaskManagementService { } // Update task in the ntask core - String taskId = TaskManagementUtil.generateTaskId(existingTask.getDynamicTaskId()); - if (isTaskExists(taskId)) { + String taskName = TaskManagementUtil.generateNTaskName(existingTask.getDynamicTaskId()); + if (isTaskExists(taskName)) { if (isEnabled) { - taskManager.resumeTask(taskId); + taskManager.resumeTask(taskName); } else { - taskManager.pauseTask(taskId); + taskManager.pauseTask(taskName); } } else { - String msg = "Task '" + taskId + "' is not exists in the ntask core " + String msg = "Task '" + taskName + "' is not exists in the ntask core " + "Hence cannot toggle the task in the ntask."; log.error(msg); } @@ -251,22 +260,23 @@ public class TaskManagementServiceImpl implements TaskManagementService { @Override public void deleteTask(int dynamicTaskId) throws TaskManagementException, TaskNotFoundException { // delete task from dynamic task table + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { TaskManagementDAOFactory.beginTransaction(); - DynamicTask existingTask = dynamicTaskDAO.getDynamicTaskById(dynamicTaskId); + DynamicTask existingTask = dynamicTaskDAO.getDynamicTask(dynamicTaskId, tenantId); if (existingTask != null) { - dynamicTaskDAO.deleteDynamicTask(dynamicTaskId); + dynamicTaskDAO.deleteDynamicTask(dynamicTaskId, tenantId); } else { String msg = "Task '" + dynamicTaskId + "' is not exists."; log.error(msg); throw new TaskNotFoundException(msg); } - String taskId = TaskManagementUtil.generateTaskId(existingTask.getDynamicTaskId()); - if (isTaskExists(taskId)) { - taskManager.deleteTask(taskId); + String taskName = TaskManagementUtil.generateNTaskName(existingTask.getDynamicTaskId()); + if (isTaskExists(taskName)) { + taskManager.deleteTask(taskName); } else { - String msg = "Task '" + taskId + "' is not exists in the ntask core " + String msg = "Task '" + taskName + "' is not exists in the ntask core " + "Hence cannot delete from the ntask core."; log.error(msg); } @@ -292,22 +302,21 @@ public class TaskManagementServiceImpl implements TaskManagementService { @Override public List getAllDynamicTasks() throws TaskManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); List dynamicTasks; try { - if (log.isDebugEnabled()) { - log.debug("Fetching the details of all dynamic tasks"); + if (log.isTraceEnabled()) { + log.trace("Fetching the details of all dynamic tasks"); } - TaskManagementDAOFactory.beginTransaction(); - dynamicTasks = dynamicTaskDAO.getAllDynamicTasks(); + TaskManagementDAOFactory.openConnection(); + dynamicTasks = dynamicTaskDAO.getAllDynamicTasks(tenantId); if (dynamicTasks != null) { for (DynamicTask dynamicTask : dynamicTasks) { dynamicTask.setProperties(dynamicTaskPropDAO - .getDynamicTaskProps(dynamicTask.getDynamicTaskId())); + .getDynamicTaskProps(dynamicTask.getDynamicTaskId(), tenantId)); } } - TaskManagementDAOFactory.commitTransaction(); } catch (TaskManagementDAOException e) { - TaskManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while fetching all dynamic tasks"; log.error(msg, e); throw new TaskManagementException(msg, e); @@ -322,20 +331,62 @@ public class TaskManagementServiceImpl implements TaskManagementService { } @Override - public DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementException { + public Map> getDynamicTasksForAllTenants() throws TaskManagementException { + List dynamicTasks; + try { + if (log.isTraceEnabled()) { + log.trace("Fetching the details of dynamic tasks for all tenants"); + } + TaskManagementDAOFactory.openConnection(); + dynamicTasks = dynamicTaskDAO.getAllDynamicTasks(); + if (dynamicTasks != null) { + for (DynamicTask dynamicTask : dynamicTasks) { + dynamicTask.setProperties(dynamicTaskPropDAO + .getDynamicTaskProps(dynamicTask.getDynamicTaskId(), dynamicTask.getTenantId())); + } + } + } catch (TaskManagementDAOException e) { + String msg = "Error occurred while fetching all dynamic tasks"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Failed to start/open transaction to get all dynamic tasks"; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } finally { + TaskManagementDAOFactory.closeConnection(); + } + Map> tenantedDynamicTasks = new HashMap<>(); + List dts; + if (dynamicTasks != null) { + for (DynamicTask dt : dynamicTasks) { + if (tenantedDynamicTasks.containsKey(dt.getTenantId())) { + dts = tenantedDynamicTasks.get(dt.getTenantId()); + } else { + dts = new ArrayList<>(); + } + dts.add(dt); + tenantedDynamicTasks.put(dt.getTenantId(), dts); + } + } + return tenantedDynamicTasks; + } + + @Override + public DynamicTask getDynamicTask(int dynamicTaskId) throws TaskManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); DynamicTask dynamicTask; try { if (log.isDebugEnabled()) { log.debug("Fetching the details of dynamic task '" + dynamicTaskId + "'"); } - TaskManagementDAOFactory.beginTransaction(); - dynamicTask = dynamicTaskDAO.getDynamicTaskById(dynamicTaskId); + TaskManagementDAOFactory.openConnection(); + dynamicTask = dynamicTaskDAO.getDynamicTask(dynamicTaskId, tenantId); if (dynamicTask != null) { - dynamicTask.setProperties(dynamicTaskPropDAO.getDynamicTaskProps(dynamicTask.getDynamicTaskId())); + dynamicTask.setProperties(dynamicTaskPropDAO.getDynamicTaskProps(dynamicTask.getDynamicTaskId(), + tenantId)); } - TaskManagementDAOFactory.commitTransaction(); } catch (TaskManagementDAOException e) { - TaskManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while fetching dynamic task '" + dynamicTaskId + "'"; log.error(msg, e); throw new TaskManagementException(msg, e); @@ -351,21 +402,21 @@ public class TaskManagementServiceImpl implements TaskManagementService { @Override public List getActiveDynamicTasks() throws TaskManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); List dynamicTasks; try { if (log.isDebugEnabled()) { log.debug("Fetching the details of all active dynamic tasks"); } - TaskManagementDAOFactory.beginTransaction(); - dynamicTasks = dynamicTaskDAO.getActiveDynamicTasks(); + TaskManagementDAOFactory.openConnection(); + dynamicTasks = dynamicTaskDAO.getActiveDynamicTasks(tenantId); if (dynamicTasks != null) { for (DynamicTask dynamicTask : dynamicTasks) { - dynamicTask.setProperties(dynamicTaskPropDAO.getDynamicTaskProps(dynamicTask.getDynamicTaskId())); + dynamicTask.setProperties(dynamicTaskPropDAO.getDynamicTaskProps(dynamicTask.getDynamicTaskId(), + tenantId)); } } - TaskManagementDAOFactory.commitTransaction(); } catch (TaskManagementDAOException e) { - TaskManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while fetching all active dynamic tasks"; log.error(msg, e); throw new TaskManagementException(msg, e); @@ -380,18 +431,19 @@ public class TaskManagementServiceImpl implements TaskManagementService { } // check whether task exist in the ntask core - private boolean isTaskExists(String taskId) throws TaskManagementException, TaskException { - if (StringUtils.isEmpty(taskId)) { - String msg = "Task ID must not be null or empty."; + private boolean isTaskExists(String taskName) throws TaskManagementException, TaskException { + if (StringUtils.isEmpty(taskName)) { + String msg = "Task Name must not be null or empty."; log.error(msg); throw new TaskManagementException(msg); } List tasks = taskManager.getAllTasks(); for (TaskInfo t : tasks) { - if (taskId.equals(t.getName())) { + if (taskName.equals(t.getName())) { return true; } } return false; } + } diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/util/TaskManagementUtil.java b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/util/TaskManagementUtil.java index c060451a6b..2a284f3021 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/util/TaskManagementUtil.java +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/src/main/java/io/entgra/device/mgt/core/task/mgt/core/util/TaskManagementUtil.java @@ -17,20 +17,21 @@ */ package io.entgra.device.mgt.core.task.mgt.core.util; -import com.google.gson.Gson; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.device.mgt.core.task.mgt.common.bean.DynamicTask; import io.entgra.device.mgt.core.task.mgt.common.constant.TaskMgtConstants; import io.entgra.device.mgt.core.task.mgt.common.exception.TaskManagementException; import io.entgra.device.mgt.core.task.mgt.core.internal.TaskManagerDataHolder; -import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; +import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; +import java.util.HashMap; import java.util.Map; /** @@ -55,11 +56,11 @@ public class TaskManagementUtil { } } - public static String generateTaskId(int dynamicTaskId) throws TaskManagementException { + public static String generateNTaskName(int dynamicTaskId) throws TaskManagementException { try { int serverHashIdx = TaskManagerDataHolder.getInstance().getHeartBeatService() .getServerCtxInfo().getLocalServerHashIdx(); - return generateTaskId(dynamicTaskId, serverHashIdx); + return generateNTaskName(dynamicTaskId, serverHashIdx); } catch (HeartBeatManagementException e) { String msg = "Failed to generate task id for a dynamic task " + dynamicTaskId; log.error(msg, e); @@ -67,18 +68,33 @@ public class TaskManagementUtil { } } - public static String generateTaskId(int dynamicTaskId, int serverHashIdx) { + public static String generateNTaskName(int dynamicTaskId, int serverHashIdx) { return TaskMgtConstants.Task.DYNAMIC_TASK_TYPE + TaskMgtConstants.Task.NAME_SEPARATOR + dynamicTaskId + TaskMgtConstants.Task.NAME_SEPARATOR + serverHashIdx; } - public static String generateTaskPropsMD5(Map taskProperties) { - taskProperties.remove(TaskMgtConstants.Task.TENANT_ID_PROP); - taskProperties.remove(TaskMgtConstants.Task.LOCAL_HASH_INDEX); - taskProperties.remove(TaskMgtConstants.Task.LOCAL_TASK_NAME); - Gson gson = new Gson(); - String json = gson.toJson(taskProperties); - return DigestUtils.md5Hex(json); + public static Map populateNTaskProperties(DynamicTask dynamicTask, + String nTaskName) throws TaskManagementException { + try { + int serverHashIdx = TaskManagerDataHolder.getInstance().getHeartBeatService() + .getServerCtxInfo().getLocalServerHashIdx(); + return populateNTaskProperties(dynamicTask, nTaskName, serverHashIdx); + } catch (HeartBeatManagementException e) { + String msg = "Failed to populate nTask properties a dynamic task " + dynamicTask.getDynamicTaskId(); + log.error(msg, e); + throw new TaskManagementException(msg, e); + } + } + + public static Map populateNTaskProperties(DynamicTask dynamicTask, + String nTaskName, int serverHashIdx) { + Map taskProperties = new HashMap<>(); + taskProperties.put(TaskMgtConstants.Task.DYNAMIC_TASK_ID, String.valueOf(dynamicTask.getDynamicTaskId())); + taskProperties.put(TaskMgtConstants.Task.LOCAL_TASK_NAME, nTaskName); + taskProperties.put(TaskMgtConstants.Task.LOCAL_HASH_INDEX, String.valueOf(serverHashIdx)); + taskProperties.put(TaskMgtConstants.Task.TENANT_ID_PROP, + String.valueOf(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId())); + return taskProperties; } } diff --git a/components/task-mgt/task-manager/pom.xml b/components/task-mgt/task-manager/pom.xml index a42c74abee..6904bc1898 100755 --- a/components/task-mgt/task-manager/pom.xml +++ b/components/task-mgt/task-manager/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml index 68133c5ebb..9b3679a880 100755 --- a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml +++ b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-watcher - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/src/main/java/io/entgra/device/mgt/core/task/mgt/watcher/IoTSStartupHandler.java b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/src/main/java/io/entgra/device/mgt/core/task/mgt/watcher/IoTSStartupHandler.java index 8d51a240cc..5b1945e686 100755 --- a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/src/main/java/io/entgra/device/mgt/core/task/mgt/watcher/IoTSStartupHandler.java +++ b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/src/main/java/io/entgra/device/mgt/core/task/mgt/watcher/IoTSStartupHandler.java @@ -38,7 +38,6 @@ import org.wso2.carbon.user.core.service.RealmService; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -69,47 +68,38 @@ public class IoTSStartupHandler implements ServerStartupObserver { private void compareTasks() { if (log.isDebugEnabled()) { - log.debug("Comparing Tasks from carbon nTask manager and entgra task manager"); + log.debug("Comparing Tasks from carbon nTask manager and Entgra task manager."); } TaskService nTaskService = TaskWatcherDataHolder.getInstance().getnTaskService(); if (nTaskService == null) { - String msg = "Unable to load TaskService from the carbon nTask core"; + String msg = "Unable to load TaskService from the carbon nTask core."; log.error(msg); return; } try { - List dynamicTasks = TaskWatcherDataHolder.getInstance().getTaskManagementService() - .getAllDynamicTasks(); + Map> tenantedDynamicTasks = TaskWatcherDataHolder.getInstance() + .getTaskManagementService().getDynamicTasksForAllTenants(); - scheduleMissingTasks(nTaskService, dynamicTasks); - deleteObsoleteTasks(nTaskService, dynamicTasks); + scheduleMissingTasks(nTaskService, tenantedDynamicTasks); + deleteObsoleteTasks(nTaskService, tenantedDynamicTasks); if (log.isDebugEnabled()) { - log.debug("Task Comparison Completed and all tasks in current node are updated"); + log.debug("Task Comparison Completed and all tasks in current node are updated."); } } catch (TaskException e) { String msg = "Error occurred while accessing carbon nTask manager."; log.error(msg, e); } catch (TaskManagementException e) { - String msg = "Error occurred while retrieving all active tasks from entgra task manager"; + String msg = "Error occurred while retrieving all active tasks from Entgra task manager."; log.error(msg, e); } } - private static void scheduleMissingTasks(TaskService nTaskService, List dynamicTasks) + private static void scheduleMissingTasks(TaskService nTaskService, Map> tenantedDynamicTasks) throws TaskException, TaskManagementException { - Map> tenantedDynamicTasks = new HashMap<>(); - List dts; - for (DynamicTask dt : dynamicTasks) { - if (tenantedDynamicTasks.containsKey(dt.getTenantId())) { - dts = tenantedDynamicTasks.get(dt.getTenantId()); - } else { - dts = new ArrayList<>(); - } - dts.add(dt); - tenantedDynamicTasks.put(dt.getTenantId(), dts); - } + TaskManager taskManager; for (Integer tenantId : tenantedDynamicTasks.keySet()) { if (tenantId == -1) { @@ -126,36 +116,56 @@ public class IoTSStartupHandler implements ServerStartupObserver { List tasks = taskManager.getAllTasks(); // add or update task into nTask core for (DynamicTask dt : tenantedDynamicTasks.get(tenantId)) { - String generatedTaskId = TaskManagementUtil.generateTaskId(dt.getDynamicTaskId()); + int serverHashIdx; + try { + serverHashIdx = TaskWatcherDataHolder.getInstance().getHeartBeatService() + .getServerCtxInfo().getLocalServerHashIdx(); + } catch (HeartBeatManagementException e) { + String msg = "Failed to get server hash index for dynamic task " + dt.getDynamicTaskId(); + log.error(msg, e); + throw new TaskManagementException(msg, e); + } + + String nTaskName = TaskManagementUtil.generateNTaskName(dt.getDynamicTaskId(), serverHashIdx); boolean isExist = false; for (TaskInfo taskInfo : tasks) { - if (taskInfo.getName().equals(generatedTaskId)) { - isExist = true; + if (taskInfo.getName().equals(nTaskName)) { + TaskInfo.TriggerInfo triggerInfo = taskInfo.getTriggerInfo(); - String dynamicTaskPropMD5 = TaskManagementUtil.generateTaskPropsMD5(dt.getProperties()); - String existingTaskPropMD5 = TaskManagementUtil.generateTaskPropsMD5(taskInfo.getProperties()); - if (!triggerInfo.getCronExpression().equals(dt.getCronExpression()) - || !dynamicTaskPropMD5.equals(existingTaskPropMD5)) { + if (taskInfo.getProperties() == null) { + String msg = "Task properties not found for task " + nTaskName + + ". Therefore deleting the nTask schedule."; + log.warn(msg); + taskManager.deleteTask(nTaskName); + break; + } + + isExist = true; + if (!triggerInfo.getCronExpression().equals(dt.getCronExpression())) { triggerInfo.setCronExpression(dt.getCronExpression()); taskInfo.setTriggerInfo(triggerInfo); - taskInfo.setProperties(populateTaskProperties(tenantId, generatedTaskId, dt.getProperties())); + taskInfo.setProperties(TaskManagementUtil + .populateNTaskProperties(dt, taskInfo.getName(), serverHashIdx)); taskManager.registerTask(taskInfo); - taskManager.rescheduleTask(generatedTaskId); + taskManager.rescheduleTask(nTaskName); if (log.isDebugEnabled()) { - log.debug("Task - '" + generatedTaskId + "' updated according to the dynamic task table"); + log.debug("Task - '" + nTaskName + + "' updated according to the dynamic task table."); } } if (dt.isEnabled() - && taskManager.getTaskState(generatedTaskId) == TaskManager.TaskState.PAUSED) { - taskManager.resumeTask(generatedTaskId); + && taskManager.getTaskState(nTaskName) == TaskManager.TaskState.PAUSED) { + taskManager.resumeTask(nTaskName); if (log.isDebugEnabled()) { - log.debug("Task - '" + generatedTaskId + "' enabled according to the dynamic task table"); + log.debug("Task - '" + nTaskName + + "' enabled according to the dynamic task table."); } } else if (!dt.isEnabled() - && taskManager.getTaskState(generatedTaskId) != TaskManager.TaskState.PAUSED) { - taskManager.pauseTask(generatedTaskId); + && taskManager.getTaskState(nTaskName) != TaskManager.TaskState.PAUSED) { + taskManager.pauseTask(nTaskName); if (log.isDebugEnabled()) { - log.debug("Task - '" + generatedTaskId + "' disabled according to the dynamic task table"); + log.debug("Task - '" + nTaskName + + "' disabled according to the dynamic task table."); } } break; @@ -164,12 +174,12 @@ public class IoTSStartupHandler implements ServerStartupObserver { if (!isExist) { TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); triggerInfo.setCronExpression(dt.getCronExpression()); - TaskInfo taskInfo = new TaskInfo(generatedTaskId, dt.getTaskClassName(), - populateTaskProperties(tenantId, generatedTaskId, dt.getProperties()), triggerInfo); + TaskInfo taskInfo = new TaskInfo(nTaskName, dt.getTaskClassName(), TaskManagementUtil + .populateNTaskProperties(dt, nTaskName, serverHashIdx), triggerInfo); taskManager.registerTask(taskInfo); - taskManager.scheduleTask(generatedTaskId); + taskManager.scheduleTask(nTaskName); if (log.isDebugEnabled()) { - log.debug("New task -'" + generatedTaskId + "' created according to the dynamic task table"); + log.debug("New task -'" + nTaskName + "' created according to the dynamic task table."); } } } @@ -177,24 +187,8 @@ public class IoTSStartupHandler implements ServerStartupObserver { } } - private static Map populateTaskProperties(int tenantId, String generatedTaskId, - Map taskProperties) - throws TaskManagementException { - try { - int serverHashIdx = TaskWatcherDataHolder.getInstance().getHeartBeatService() - .getServerCtxInfo().getLocalServerHashIdx(); - taskProperties.put(TaskMgtConstants.Task.LOCAL_HASH_INDEX, String.valueOf(serverHashIdx)); - taskProperties.put(TaskMgtConstants.Task.LOCAL_TASK_NAME, generatedTaskId); - taskProperties.put(TaskMgtConstants.Task.TENANT_ID_PROP, String.valueOf(tenantId)); - return taskProperties; - } catch (HeartBeatManagementException e) { - String msg = "Unexpected exception when getting server hash index."; - log.error(msg, e); - throw new TaskManagementException(msg, e); - } - } - - private static void deleteObsoleteTasks(TaskService nTaskService, List dynamicTasks) + private static void deleteObsoleteTasks(TaskService nTaskService, + Map> tenantedDynamicTasks) throws TaskManagementException, TaskException { List tenants = new ArrayList<>(); @@ -224,6 +218,13 @@ public class IoTSStartupHandler implements ServerStartupObserver { } for (Tenant tenant : tenants) { + if (tenantedDynamicTasks.get(tenant.getId()) == null) { + if (log.isTraceEnabled()) { + log.trace("Dynamic tasks not running for tenant: [" + tenant.getId() + "] " + + tenant.getDomain()); + } + continue; + } PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenant.getId(), true); if (!nTaskService.getRegisteredTaskTypes().contains(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE)) { @@ -234,10 +235,10 @@ public class IoTSStartupHandler implements ServerStartupObserver { // Remove deleted items from the nTask core for (TaskInfo taskInfo : tasks) { boolean isExist = false; - for (DynamicTask dt : dynamicTasks) { + for (DynamicTask dt : tenantedDynamicTasks.get(tenant.getId())) { for (int hid : hashIds) { if (tenant.getId() == dt.getTenantId() && - taskInfo.getName().equals(TaskManagementUtil.generateTaskId(dt.getDynamicTaskId(), hid))) { + taskInfo.getName().equals(TaskManagementUtil.generateNTaskName(dt.getDynamicTaskId(), hid))) { isExist = true; break; } diff --git a/components/task-mgt/task-watcher/pom.xml b/components/task-mgt/task-watcher/pom.xml index 963641ebe5..9fe0b11e7c 100755 --- a/components/task-mgt/task-watcher/pom.xml +++ b/components/task-mgt/task-watcher/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml index 47e3cd2196..2dd5078116 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml @@ -20,7 +20,7 @@ tenant-mgt io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/src/main/java/io/entgra/device/mgt/core/tenant/mgt/common/spi/TenantManagerService.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/src/main/java/io/entgra/device/mgt/core/tenant/mgt/common/spi/TenantManagerService.java index a43f20f24c..cbc67114ee 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/src/main/java/io/entgra/device/mgt/core/tenant/mgt/common/spi/TenantManagerService.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/src/main/java/io/entgra/device/mgt/core/tenant/mgt/common/spi/TenantManagerService.java @@ -26,4 +26,6 @@ public interface TenantManagerService { void addDefaultAppCategories(TenantInfoBean tenantInfoBean) throws TenantMgtException; void addDefaultDeviceStatusFilters(TenantInfoBean tenantInfoBean) throws TenantMgtException; + void deleteTenantApplicationData(int tenantId) throws TenantMgtException; + void deleteTenantDeviceData(int tenantId) throws TenantMgtException; } \ No newline at end of file diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml index 5e61b38445..7eafae8b99 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml @@ -20,7 +20,7 @@ tenant-mgt io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml @@ -66,6 +66,7 @@ io.entgra.device.mgt.core.device.mgt.common.roles.config, io.entgra.device.mgt.core.device.mgt.core.metadata.mgt, io.entgra.device.mgt.core.device.mgt.core.config, + io.entgra.device.mgt.core.device.mgt.core.dao.*, org.wso2.carbon.user.core.service, org.wso2.carbon.context diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/TenantManager.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/TenantManager.java index 97eb706be7..ac3ee406f9 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/TenantManager.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/TenantManager.java @@ -43,4 +43,18 @@ public interface TenantManager { * @throws TenantMgtException Throws when error occurred while adding default application categories */ void addDefaultDeviceStatusFilters(TenantInfoBean tenantInfoBean) throws TenantMgtException; + + /** + * Delete Application related details of a tenant + * @param tenantId ID of the tenant + * @throws TenantMgtException Throws when deleting Tenant related application data + */ + void deleteTenantApplicationData(int tenantId) throws TenantMgtException; + + /** + * Delete Device related details of a tenant + * @param tenantId ID of the tenant + * @throws TenantMgtException Throws when deleting Tenant related device data + */ + void deleteTenantDeviceData(int tenantId) throws TenantMgtException; } diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerImpl.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerImpl.java index 5dc2eb7f08..00cdc801be 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerImpl.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerImpl.java @@ -20,6 +20,10 @@ package io.entgra.device.mgt.core.tenant.mgt.core.impl; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.core.config.ConfigurationManager; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory; +import io.entgra.device.mgt.core.device.mgt.core.dao.TenantDAO; import io.entgra.device.mgt.core.tenant.mgt.core.TenantManager; import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException; import io.entgra.device.mgt.core.tenant.mgt.core.internal.TenantMgtDataHolder; @@ -38,6 +42,7 @@ import io.entgra.device.mgt.core.device.mgt.common.roles.config.Role; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -46,6 +51,11 @@ import java.util.Map; public class TenantManagerImpl implements TenantManager { private static final Log log = LogFactory.getLog(TenantManagerImpl.class); private static final String PERMISSION_ACTION = "ui.execute"; + TenantDAO tenantDao; + + public TenantManagerImpl() { + this.tenantDao = DeviceManagementDAOFactory.getTenantDAO(); + } @Override public void addDefaultRoles(TenantInfoBean tenantInfoBean) throws TenantMgtException { @@ -113,6 +123,100 @@ public class TenantManagerImpl implements TenantManager { } } + @Override + public void deleteTenantApplicationData(int tenantId) throws TenantMgtException { + try { + TenantMgtDataHolder.getInstance().getApplicationManager(). + deleteApplicationDataOfTenant(tenantId); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while deleting Application related data of Tenant of " + + "tenant Id" + tenantId; + log.error(msg, e); + throw new TenantMgtException(msg, e); + } + } + + @Override + public void deleteTenantDeviceData(int tenantId) throws TenantMgtException { + if (log.isDebugEnabled()) { + log.debug("Request is received to delete Device related data of tenant with ID: " + tenantId); + } + try { + DeviceManagementDAOFactory.beginTransaction(); + + tenantDao.deleteExternalPermissionMapping(tenantId); + tenantDao.deleteExternalDeviceMappingByTenantId(tenantId); + tenantDao.deleteExternalGroupMappingByTenantId(tenantId); + // TODO: Check whether deleting DM_DEVICE_ORGANIZATION table data is necessary +// tenantDao.deleteDeviceOrganizationByTenantId(tenantId); + tenantDao.deleteDeviceHistoryLastSevenDaysByTenantId(tenantId); + tenantDao.deleteDeviceDetailByTenantId(tenantId); + tenantDao.deleteDeviceLocationByTenantId(tenantId); + tenantDao.deleteDeviceInfoByTenantId(tenantId); + tenantDao.deleteNotificationByTenantId(tenantId); + tenantDao.deleteAppIconsByTenantId(tenantId); + tenantDao.deleteTraccarUnsyncedDevicesByTenantId(tenantId); + tenantDao.deleteDeviceEventGroupMappingByTenantId(tenantId); + tenantDao.deleteGeofenceEventMappingByTenantId(tenantId); + tenantDao.deleteDeviceEventByTenantId(tenantId); + tenantDao.deleteGeofenceGroupMappingByTenantId(tenantId); + tenantDao.deleteGeofenceByTenantId(tenantId); + tenantDao.deleteDeviceGroupPolicyByTenantId(tenantId); + tenantDao.deleteDynamicTaskPropertiesByTenantId(tenantId); + tenantDao.deleteDynamicTaskByTenantId(tenantId); + tenantDao.deleteMetadataByTenantId(tenantId); + tenantDao.deleteOTPDataByTenantId(tenantId); + tenantDao.deleteSubOperationTemplate(tenantId); + tenantDao.deleteDeviceSubTypeByTenantId(tenantId); + tenantDao.deleteCEAPoliciesByTenantId(tenantId); + + tenantDao.deleteApplicationByTenantId(tenantId); + tenantDao.deletePolicyCriteriaPropertiesByTenantId(tenantId); + tenantDao.deletePolicyCriteriaByTenantId(tenantId); + tenantDao.deleteCriteriaByTenantId(tenantId); + tenantDao.deletePolicyChangeManagementByTenantId(tenantId); + tenantDao.deletePolicyComplianceFeaturesByTenantId(tenantId); + tenantDao.deletePolicyComplianceStatusByTenantId(tenantId); + tenantDao.deleteRolePolicyByTenantId(tenantId); + tenantDao.deleteUserPolicyByTenantId(tenantId); + tenantDao.deleteDeviceTypePolicyByTenantId(tenantId); + tenantDao.deleteDevicePolicyAppliedByTenantId(tenantId); + tenantDao.deleteDevicePolicyByTenantId(tenantId); + tenantDao.deletePolicyCorrectiveActionByTenantId(tenantId); + tenantDao.deletePolicyByTenantId(tenantId); + tenantDao.deleteProfileFeaturesByTenantId(tenantId); + tenantDao.deleteProfileByTenantId(tenantId); + + tenantDao.deleteDeviceOperationResponseLargeByTenantId(tenantId); + tenantDao.deleteDeviceOperationResponseByTenantId(tenantId); + tenantDao.deleteEnrolmentOpMappingByTenantId(tenantId); + tenantDao.deleteDeviceStatusByTenantId(tenantId); + tenantDao.deleteEnrolmentByTenantId(tenantId); + tenantDao.deleteOperationByTenantId(tenantId); + tenantDao.deleteDeviceGroupMapByTenantId(tenantId); + tenantDao.deleteGroupPropertiesByTenantId(tenantId); + tenantDao.deleteDevicePropertiesByTenantId(tenantId); + tenantDao.deleteDeviceByTenantId(tenantId); + tenantDao.deleteRoleGroupMapByTenantId(tenantId); + tenantDao.deleteGroupByTenantId(tenantId); + tenantDao.deleteDeviceCertificateByTenantId(tenantId); + + DeviceManagementDAOFactory.commitTransaction(); + } catch (DeviceManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error deleting data of tenant of ID: '" + tenantId + "'"; + log.error(msg); + throw new TenantMgtException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error initializing transaction when trying to delete tenant info of '" + tenantId + "'"; + log.error(msg); + throw new TenantMgtException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + } + private void initTenantFlow(TenantInfoBean tenantInfoBean) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerServiceImpl.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerServiceImpl.java index da21a52100..bc82bef3db 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerServiceImpl.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerServiceImpl.java @@ -38,4 +38,14 @@ public class TenantManagerServiceImpl implements TenantManagerService { public void addDefaultDeviceStatusFilters(TenantInfoBean tenantInfoBean) throws TenantMgtException { TenantMgtDataHolder.getInstance().getTenantManager().addDefaultDeviceStatusFilters(tenantInfoBean); } + + @Override + public void deleteTenantApplicationData(int tenantId) throws TenantMgtException { + TenantMgtDataHolder.getInstance().getTenantManager().deleteTenantApplicationData(tenantId); + } + + @Override + public void deleteTenantDeviceData(int tenantId) throws TenantMgtException { + TenantMgtDataHolder.getInstance().getTenantManager().deleteTenantDeviceData(tenantId); + } } diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java index 978e69b0e4..257206f84f 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java @@ -88,5 +88,13 @@ public class DeviceMgtTenantListener implements TenantMgtListener { @Override public void onPreDelete(int i) throws StratosException { // Any work to be performed before a tenant is deleted + TenantManager tenantManager = TenantMgtDataHolder.getInstance().getTenantManager(); + try{ + tenantManager.deleteTenantDeviceData(i); + tenantManager.deleteTenantApplicationData(i); + } catch (TenantMgtException e) { + String msg = "Error occurred while deleting tenant data"; + log.error(msg, e); + } } } diff --git a/components/tenant-mgt/pom.xml b/components/tenant-mgt/pom.xml index 73e3006b3a..b4e13f6292 100644 --- a/components/tenant-mgt/pom.xml +++ b/components/tenant-mgt/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml index 190f753a8e..7e2afe4f69 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core email-sender - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/email-sender/pom.xml b/components/transport-mgt/email-sender/pom.xml index ef75c2af72..1b663db64e 100644 --- a/components/transport-mgt/email-sender/pom.xml +++ b/components/transport-mgt/email-sender/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/pom.xml b/components/transport-mgt/pom.xml index e27928bcad..e28aeb6f30 100644 --- a/components/transport-mgt/pom.xml +++ b/components/transport-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml index 0c1d62761f..c911c571a4 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml index 628eb8962b..eec782a9aa 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml index 92b18dac5e..740d1b7ae5 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/pom.xml b/components/transport-mgt/sms-handler/pom.xml index 3bdfdf8d07..63db59b599 100644 --- a/components/transport-mgt/sms-handler/pom.xml +++ b/components/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml index 92d03faa63..83f664e143 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml @@ -21,7 +21,7 @@ ui-request-interceptor io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT 4.0.0 diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java index 343a9c620d..dac8f541ee 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java @@ -22,6 +22,8 @@ import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; +import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; @@ -31,9 +33,11 @@ import org.apache.commons.logging.LogFactory; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import org.apache.http.entity.StringEntity; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -42,85 +46,53 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Base64; @MultipartConfig @WebServlet("/default-oauth2-credentials") public class DefaultOauth2TokenHandler extends HttpServlet { private static final Log log = LogFactory.getLog(DefaultTokenHandler.class); - @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { HttpSession httpSession = req.getSession(false); - if (httpSession != null) { AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); if (authData == null) { HandlerUtil.sendUnAuthorizeResponse(resp); return; } - AuthData defaultAuthData = (AuthData) httpSession .getAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY); if (defaultAuthData != null) { - HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultAuthData.getAccessToken())); - return; - } - - String clientId = authData.getClientId(); - String clientSecret = authData.getClientSecret(); - - String queryString = req.getQueryString(); - String scopeString = ""; - if (StringUtils.isNotEmpty(queryString)) { - scopeString = req.getParameter("scopes"); - if (scopeString != null) { - scopeString = "?scopes=" + scopeString; + String accessToken = defaultAuthData.getAccessToken(); + String accessTokenWithoutPrefix = accessToken.substring(accessToken.indexOf("_") + 1); + + HttpPost tokenEndpoint = new HttpPost(HandlerUtil.getKeyManagerUrl(req.getScheme()) + HandlerConstants.INTROSPECT_ENDPOINT); + tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); + DeviceManagementConfig dmc = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + String adminUsername = dmc.getKeyManagerConfigurations().getAdminUsername(); + String adminPassword = dmc.getKeyManagerConfigurations().getAdminPassword(); + tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() + .encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes())); + StringEntity tokenEPPayload = new StringEntity("token=" + accessTokenWithoutPrefix, + ContentType.APPLICATION_FORM_URLENCODED); + tokenEndpoint.setEntity(tokenEPPayload); + ProxyResponse tokenStatus = HandlerUtil.execute(tokenEndpoint); + + if (HandlerConstants.DEFAULT_TOKEN_IS_EXPIRED.equals(tokenStatus.getData())) { + tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, tokenEndpoint, HandlerUtil.getKeyManagerUrl(req.getScheme()), true); + if (!HandlerUtil.isResponseSuccessful(tokenStatus)) { + HandlerUtil.handleError(resp, tokenStatus); + return; + } + } else { + HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultAuthData.getAccessToken())); + return; } } - - String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR - + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - String tokenUrl = iotsCoreUrl + "/api/device-mgt/v1.0/devices/" + clientId - + "/" + clientSecret + "/default-token" + scopeString; - - HttpGet defaultTokenRequest = new HttpGet(tokenUrl); - defaultTokenRequest - .setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - defaultTokenRequest - .setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest); - - if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { - log.error("Error occurred while invoking the API to get default token data."); - HandlerUtil.handleError(resp, tokenResultResponse); - return; - } - String tokenResult = tokenResultResponse.getData(); - if (tokenResult == null) { - log.error("Invalid default token response is received."); - HandlerUtil.handleError(resp, tokenResultResponse); - return; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResult); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - AuthData newDefaultAuthData = new AuthData(); - newDefaultAuthData.setClientId(clientId); - newDefaultAuthData.setClientSecret(clientSecret); - - String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString(); - newDefaultAuthData.setAccessToken(defaultToken); - newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString()); - newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString()); - httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData); - - HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken)); - } + processDefaultTokenRequest(httpSession, authData, req, resp); } else { HandlerUtil.sendUnAuthorizeResponse(resp); } @@ -129,6 +101,62 @@ public class DefaultOauth2TokenHandler extends HttpServlet { } } + private void processDefaultTokenRequest(HttpSession httpSession, AuthData authData, HttpServletRequest req, HttpServletResponse resp) throws IOException { + String clientId = authData.getClientId(); + String clientSecret = authData.getClientSecret(); + + String queryString = req.getQueryString(); + String scopeString = ""; + if (StringUtils.isNotEmpty(queryString)) { + scopeString = req.getParameter("scopes"); + if (scopeString != null) { + scopeString = "?scopes=" + scopeString; + } + } + + String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); + String tokenUrl = iotsCoreUrl + "/api/device-mgt/v1.0/devices/" + clientId + + "/" + clientSecret + "/default-token" + scopeString; + + HttpGet defaultTokenRequest = new HttpGet(tokenUrl); + defaultTokenRequest + .setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); + defaultTokenRequest + .setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); + ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest); + + if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { + log.error("Error occurred while invoking the API to get default token data."); + HandlerUtil.handleError(resp, tokenResultResponse); + return; + } + String tokenResult = tokenResultResponse.getData(); + if (tokenResult == null) { + log.error("Invalid default token response is received."); + HandlerUtil.handleError(resp, tokenResultResponse); + return; + } + + JsonParser jsonParser = new JsonParser(); + JsonElement jTokenResult = jsonParser.parse(tokenResult); + if (jTokenResult.isJsonObject()) { + JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); + AuthData newDefaultAuthData = new AuthData(); + newDefaultAuthData.setClientId(clientId); + newDefaultAuthData.setClientSecret(clientSecret); + + String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString(); + newDefaultAuthData.setAccessToken(defaultToken); + newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString()); + newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString()); + httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData); + + HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken)); + } + } + /** * Get Success Proxy Response * @param defaultAccessToken Access token which has default scope diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java index 44aedaafe5..d38b9942d3 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java @@ -52,6 +52,7 @@ public class HandlerConstants { public static final String API_COMMON_CONTEXT = "/api"; public static final String EXECUTOR_EXCEPTION_PREFIX = "ExecutorException-"; public static final String TOKEN_IS_EXPIRED = "ACCESS_TOKEN_IS_EXPIRED"; + public static final String DEFAULT_TOKEN_IS_EXPIRED = "{\"active\":false}"; public static final String REPORTS = "Reports"; public static final String APP_NAME = "App-Name"; public static final String[] SSO_LOGOUT_COOKIE_PATHS = new String[]{"/", "/entgra-ui-request-handler", diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java index 0fca3811c0..0d991c8693 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java @@ -73,6 +73,7 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.math.BigInteger; import java.security.SecureRandom; +import java.util.Base64; import java.util.Enumeration; import java.util.List; @@ -613,26 +614,32 @@ public class HandlerUtil { * @throws IOException If an error occurs when try to retry the request. */ public static ProxyResponse retryRequestWithRefreshedToken(HttpServletRequest req, HttpRequestBase httpRequest, - String apiEndpoint) throws IOException { - ProxyResponse retryResponse = refreshToken(req, apiEndpoint); + String apiEndpoint, boolean isDefaultAuthToken) throws IOException { + ProxyResponse retryResponse = refreshToken(req, apiEndpoint, isDefaultAuthToken); if (isResponseSuccessful(retryResponse)) { HttpSession session = req.getSession(false); if (session == null) { log.error("Unauthorized, You are not logged in. Please log in to the portal"); return constructProxyResponseByErrorCode(HttpStatus.SC_UNAUTHORIZED); } - httpRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - ProxyResponse proxyResponse = HandlerUtil.execute(httpRequest); - if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { - log.error("Error occurred while invoking the API after refreshing the token."); + if (!isDefaultAuthToken) { + httpRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); + ProxyResponse proxyResponse = HandlerUtil.execute(httpRequest); + if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { + log.error("Error occurred while invoking the API after refreshing the token."); + return proxyResponse; + } return proxyResponse; } - return proxyResponse; - } return retryResponse; } + public static ProxyResponse retryRequestWithRefreshedToken(HttpServletRequest req, HttpRequestBase httpRequest, + String apiEndpoint) throws IOException { + return retryRequestWithRefreshedToken(req, httpRequest, apiEndpoint, false); + } + /*** * This method is responsible to get the refresh token * @@ -640,7 +647,7 @@ public class HandlerUtil { * @return If successfully renew tokens, returns TRUE otherwise return FALSE * @throws IOException If an error occurs while witting error response to client side or invoke token renewal API */ - private static ProxyResponse refreshToken(HttpServletRequest req, String keymanagerUrl) + private static ProxyResponse refreshToken(HttpServletRequest req, String keymanagerUrl, boolean isDefaultAuthToken) throws IOException { if (log.isDebugEnabled()) { log.debug("refreshing the token"); @@ -653,8 +660,11 @@ public class HandlerUtil { // handleError(resp, HttpStatus.SC_UNAUTHORIZED); return tokenResultResponse; } - - authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); + if (isDefaultAuthToken) { + authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY); + } else { + authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); + } tokenResultResponse = getTokenResult(authData, keymanagerUrl); if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { log.error("Error occurred while refreshing access token."); @@ -666,7 +676,11 @@ public class HandlerUtil { JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData()); if (jTokenResult.isJsonObject()) { - setNewAuthData(constructAuthDataFromTokenResult(jTokenResult, authData), session); + if (isDefaultAuthToken) { + setNewDefaultAuthData(constructAuthDataFromTokenResult(jTokenResult, authData), session); + } else { + setNewAuthData(constructAuthDataFromTokenResult(jTokenResult, authData), session); + } return tokenResultResponse; } @@ -675,6 +689,11 @@ public class HandlerUtil { // handleError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR); return tokenResultResponse; } + + private static ProxyResponse refreshToken(HttpServletRequest req, String keymanagerUrl) throws IOException { + return refreshToken(req, keymanagerUrl, false); + } + public static ProxyResponse getTokenResult(AuthData authData, String keymanagerUrl) throws IOException { HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); StringEntity tokenEndpointPayload = new StringEntity( @@ -683,6 +702,12 @@ public class HandlerUtil { tokenEndpoint.setEntity(tokenEndpointPayload); String encodedClientApp = authData.getEncodedClientApp(); + if (encodedClientApp == null) { + String clientId = authData.getClientId(); + String clientSecret = authData.getClientSecret(); + String toEncode = clientId + ":" + clientSecret; + encodedClientApp = Base64.getEncoder().encodeToString(toEncode.getBytes()); + } tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); @@ -694,6 +719,11 @@ public class HandlerUtil { session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData); } + public static void setNewDefaultAuthData(AuthData newAuthData, HttpSession session) { + authData = newAuthData; + session.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newAuthData); + } + public static AuthData constructAuthDataFromTokenResult(JsonElement tokenResult, AuthData authData) { JsonObject jTokenResultAsJsonObject = tokenResult.getAsJsonObject(); AuthData newAuthData = new AuthData(); diff --git a/components/ui-request-interceptor/pom.xml b/components/ui-request-interceptor/pom.xml index 70afb85317..cc51666724 100644 --- a/components/ui-request-interceptor/pom.xml +++ b/components/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml index 243c26121e..b52526e02a 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core webapp-authenticator-framework - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/webapp-authenticator-framework/pom.xml b/components/webapp-authenticator-framework/pom.xml index e505ad6cb4..0ede892b7f 100644 --- a/components/webapp-authenticator-framework/pom.xml +++ b/components/webapp-authenticator-framework/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml index b5f659ef6f..8f1745bb78 100644 --- a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml +++ b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml index 45d9ee4cef..4b128c1cb3 100644 --- a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml +++ b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/pom.xml b/features/analytics-mgt/grafana-mgt/pom.xml index 6ec765b1fb..46349cd1ae 100644 --- a/features/analytics-mgt/grafana-mgt/pom.xml +++ b/features/analytics-mgt/grafana-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core analytics-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/pom.xml b/features/analytics-mgt/pom.xml index 67d07adfd5..569422c9de 100644 --- a/features/analytics-mgt/pom.xml +++ b/features/analytics-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml index 17bf23f473..3f06938008 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml index 91f5cfb894..ea792fb1f6 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml index 3fb77250fc..ca37184ea3 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml index ff6cf71893..f96d462b4e 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml index 30a064b238..2f015d97d3 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/pom.xml b/features/apimgt-extensions/pom.xml index 34f5347bda..ef44e37db0 100644 --- a/features/apimgt-extensions/pom.xml +++ b/features/apimgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml index 3819de938a..514dfdd2f4 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core application-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/application-mgt/pom.xml b/features/application-mgt/pom.xml index 10875e5695..f639dbdaf4 100644 --- a/features/application-mgt/pom.xml +++ b/features/application-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/cea-mgt-feature/io.entgra.device.mgt.core.cea.mgt.admin.api.feature/pom.xml b/features/cea-mgt-feature/io.entgra.device.mgt.core.cea.mgt.admin.api.feature/pom.xml index 6fea61c90d..14e01f52b4 100644 --- a/features/cea-mgt-feature/io.entgra.device.mgt.core.cea.mgt.admin.api.feature/pom.xml +++ b/features/cea-mgt-feature/io.entgra.device.mgt.core.cea.mgt.admin.api.feature/pom.xml @@ -18,13 +18,11 @@ ~ --> - + io.entgra.device.mgt.core cea-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/cea-mgt-feature/io.entgra.device.mgt.core.cea.mgt.server.feature/pom.xml b/features/cea-mgt-feature/io.entgra.device.mgt.core.cea.mgt.server.feature/pom.xml index c75f880742..8d8397ae01 100644 --- a/features/cea-mgt-feature/io.entgra.device.mgt.core.cea.mgt.server.feature/pom.xml +++ b/features/cea-mgt-feature/io.entgra.device.mgt.core.cea.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core cea-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/cea-mgt-feature/pom.xml b/features/cea-mgt-feature/pom.xml index 93fce41bca..ddfd8381c9 100644 --- a/features/cea-mgt-feature/pom.xml +++ b/features/cea-mgt-feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml index ca3c60c768..54dec9a0a7 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core certificate-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml index 53c950a249..a4cd54ecb8 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core certificate-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml index 8b33d42fc8..c29d15d221 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core certificate-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index 2a0626945c..3ed731f10e 100644 --- a/features/certificate-mgt/pom.xml +++ b/features/certificate-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml index a6a2d3edc1..d9b0d5fedc 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api.feature/pom.xml index 11c43c203a..49509d8695 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT 4.0.0 diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.feature/pom.xml index d43ddb34c4..37e9e2ac4a 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml index cdaa5fd1e1..94d691700b 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml index 3eb579d31f..a8ea392725 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml index d57ed8363d..d4ba060b68 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml index cc845127c9..399761b3f0 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml index 9d08a86eb7..2e9351f5ca 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml index ebec73daa7..a04e0a0933 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml index 78b8291ef0..66ac3b6eb8 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml index 7cfdf72a68..bc35f8e7c1 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/pom.xml b/features/device-mgt-extensions/pom.xml index 9210d4af15..240077996f 100644 --- a/features/device-mgt-extensions/pom.xml +++ b/features/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml index 778e5a930d..3baff87eb1 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml index eeaf599123..6f21b990a7 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index f5208c958f..8303fc6402 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -289,6 +289,7 @@ um:users:update um:users:invite um:admin:users:view + um:admin:tenants:remove dm:admin:enrollment:update gm:devices:view gm:groups:update @@ -382,6 +383,10 @@ win:ops:reboot win:ops:location win:ops:scan + win:ops:apps + win:ops:device-info + win:ops:security-info + win:ops:firewall-info admin:tenant:view dm:admin:devices:usage:view and:ops:clear-app @@ -415,6 +420,7 @@ dm:admin:cea:update dm:admin:cea:delete dm:admin:cea:sync + am:pub:app:upload device-mgt diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index 43e57cf430..b6dcb7d5be 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -782,9 +782,9 @@ CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING ( CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( DYNAMIC_TASK_ID INTEGER AUTO_INCREMENT NOT NULL, NAME VARCHAR(300) DEFAULT NULL , - CRON VARCHAR(8000) DEFAULT NULL, + CRON VARCHAR(100) DEFAULT NULL, IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TASK_CLASS_NAME VARCHAR(1000) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (DYNAMIC_TASK_ID) ); @@ -792,8 +792,8 @@ CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( DYNAMIC_TASK_ID INTEGER NOT NULL, PROPERTY_NAME VARCHAR(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID VARCHAR(100), + PROPERTY_VALUE VARCHAR(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql index 318dfd2a76..cee731c034 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -852,10 +852,10 @@ CREATE TABLE DM_GEOFENCE_EVENT_MAPPING ( IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DYNAMIC_TASK]') AND TYPE IN (N'U')) CREATE TABLE DYNAMIC_TASK ( DYNAMIC_TASK_ID INTEGER IDENTITY(1,1) NOT NULL, - NAME VARCHAR(255) DEFAULT NULL , - CRON VARCHAR(8000) DEFAULT NULL, + NAME VARCHAR(300) DEFAULT NULL , + CRON VARCHAR(100) DEFAULT NULL, IS_ENABLED BIT NOT NULL DEFAULT 0, - TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TASK_CLASS_NAME VARCHAR(1000) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (DYNAMIC_TASK_ID) ); @@ -864,8 +864,8 @@ IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[D CREATE TABLE DYNAMIC_TASK_PROPERTIES ( DYNAMIC_TASK_ID INTEGER NOT NULL, PROPERTY_NAME VARCHAR(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID VARCHAR(100), + PROPERTY_VALUE VARCHAR(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index b0de3dc590..7ddaf22af6 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -853,9 +853,9 @@ CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING ( CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( DYNAMIC_TASK_ID INTEGER AUTO_INCREMENT NOT NULL, NAME VARCHAR(300) DEFAULT NULL , - CRON VARCHAR(8000) DEFAULT NULL, + CRON VARCHAR(100) DEFAULT NULL, IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TASK_CLASS_NAME VARCHAR(1000) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (DYNAMIC_TASK_ID) ) ENGINE=InnoDB; @@ -863,8 +863,8 @@ CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( DYNAMIC_TASK_ID INTEGER NOT NULL, PROPERTY_NAME VARCHAR(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID VARCHAR(100), + PROPERTY_VALUE TEXT DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql index d632be52aa..6e99bb43ee 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -1127,9 +1127,9 @@ CREATE TABLE DM_GEOFENCE ( CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( DYNAMIC_TASK_ID NUMBER(10) NOT NULL, NAME VARCHAR2(300) DEFAULT NULL , - CRON VARCHAR2(8000) DEFAULT NULL, + CRON VARCHAR2(100) DEFAULT NULL, IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - TASK_CLASS_NAME VARCHAR2(8000) DEFAULT NULL, + TASK_CLASS_NAME VARCHAR2(1000) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, CONSTRAINT PK_DYNAMIC_TASK PRIMARY KEY (DYNAMIC_TASK_ID) ) ENGINE=InnoDB; @@ -1137,8 +1137,8 @@ CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( DYNAMIC_TASK_ID INTEGER NOT NULL, PROPERTY_NAME VARCHAR2(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR2(100) DEFAULT NULL, - TENANT_ID VARCHAR2(100), + PROPERTY_VALUE VARCHAR2(8000) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, CONSTRAINT PK_DYNAMIC_TASK_PROPERTIES PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql index bc22e6db63..5d5c7446e6 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -772,9 +772,9 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE ( CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( DYNAMIC_TASK_ID INTEGER DEFAULT NEXTVAL ('DYNAMIC_TASK_seq') NOT NULL, NAME VARCHAR(300) DEFAULT NULL , - CRON VARCHAR(8000) DEFAULT NULL, + CRON VARCHAR(100) DEFAULT NULL, IS_ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - TASK_CLASS_NAME VARCHAR(8000) DEFAULT NULL, + TASK_CLASS_NAME VARCHAR(1000) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (DYNAMIC_TASK_ID) ) ENGINE=InnoDB; @@ -782,8 +782,8 @@ CREATE TABLE IF NOT EXISTS DYNAMIC_TASK ( CREATE TABLE IF NOT EXISTS DYNAMIC_TASK_PROPERTIES ( DYNAMIC_TASK_ID INTEGER NOT NULL, PROPERTY_NAME VARCHAR(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID VARCHAR(100), + PROPERTY_VALUE TEXT DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (DYNAMIC_TASK_ID, PROPERTY_NAME, TENANT_ID), CONSTRAINT FK_DYNAMIC_TASK_TASK_PROPERTIES FOREIGN KEY (DYNAMIC_TASK_ID) REFERENCES DYNAMIC_TASK (DYNAMIC_TASK_ID) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml index 90870e0aab..2e69e4991e 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml index 458c6835c4..ca7591b012 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml index d7641899e0..fecbd4b026 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml index f46cf7e2f3..dd09fa4aae 100644 --- a/features/device-mgt/pom.xml +++ b/features/device-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml index 70b01ce070..92cc4ed0a6 100644 --- a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml +++ b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core heart-beat-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/heartbeat-management/pom.xml b/features/heartbeat-management/pom.xml index 52208d947f..77db508369 100644 --- a/features/heartbeat-management/pom.xml +++ b/features/heartbeat-management/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml b/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml index 327468d869..47d3eba794 100644 --- a/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml +++ b/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core jwt-client-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/jwt-client/pom.xml b/features/jwt-client/pom.xml index 80120fcee3..13352c3ac9 100644 --- a/features/jwt-client/pom.xml +++ b/features/jwt-client/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml b/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml index 0fb95f7154..13dfee7c04 100644 --- a/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml +++ b/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core logger-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/logger/pom.xml b/features/logger/pom.xml index a084424445..d618a48143 100644 --- a/features/logger/pom.xml +++ b/features/logger/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml b/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml index 185b51e821..51e22389d6 100644 --- a/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml +++ b/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core operation-template-mgt-plugin-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/operation-template-mgt-plugin-feature/pom.xml b/features/operation-template-mgt-plugin-feature/pom.xml index 4bc9c9ab6e..6eaf76b03a 100644 --- a/features/operation-template-mgt-plugin-feature/pom.xml +++ b/features/operation-template-mgt-plugin-feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml b/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml index 4cb66e553a..27e6f9f338 100644 --- a/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml +++ b/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core policy-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/policy-mgt/pom.xml b/features/policy-mgt/pom.xml index 5cb74dbe7a..b8ad61c8c1 100644 --- a/features/policy-mgt/pom.xml +++ b/features/policy-mgt/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml b/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml index 54dd91217d..545cbf5983 100644 --- a/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml +++ b/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../../pom.xml diff --git a/features/subtype-mgt/pom.xml b/features/subtype-mgt/pom.xml index 8e2beb2d65..1d9a686b44 100644 --- a/features/subtype-mgt/pom.xml +++ b/features/subtype-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml b/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml index 9162debebe..910eb1dd01 100755 --- a/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml +++ b/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../../pom.xml diff --git a/features/task-mgt/pom.xml b/features/task-mgt/pom.xml index 0a6401dd4e..847891c371 100755 --- a/features/task-mgt/pom.xml +++ b/features/task-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml b/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml index 6f589c6d99..11c9910d26 100644 --- a/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml +++ b/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml @@ -20,7 +20,7 @@ tenant-mgt-feature io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/tenant-mgt/pom.xml b/features/tenant-mgt/pom.xml index d34902afa0..1905e1c77f 100644 --- a/features/tenant-mgt/pom.xml +++ b/features/tenant-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml index 6aa8c4c0c2..5fdfd06406 100644 --- a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml +++ b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core email-sender-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/share-product-download-url.vm b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/share-product-download-url.vm index be994a117f..8081adb209 100644 --- a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/share-product-download-url.vm +++ b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/share-product-download-url.vm @@ -196,7 +196,7 @@

Hi $first-name,

-

Welcome to your free Entgra UEM trial. Please download the product here.

+

Welcome to your free Entgra UEM trial. Please download the product here.


To make the best use of your evaluation, here's a quick introduction to the key capabilities of our product.

diff --git a/features/transport-mgt/email-sender/pom.xml b/features/transport-mgt/email-sender/pom.xml index 3efbf0e089..3a8cad8254 100644 --- a/features/transport-mgt/email-sender/pom.xml +++ b/features/transport-mgt/email-sender/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/pom.xml b/features/transport-mgt/pom.xml index d5b2168e61..d8ef07065e 100644 --- a/features/transport-mgt/pom.xml +++ b/features/transport-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml index 241b45c78f..ba79eec348 100644 --- a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml index 327b5ed869..8a8d12575f 100644 --- a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/sms-handler/pom.xml b/features/transport-mgt/sms-handler/pom.xml index 3d98b52859..29a6377f7a 100644 --- a/features/transport-mgt/sms-handler/pom.xml +++ b/features/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml b/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml index 43550a3381..4695bfd1a7 100644 --- a/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml +++ b/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml @@ -21,7 +21,7 @@ ui-request-interceptor-feature io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT 4.0.0 diff --git a/features/ui-request-interceptor/pom.xml b/features/ui-request-interceptor/pom.xml index f8b1dbb537..af85499d51 100644 --- a/features/ui-request-interceptor/pom.xml +++ b/features/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml b/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml index 91260f0b1e..ad5a36dc35 100644 --- a/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml +++ b/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core webapp-authenticator-framework-feature - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/webapp-authenticator-framework/pom.xml b/features/webapp-authenticator-framework/pom.xml index 145f9919a8..b790add82e 100644 --- a/features/webapp-authenticator-framework/pom.xml +++ b/features/webapp-authenticator-framework/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index dc526efe6c..680a4ced22 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent pom - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT WSO2 Carbon - Device Management - Parent http://wso2.org WSO2 Connected Device Manager Components @@ -894,6 +894,12 @@ ${jaxb.api.version} test
+ + org.wso2.orbit.javax.xml.bind + jaxb-api + 2.3.1.wso2v1 + compile + org.apache.axis2.transport @@ -2122,7 +2128,7 @@ 1.2.11.wso2v10 - 5.0.40-SNAPSHOT + 5.0.42-SNAPSHOT 4.7.35 @@ -2171,8 +2177,8 @@ 1.3 2.8.5 31.0.1-jre - 4.6.0 - 1.13.0 + 4.12.0 + 3.6.0 9.3.1 1.1.1 1.2