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 c86b9b207e..25fc486ee7 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.41-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 e59e9abc44..ceef7f5959 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.41-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 0d134dae6c..4842750edf 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.41-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 6604c333c9..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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/pom.xml b/components/analytics-mgt/pom.xml index 2527b4a26d..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.41-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 592b1ed792..b8d868cc87 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.41-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 05e9c54049..3ab5fe59dd 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.41-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 69a7bc2541..4ecbf9f1c4 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.41-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 0cb9ffd8f9..84822384e9 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.41-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 244bd8c942..b1cedaca8e 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.41-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 a4593e6811..f8c004e5c5 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.41-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 93e3e0289d..d601142018 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.41-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 0f898f0df6..cfdf22f121 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 567e1f8883..8cc45e2808 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.41-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 d62f719a14..e6f51568d0 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.41-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 ceed8f5544..700fe9adbc 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 @@ -372,11 +372,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; /** @@ -384,33 +382,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 @@ -547,4 +539,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 53cea397b0..75ee1551e9 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml @@ -163,6 +163,9 @@ ${basedir}/target/coverage-reports/jacoco-unit.exec file:src/test/resources/log4j.properties + 8280 + 8280 + test org.ops4j.pax.logging @@ -419,6 +422,27 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.notification.logger + + com.squareup.okhttp3 + okhttp + compile + + + com.squareup.okio + okio + + + + + com.squareup.okio + okio + ${okio.version} + + + 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 13be8be454..9777469cea 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 aa1aaff816..558bf2821f 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 e4db2592f9..9fc8994f5e 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 @@ -119,4 +119,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 b722030343..d26405203e 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 1f962e1d3e..dd4a517dd0 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 @@ -1880,4 +1880,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 78d16d56bb..8dc97494c0 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 @@ -620,4 +620,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 f30cd71da4..b3f0eb9f56 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 @@ -480,4 +480,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 008f64db89..76269cbf89 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 @@ -482,4 +482,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 2339e92e10..d842868d31 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 @@ -482,4 +482,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 1b6e7a4e1b..428f4dc393 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 @@ -482,4 +482,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 3d40c552ac..ac16c04084 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 @@ -110,6 +110,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 e6d98993e6..5f1cd06dc2 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 @@ -597,4 +597,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 9dd324123c..243ce17bf4 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 @@ -1466,4 +1466,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 4cb37705d5..410fcacd66 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 1f5c49fb81..9be21a8a0c 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.exception.ApplicationManagementDAOException; import io.entgra.device.mgt.core.application.mgt.core.exception.ForbiddenException; @@ -95,6 +95,8 @@ import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementEx import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagementException; 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; @@ -102,6 +104,8 @@ import org.wso2.carbon.user.api.UserStoreException; 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; @@ -127,6 +131,8 @@ public class ApplicationManagerImpl implements ApplicationManager { private SubscriptionDAO subscriptionDAO; private LifecycleStateManager lifecycleStateManager; private SPApplicationDAO spApplicationDAO; + private VppApplicationDAO vppApplicationDAO; + private ReviewDAO reviewDAO; public ApplicationManagerImpl() { initDataAccessObjects(); @@ -140,10 +146,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(); @@ -171,22 +228,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); } } @@ -195,17 +340,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); } } @@ -214,38 +369,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); } } @@ -278,27 +464,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) { @@ -315,7 +501,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; @@ -2421,21 +2617,25 @@ public class ApplicationManagerImpl implements ApplicationManager { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); ApplicationDTO applicationDTO = getApplication(applicationId); + String sanitizedName = ""; + if (!StringUtils.isEmpty(applicationUpdateWrapper.getName())) { + 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(ApplicationManagementUtil.sanitizeName(applicationUpdateWrapper.getName(), - Constants.ApplicationProperties.NAME)); + applicationDTO.setName(sanitizedName); } if (!StringUtils.isEmpty(applicationUpdateWrapper.getSubMethod()) && !applicationDTO.getSubType() .equals(applicationUpdateWrapper.getSubMethod())) { @@ -3131,11 +3331,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()); @@ -3202,17 +3404,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, @@ -3271,17 +3481,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, @@ -3336,18 +3554,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<>( @@ -3466,6 +3693,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(); } @@ -3901,30 +4134,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()); } @@ -4165,4 +4392,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 4b580f046b..7a20401381 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 @@ -313,4 +313,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 151240e3c0..625d95130b 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; @@ -29,6 +30,7 @@ import io.entgra.device.mgt.core.application.mgt.common.services.*; 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; @@ -102,6 +104,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(); // todo: 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 bc770ead5e..d9de5fe57f 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; @@ -56,6 +57,7 @@ public class DataHolder { private AppmDataHandler configManager; private TaskService taskService; + private FileTransferService fileTransferService; private static final DataHolder applicationMgtDataHolder = new DataHolder(); @@ -154,4 +156,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/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 8c9d1b2346..4a0687052a 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 @@ -67,6 +67,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) { @@ -488,7 +489,6 @@ public class APIUtil { List screenshotPaths = new ArrayList<>(); ApplicationRelease applicationRelease = new ApplicationRelease(); - UrlValidator urlValidator = new UrlValidator(); applicationRelease.setDescription(applicationReleaseDTO.getDescription()); applicationRelease.setVersion(applicationReleaseDTO.getVersion()); @@ -511,13 +511,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 @@ -538,6 +533,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(); @@ -584,4 +594,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 e2ec105081..f70d94fb76 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,17 +54,17 @@ 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 io.entgra.device.mgt.core.application.mgt.common.services.*; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.*; import java.io.ByteArrayOutputStream; import java.io.File; @@ -76,6 +85,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; /** @@ -161,6 +171,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 @@ -253,6 +306,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()); @@ -281,13 +369,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); @@ -295,7 +382,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); @@ -308,56 +394,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()); @@ -562,4 +640,77 @@ public class ApplicationManagementUtil { 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 2d3b8e85ca..92dfe8e948 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 @@ -223,4 +223,14 @@ public class 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 2ce7f47775..6ba0305ba0 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,18 @@ 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; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.RequestValidatingException; @@ -52,6 +62,10 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; 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 +112,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 23b7a2c082..47af2ec027 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.41-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 bb6cf9eabc..bbce643b92 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 @@ -22,7 +22,7 @@ io.entgra.device.mgt.core cea-mgt - 5.0.41-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 ffc6777ef1..5a04c17d1f 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.41-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 f7e6018ac9..159dbebab6 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.41-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 d3ebc2fd55..9cb93c4e30 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/cea-mgt/pom.xml b/components/cea-mgt/pom.xml index 0164f1703e..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.41-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 86a56d5549..3eda5016bf 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.41-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 8029b28952..754e97da5c 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.41-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 b3c6db4459..96efb9638b 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index 3efe44aef8..0ede70bbb1 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.41-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 db013ea71b..d42020c825 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.41-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 c0e88b8373..4cdf1c9f1f 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml 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 7bdee363d5..f05dd89d70 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.41-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/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index 5b2f7147fc..ad1493e17a 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -116,6 +116,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION OPERATION_CODE VARCHAR(1000) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID) ); diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/sql/h2.sql b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/sql/h2.sql index b4d2bde228..c079d1e214 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/sql/h2.sql +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/sql/h2.sql @@ -140,6 +140,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( OPERATION_CODE VARCHAR(1000) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) 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 f2edc213d0..0397c541fb 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.41-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 7eaf4ffb6e..062bdf563e 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.41-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 685c67cc29..0fc72b8a74 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.41-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 ad12e88935..9cb4fe0f9a 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.41-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 dcabcda941..3ae0f1a55e 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.41-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 ade454924c..1e2665ee47 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.41-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 acf333455f..088a6f10c8 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.41-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 eeda552280..e1f3abaa41 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.41-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 8b29c1d722..86f118454f 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index 69c82689ef..8d488468f7 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.41-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 ba27202abc..6b6e00fb2c 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.41-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/AccessAuthorizationService.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/AccessAuthorizationService.java new file mode 100644 index 0000000000..1de058f4fc --- /dev/null +++ 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/AccessAuthorizationService.java @@ -0,0 +1,181 @@ +/* + * 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.api.jaxrs.service.api; + +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse; +import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAuthorizationRequest; +import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAuthorizationRequest; +import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAuthorizationResult; +import io.swagger.annotations.*; +import org.apache.axis2.transport.http.HTTPConstants; + +import javax.validation.Valid; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@SwaggerDefinition( + info = @Info( + version = "1.0.0", + title = "", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "name", value = "AccessAuthorizationService"), + @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/access"), + }) + } + ), + tags = { + @Tag(name = "device_management", description = "") + } +) +@Path("/access") +@Api(value = "AccessAuthorizationService", description = "This API carries all device group management related " + + "access authorization") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface AccessAuthorizationService { + + @POST + @Path("/device") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "check device access authorization", + notes = "Returns device access acutorization info", + tags = "device_management" + ) + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "Created. \n Device group has successfully been created", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The URL of the added group."), + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time" + + ".\n" + "Used by caches, or in conditional requests.") + } + ), + @ApiResponse( + code = 303, + message = "See Other. \n Source can be retrieved from the URL specified at the Location " + + "header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Current logged in user is not authorized for this request", + response = ErrorResponse.class), + @ApiResponse( + code = 415, + message = "Unsupported media type. \n The entity of the request was in a not supported " + + "format."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while checking access", + response = ErrorResponse.class) + }) + Response checkDeviceAccess( + @ApiParam( + name = "deviceAccessRequest", + value = "Define the device access request object with data.", + required = true) + @Valid DeviceAuthorizationRequest deviceAuthorizationRequest); + + @POST + @Path("/group") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "check device access authorization", + notes = "Returns device access acutorization info", + tags = "device_management" + ) + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "Created. \n Device group has successfully been created", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The URL of the added group."), + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time" + + ".\n" + "Used by caches, or in conditional requests.") + } + ), + @ApiResponse( + code = 303, + message = "See Other. \n Source can be retrieved from the URL specified at the Location " + + "header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Current logged in user is not authorized for this request", + response = ErrorResponse.class), + @ApiResponse( + code = 415, + message = "Unsupported media type. \n The entity of the request was in a not supported " + + "format."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while checking access", + response = ErrorResponse.class) + }) + Response checkGroupAccess( + @ApiParam( + name = "groupAccessRequest", + value = "Define the group access request object with data.", + required = true) + @Valid GroupAuthorizationRequest request); +} 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/ActivityInfoProviderService.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/ActivityInfoProviderService.java index 39b133202a..9c9756241b 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/ActivityInfoProviderService.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/ActivityInfoProviderService.java @@ -473,7 +473,7 @@ public interface ActivityInfoProviderService { name = "status", value = "Operation response status to filter" ) - @QueryParam("status") String status, + @QueryParam("status") List statuses, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time\n." + @@ -597,7 +597,7 @@ public interface ActivityInfoProviderService { name = "status", value = "Operation response status to filter" ) - @QueryParam("status") String status, + @QueryParam("status") List statuses, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time\n." + 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 1feefa0756..30cf32a98b 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/AccessAuthorizationServiceImpl.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/AccessAuthorizationServiceImpl.java new file mode 100644 index 0000000000..f6d555a273 --- /dev/null +++ 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/AccessAuthorizationServiceImpl.java @@ -0,0 +1,95 @@ +/* + * 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.api.jaxrs.service.impl; + +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.AccessAuthorizationService; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; +import io.entgra.device.mgt.core.device.mgt.common.authorization.*; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + + +public class AccessAuthorizationServiceImpl implements AccessAuthorizationService { + + private static final Log log = LogFactory.getLog(AccessAuthorizationServiceImpl.class); + @Override + public Response checkDeviceAccess(DeviceAuthorizationRequest deviceAuthorizationRequest) { + + if (StringUtils.isEmpty(deviceAuthorizationRequest.getType())) { + String msg = "device type not specified"; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + + if (deviceAuthorizationRequest.getDeviceIds().isEmpty()) { + String msg = "device ids not specified"; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + + if (deviceAuthorizationRequest.getPermissions().isEmpty()) { + String msg = "permissions not specified"; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + + List deviceIdentifiers = new ArrayList<>(); + for(String id : deviceAuthorizationRequest.getDeviceIds()) { + DeviceIdentifier identifier = new DeviceIdentifier(id, deviceAuthorizationRequest.getType()); + deviceIdentifiers.add(identifier); + } + try { + DeviceAuthorizationResult result = DeviceMgtAPIUtils.getDeviceAccessAuthorizationService() + .isUserAuthorized(deviceIdentifiers, deviceAuthorizationRequest.getUsername(), + deviceAuthorizationRequest.getPermissions().toArray(new String[0])); + return Response.status(Response.Status.OK).entity(result).build(); + } catch (DeviceAccessAuthorizationException e) { + String msg = "Error occurred while checking access info"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @Override + public Response checkGroupAccess(GroupAuthorizationRequest request) { + + if (request.getGroupIds().isEmpty()) { + String msg = "group ids not specified"; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + + if (request.getPermissions().isEmpty()) { + String msg = "permissions not specified"; + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + + try { + GroupAuthorizationResult result = DeviceMgtAPIUtils.getGroupAccessAuthorizationService() + .isUserAuthorized(request.getGroupIds(), request.getUsername(), + request.getPermissions().toArray(new String[0])); + return Response.status(Response.Status.OK).entity(result).build(); + } catch (GroupAccessAuthorizationException e) { + String msg = "Error occurred while checking access info"; + 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/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/ActivityProviderServiceImpl.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/ActivityProviderServiceImpl.java index 6082eb0f1c..41d56dbe54 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/ActivityProviderServiceImpl.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/ActivityProviderServiceImpl.java @@ -43,6 +43,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -252,7 +253,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService @QueryParam("deviceType") String deviceType, @QueryParam("deviceId") List deviceIds, @QueryParam("type") String type, - @QueryParam("status") String status, + @QueryParam("status") List statuses, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("startTimestamp") long startTimestamp, @QueryParam("endTimestamp") long endTimestamp) { @@ -329,8 +330,12 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService if (type != null && !type.isEmpty()) { activityPaginationRequest.setType(Operation.Type.valueOf(type.toUpperCase())); } - if (status != null && !status.isEmpty()) { - activityPaginationRequest.setStatus(Operation.Status.valueOf(status.toUpperCase())); + if (statuses != null && !statuses.isEmpty()) { + List statusEnums = new ArrayList<>(); + for (String status : statuses) { + statusEnums.add(Operation.Status.valueOf(status.toUpperCase())); + } + activityPaginationRequest.setStatuses(statusEnums); } if (timestamp > 0) { activityPaginationRequest.setSince(timestamp); @@ -375,7 +380,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService @QueryParam("deviceType") String deviceType, @QueryParam("deviceId") List deviceIds, @QueryParam("type") String type, - @QueryParam("status") String status, + @QueryParam("status") List statuses, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("startTimestamp") long startTimestamp, @QueryParam("endTimestamp") long endTimestamp) { @@ -450,8 +455,12 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService if (type != null && !type.isEmpty()) { activityPaginationRequest.setType(Operation.Type.valueOf(type.toUpperCase())); } - if (status != null && !status.isEmpty()) { - activityPaginationRequest.setStatus(Operation.Status.valueOf(status.toUpperCase())); + if (statuses != null && !statuses.isEmpty()) { + List statusEnums = new ArrayList<>(); + for (String status : statuses) { + statusEnums.add(Operation.Status.valueOf(status.toUpperCase())); + } + activityPaginationRequest.setStatuses(statusEnums); } if (timestamp > 0) { activityPaginationRequest.setSince(timestamp); 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/DeviceAgentServiceImpl.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/DeviceAgentServiceImpl.java index e8fa9cacf9..9f89b7f0cd 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/DeviceAgentServiceImpl.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/DeviceAgentServiceImpl.java @@ -28,6 +28,11 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventAttri import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceAgentService; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; +import org.apache.axis2.AxisFault; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; @@ -161,7 +166,9 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { DeviceMgtAPIUtils.getDeviceAccessAuthorizationService(); boolean status; try { - status = deviceAccessAuthorizationService.isUserAuthorized(new DeviceIdentifier(id, type)); + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; + status = deviceAccessAuthorizationService.isUserAuthorized(new DeviceIdentifier(id, type), requiredPermissions); } catch (DeviceAccessAuthorizationException e) { String msg = "Error occurred while modifying enrollment of the Android device that carries the id '" + id + "'"; @@ -223,8 +230,10 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { String msg = "invalid payload structure"; return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } else { + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; boolean authorized = DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized - (new DeviceIdentifier(type, deviceId)); + (new DeviceIdentifier(type, deviceId), requiredPermissions); if (!authorized) { String msg = "Does not have permission to access the device."; return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); @@ -323,8 +332,10 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { String msg = "Invalid payload structure"; return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } else { + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; boolean authorized = DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized - (new DeviceIdentifier(type, deviceId)); + (new DeviceIdentifier(type, deviceId), requiredPermissions); if (!authorized) { String msg = "Does not have permission to access the device."; return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); 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/DeviceManagementServiceImpl.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/DeviceManagementServiceImpl.java index 43da49fc7e..47699b100d 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/DeviceManagementServiceImpl.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/DeviceManagementServiceImpl.java @@ -43,6 +43,7 @@ import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionMan import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DisenrollRequest; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtUtil; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; @@ -589,7 +590,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type); // check whether the user is authorized - if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser)) { + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; + if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser, requiredPermissions)) { String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + id + "'"; log.error(msg); return Response.status(Response.Status.UNAUTHORIZED).entity( @@ -725,7 +728,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, device.getType()); // check whether the user is authorized - if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser)) { + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; + if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser, requiredPermissions)) { String message = "User '" + authorizedUser + "' is not authorized to retrieve the given " + "device id '" + id + "'"; log.error(message); 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/PolicyManagementServiceImpl.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/PolicyManagementServiceImpl.java index fb16a529e4..fa581862b6 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/PolicyManagementServiceImpl.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/PolicyManagementServiceImpl.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import io.entgra.device.mgt.core.device.mgt.common.PolicyPaginationRequest; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -96,7 +97,9 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); String username = threadLocalCarbonContext.getUsername(); try { - if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, username)) { + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; + if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, username, requiredPermissions)) { return Response.status(Response.Status.UNAUTHORIZED).entity( new ErrorResponse.ErrorResponseBuilder().setMessage ("Current logged in user is not authorized to add policies").build()).build(); 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 efdefef7a4..acd19f4dbd 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 @@ -243,7 +243,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( @@ -325,7 +325,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( @@ -486,7 +486,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( @@ -565,6 +565,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); } } @@ -589,7 +590,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( @@ -1240,7 +1241,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)); @@ -1248,9 +1249,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/GroupManagementAdminServiceImpl.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/GroupManagementAdminServiceImpl.java index 8c13cf4bf3..0ed3205426 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/GroupManagementAdminServiceImpl.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/GroupManagementAdminServiceImpl.java @@ -172,6 +172,9 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ if (group == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } + if (StringUtils.isEmpty(group.getOwner())) { + group.setOwner(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername()); + } group.setStatus(DeviceGroupConstants.GroupStatus.ACTIVE); try { DeviceMgtAPIUtils.getGroupManagementProviderService().createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS); 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 a99b19ff7d..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,14 +17,21 @@ */ 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; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.PrivacyComplianceException; 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 io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.PrivacyComplianceException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +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/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.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/util/DeviceMgtAPIUtils.java index c1c1f1aca5..6a4adacd55 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/util/DeviceMgtAPIUtils.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/util/DeviceMgtAPIUtils.java @@ -30,7 +30,9 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.OperationStatusBean; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.analytics.EventAttributeList; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.InputValidationException; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.RequestValidationUtil; +import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.apache.axis2.AxisFault; import org.apache.axis2.client.Options; import org.apache.axis2.java.security.SSLProtocolSocketFactory; @@ -346,6 +348,17 @@ public class DeviceMgtAPIUtils { return deviceAccessAuthorizationService; } + public static GroupAccessAuthorizationService getGroupAccessAuthorizationService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + GroupAccessAuthorizationService groupAccessAuthorizationService = + (GroupAccessAuthorizationService) ctx.getOSGiService(GroupAccessAuthorizationService.class, null); + if (groupAccessAuthorizationService == null) { + String msg = "GroupAccessAuthorizationService service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return groupAccessAuthorizationService; + } public static GroupManagementProviderService getGroupManagementProviderService() { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); GroupManagementProviderService groupManagementProviderService = @@ -1172,7 +1185,9 @@ public class DeviceMgtAPIUtils { RequestValidationUtil.validateDeviceIdentifier(deviceType, identifier); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(identifier, deviceType); - if (!getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, authorizedUser)) { + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; + if (!getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, authorizedUser, requiredPermissions)) { String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + identifier + "'"; log.error(msg); 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/ActivityProviderServiceImplTest.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/ActivityProviderServiceImplTest.java index 91711e6b44..1cc391a3e7 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/ActivityProviderServiceImplTest.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/ActivityProviderServiceImplTest.java @@ -132,7 +132,7 @@ public class ActivityProviderServiceImplTest { activityPaginationRequest.setDeviceType(DEVICE_TYPE_2); activityPaginationRequest.setOperationId(OPERATION_ID); activityPaginationRequest.setInitiatedBy(INITIATED_BY); - activityPaginationRequest.setStatus(STATUS); + activityPaginationRequest.setStatuses(Collections.singletonList(STATUS)); activityPaginationRequest.setType(TYPE); activityPaginationRequest.setStartTimestamp(0); activityPaginationRequest.setEndTimestamp(0); @@ -226,7 +226,7 @@ public class ActivityProviderServiceImplTest { Mockito.when(this.deviceManagementProviderService.getActivities(Mockito.any())).thenReturn(activities); Response response = this.activityInfoProviderService.getActivities( OFFSET, LIMIT, SINCE, INITIATED_BY, OPERATION_CODE, OPERATION_ID, - DEVICE_TYPE_2, Collections.singletonList(DEVICE_ID), TYPE.toString(), STATUS.toString(), null, 0, 0); + DEVICE_TYPE_2, Collections.singletonList(DEVICE_ID), TYPE.toString(), Collections.singletonList(STATUS.toString()), null, 0, 0); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertNotNull(response); @@ -258,7 +258,7 @@ public class ActivityProviderServiceImplTest { Mockito.when(this.deviceManagementProviderService.getDeviceActivities(Mockito.any())).thenReturn(deviceActivities); Response response = this.activityInfoProviderService.getDeviceActivities( OFFSET, LIMIT, SINCE, INITIATED_BY, OPERATION_CODE, OPERATION_ID, - DEVICE_TYPE_2, Collections.singletonList(DEVICE_ID), TYPE.toString(), STATUS.toString(), null, 0, 0); + DEVICE_TYPE_2, Collections.singletonList(DEVICE_ID), TYPE.toString(), Collections.singletonList(STATUS.toString()), null, 0, 0); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertNotNull(response); 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/DeviceAgentServiceTest.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/DeviceAgentServiceTest.java index 4a5a370d0f..1abf3d5fc3 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/DeviceAgentServiceTest.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/DeviceAgentServiceTest.java @@ -283,7 +283,7 @@ public class DeviceAgentServiceTest { Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Mockito.when(this.deviceManagementProviderService .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenThrow(new DeviceAccessAuthorizationException()); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Assert.assertNotNull(response, "Response should not be null"); @@ -303,7 +303,7 @@ public class DeviceAgentServiceTest { Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Mockito.when(this.deviceManagementProviderService .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(false); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Assert.assertNotNull(response, "Response should not be null"); @@ -325,7 +325,7 @@ public class DeviceAgentServiceTest { Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Mockito.when(this.deviceManagementProviderService .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -348,7 +348,7 @@ public class DeviceAgentServiceTest { Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Mockito.when(this.deviceManagementProviderService .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())) .thenThrow(new DeviceManagementException()); @@ -370,7 +370,7 @@ public class DeviceAgentServiceTest { "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true)); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -406,7 +406,7 @@ public class DeviceAgentServiceTest { .toReturn(this.privilegedCarbonContext); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(false); Mockito.when(this.privilegedCarbonContext.getTenantDomain()) .thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); @@ -430,7 +430,7 @@ public class DeviceAgentServiceTest { .toReturn(this.privilegedCarbonContext); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenThrow(new DeviceAccessAuthorizationException()); Mockito.when(this.privilegedCarbonContext.getTenantDomain()) .thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); @@ -455,7 +455,7 @@ public class DeviceAgentServiceTest { .toReturn(this.privilegedCarbonContext); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(true); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) .toReturn(this.eventStreamAdminServiceStub); @@ -483,7 +483,7 @@ public class DeviceAgentServiceTest { .toReturn(this.privilegedCarbonContext); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(true); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) .toThrow(new AxisFault("")); @@ -509,7 +509,7 @@ public class DeviceAgentServiceTest { .toReturn(this.privilegedCarbonContext); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(true); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) .toThrow(new RemoteException()); @@ -537,7 +537,7 @@ public class DeviceAgentServiceTest { .toReturn(this.privilegedCarbonContext); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(true); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) .toThrow(new JWTClientException()); @@ -565,7 +565,7 @@ public class DeviceAgentServiceTest { .toReturn(this.privilegedCarbonContext); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); - Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) + Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), Mockito.any(String[].class))) .thenReturn(true); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub")) .toThrow(new UserStoreException()); 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/DeviceManagementServiceImplTest.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/DeviceManagementServiceImplTest.java index 0f50c89156..f45299bd0e 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/DeviceManagementServiceImplTest.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/DeviceManagementServiceImplTest.java @@ -215,7 +215,7 @@ public class DeviceManagementServiceImplTest { Mockito.when(carbonContext.getTenantId()).thenReturn(-1234); Mockito.when(carbonContext.getUsername()).thenReturn(DEFAULT_USERNAME); Mockito.when(deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), - Mockito.anyString())).thenReturn(true); + Mockito.anyString(), Mockito.any(String[].class))).thenReturn(true); Response response = this.deviceManagementService .getDeviceByID(TEST_DEVICE_IDENTIFIER, ifModifiedSince,true); 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 911c85449c..60530eed80 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 9ed56e0d47..51a96e5122 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/ActivityPaginationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/ActivityPaginationRequest.java index 058b82dd2f..77161d7036 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/ActivityPaginationRequest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/ActivityPaginationRequest.java @@ -36,7 +36,7 @@ public class ActivityPaginationRequest { private String initiatedBy; private long since; private Operation.Type type; - private Operation.Status status; + private List statuses; private long startTimestamp; private long endTimestamp; @@ -110,12 +110,12 @@ public class ActivityPaginationRequest { this.type = type; } - public Operation.Status getStatus() { - return status; + public List getStatuses() { + return statuses; } - public void setStatus(Operation.Status status) { - this.status = status; + public void setStatuses(List statuses) { + this.statuses = statuses; } public long getStartTimestamp() { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/DeviceAccessAuthorizationService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/DeviceAccessAuthorizationService.java index 713defbcee..c1d4d50b3f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/DeviceAccessAuthorizationService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/DeviceAccessAuthorizationService.java @@ -28,15 +28,6 @@ import java.util.List; * accessing the device information and performing MDM operations on devices. */ public interface DeviceAccessAuthorizationService { - /** - * This method will check whether the currently logged-in user has the access to the device identified by the given - * DeviceIdentifier. - * - * @param deviceIdentifier - DeviceIdentifier of the device to be checked. - * @return Boolean authorization result. - * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. - */ - boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException; /** * This method will check whether the currently logged-in user has the access to the device identified by the given @@ -50,18 +41,6 @@ public interface DeviceAccessAuthorizationService { boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String[] groupPermissions) throws DeviceAccessAuthorizationException; - /** - * This method will check whether the currently logged-in user has the access to the devices identified by the given - * DeviceIdentifier list. - * - * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. - * @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and - * unauthorized devices. - * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. - */ - DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers) throws - DeviceAccessAuthorizationException; - /** * This method will check whether the currently logged-in user has the access to the devices identified by the given * DeviceIdentifier list. @@ -103,18 +82,6 @@ public interface DeviceAccessAuthorizationService { String[] groupPermissions) throws DeviceAccessAuthorizationException; - /** - * This method will check whether the given user has the access to the device identified by the given - * DeviceIdentifier. - * - * @param deviceIdentifier - DeviceIdentifier of the device to be checked. - * @param username - Username of the user to be checked for authorization. - * @return Boolean authorization result. - * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. - */ - boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username) throws - DeviceAccessAuthorizationException; - /** * This method will check whether the authenticated user has the admin permissions. * @@ -122,17 +89,4 @@ public interface DeviceAccessAuthorizationService { * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. */ boolean isDeviceAdminUser() throws DeviceAccessAuthorizationException; - - /** - * This method will check whether the given user has the access to the devices identified by the given - * DeviceIdentifier list. - * - * @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization. - * @param username - Username of the user to be checked for authorization. - * @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and - * unauthorized devices. - * @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization. - */ - DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers, String username) throws - DeviceAccessAuthorizationException; } \ No newline at end of file diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/DeviceAuthorizationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/DeviceAuthorizationRequest.java new file mode 100644 index 0000000000..92602fe5f4 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/DeviceAuthorizationRequest.java @@ -0,0 +1,68 @@ +/* + * 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.common.authorization; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; + +@ApiModel(value = "DeviceAuthorizationRequest", description = "") +public class DeviceAuthorizationRequest { + + @ApiModelProperty(name = "type", value = "device type") + private String type; + @ApiModelProperty(name = "deviceIds", value = "list of device ids") + private List deviceIds; + @ApiModelProperty(name = "username", value = "user who is accessing the device") + private String username; + @ApiModelProperty(name = "permissions", value = "list of permissions") + private List permissions; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public List getDeviceIds() { + return deviceIds; + } + + public void setDeviceIds(List deviceIds) { + this.deviceIds = deviceIds; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public List getPermissions() { + return permissions; + } + + public void setPermissions(List permissions) { + this.permissions = permissions; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAccessAuthorizationException.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAccessAuthorizationException.java new file mode 100644 index 0000000000..22ab4eef62 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAccessAuthorizationException.java @@ -0,0 +1,61 @@ +/* + * 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.common.authorization; + +/** + * Custom exception class which wraps exceptions occurred inside GroupAccessAuthorization service. + */ +public class GroupAccessAuthorizationException extends Exception { + + private static final long serialVersionUID = -3151279331929070297L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public GroupAccessAuthorizationException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public GroupAccessAuthorizationException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public GroupAccessAuthorizationException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public GroupAccessAuthorizationException() { + super(); + } + + public GroupAccessAuthorizationException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAccessAuthorizationService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAccessAuthorizationService.java new file mode 100644 index 0000000000..c9e942cd31 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAccessAuthorizationService.java @@ -0,0 +1,33 @@ +/* + * 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.common.authorization; + +import java.util.List; + +public interface GroupAccessAuthorizationService { + + public boolean isUserAuthorized(int groupId, String username, String[] groupPermissions) + throws GroupAccessAuthorizationException; + + public boolean isUserAuthorized(int groupId, String[] groupPermissions) + throws GroupAccessAuthorizationException; + + public GroupAuthorizationResult isUserAuthorized(List groupIds, String username, String[] groupPermission) + throws GroupAccessAuthorizationException; + +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAuthorizationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAuthorizationRequest.java new file mode 100644 index 0000000000..9cda89c591 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAuthorizationRequest.java @@ -0,0 +1,58 @@ +/* + * 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.common.authorization; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; + +@ApiModel(value = "GroupAuthorizationRequest", description = "") +public class GroupAuthorizationRequest { + + @ApiModelProperty(name = "groupIds", value = "list of group Ids") + private List groupIds; + @ApiModelProperty(name = "username", value = "user who is accessing the device") + private String username; + @ApiModelProperty(name = "permissions", value = "list of permissions") + private List permissions; + + public List getGroupIds() { + return groupIds; + } + + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public List getPermissions() { + return permissions; + } + + public void setPermissions(List permissions) { + this.permissions = permissions; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAuthorizationResult.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAuthorizationResult.java new file mode 100644 index 0000000000..93608510ad --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/authorization/GroupAuthorizationResult.java @@ -0,0 +1,56 @@ +/* + * 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.common.authorization; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a GroupAuthorizationResult including a list of authorized groups and a list of unauthorized groups. + */ +public class GroupAuthorizationResult { + + private List authorizedGroupIds = new ArrayList<>(); + private List unauthorizedGroupIds= new ArrayList<>(); + + public List getAuthorizedGroupIds() { + return authorizedGroupIds; + } + + public void setAuthorizedGroupIds(List authorizedGroupIds) { + this.authorizedGroupIds = authorizedGroupIds; + } + + public List getUnauthorizedGroupIds() { + return unauthorizedGroupIds; + } + + public void setUnauthorizedGroupIds(List unauthorizedGroupIds) { + this.unauthorizedGroupIds = unauthorizedGroupIds; + } + + public void addAuthorizedGroupId(int groupId) { + this.authorizedGroupIds.add(groupId); + } + + public void addUnauthorizedGroupId(int groupId) { + this.unauthorizedGroupIds.add(groupId); + } + +} 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 777003a7bd..b60604bbff 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.41-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 7ee5c761ff..d95fa8e1df 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml 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 3e49e65542..240ebad171 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,11 @@ 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; +import org.wso2.carbon.context.CarbonContext; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; @@ -286,8 +291,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/archival/dao/impl/ArchivalDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java index 3ade9e203c..1f085745f4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java @@ -538,8 +538,9 @@ public class ArchivalDAOImpl implements ArchivalDAO { String sql = "INSERT INTO " + DESTINATION_DB + ".DM_OPERATION_ARCH " + "SELECT OPR.ID, OPR.TYPE, OPR.CREATED_TIMESTAMP, OPR.RECEIVED_TIMESTAMP, " + - "OPR.OPERATION_CODE, OPR.INITIATED_BY, OPR.OPERATION_DETAILS, OPR.ENABLED, NOW() " + - "FROM " + SOURCE_DB + ".DM_OPERATION OPR " + + "OPR.OPERATION_CODE, OPR.INITIATED_BY, OPR.OPERATION_DETAILS, OPR.OPERATION_PROPERTIES, " + + "OPR.ENABLED, NOW() " + + "FROM " + SOURCE_DB + ".DM_OPERATION OPR " + "WHERE OPR.ID NOT IN (SELECT DISTINCT OPERATION_ID FROM " + SOURCE_DB + ".DM_ENROLMENT_OP_MAPPING)"; long startTime = System.currentTimeMillis(); 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/authorization/DeviceAccessAuthorizationServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java index 20460dcdf3..137f79eb22 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java @@ -64,41 +64,55 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori return !DeviceManagementDataHolder.getInstance().requireDeviceAuthorization(deviceIdentifier.getType()); } //check for admin and ownership permissions - if (isAdmin(username, tenantId) || isDeviceOwner(deviceIdentifier, username)) { + if (isDeviceAdminUser(username, tenantId) || isDeviceOwner(deviceIdentifier, username)) { return true; } //check for group permissions - try { - return isSharedViaGroup(deviceIdentifier, username); - } catch (GroupManagementException | UserStoreException e) { - throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + - deviceIdentifier.getId() + " for the user : " + - username, e); - } - } - - private boolean isSharedViaGroup(DeviceIdentifier deviceIdentifier, String username) - throws GroupManagementException, UserStoreException { - List groupsWithDevice = DeviceManagementDataHolder.getInstance() - .getGroupManagementProviderService().getGroups(deviceIdentifier, false); - String[] userRoles = DeviceManagementDataHolder.getInstance().getRealmService() - .getTenantUserRealm(getTenantId()).getUserStoreManager().getRoleListOfUser(username); - for (DeviceGroup deviceGroup : groupsWithDevice) { - List sharingRoles = DeviceManagementDataHolder.getInstance() - .getGroupManagementProviderService().getRoles(deviceGroup.getGroupId()); - for (String role : userRoles) { - if (sharingRoles.contains(role)) { - return true; + if (groupPermissions == null || groupPermissions.length == 0) { + return false; + } else { + // if group permissions specified, check whether that permission is available in shared role + try { + boolean isAuthorized = true; + for (String groupPermission : groupPermissions) { + if (!isAuthorizedViaSharedGroup(deviceIdentifier, username, groupPermission)) { + //if at least one failed, authorizations fails and break the loop + isAuthorized = false; + break; + } } + return isAuthorized; + } catch (DeviceAccessAuthorizationException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + + deviceIdentifier.getId() + " for the user : " + + username, e); } } - return false; } - @Override - public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username) + + private boolean isAuthorizedViaSharedGroup(DeviceIdentifier deviceIdentifier, String username, String groupPermission) throws DeviceAccessAuthorizationException { - return isUserAuthorized(deviceIdentifier, username, null); + try { + List groupsWithDevice = DeviceManagementDataHolder.getInstance() + .getGroupManagementProviderService().getGroups(deviceIdentifier, false); + UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService() + .getTenantUserRealm(getTenantId()); + String[] userRoles = userRealm.getUserStoreManager().getRoleListOfUser(username); + for (DeviceGroup deviceGroup : groupsWithDevice) { + List sharingRoles = DeviceManagementDataHolder.getInstance() + .getGroupManagementProviderService().getRoles(deviceGroup.getGroupId()); + for (String role : userRoles) { + if (sharingRoles.contains(role) && userRealm.getAuthorizationManager(). + isRoleAuthorized(role, groupPermission, CarbonConstants.UI_PERMISSION_ACTION)) { + return true; + } + } + } + return false; + } catch (GroupManagementException | UserStoreException e) { + throw new DeviceAccessAuthorizationException("unable to authorized via shared role, " + groupPermission); + } } @Override @@ -107,18 +121,13 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori return isUserAuthorized(deviceIdentifier, this.getUserName(), groupPermissions); } - @Override - public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException { - return isUserAuthorized(deviceIdentifier, this.getUserName(), null); - } - @Override public boolean isDeviceAdminUser() throws DeviceAccessAuthorizationException { String username = this.getUserName(); int tenantId = this.getTenantId(); try { - return isAdminUser(username, tenantId); - } catch (UserStoreException e) { + return isDeviceAdminUser(username, tenantId); + } catch (DeviceAccessAuthorizationException e) { throw new DeviceAccessAuthorizationException("Unable to check the admin permissions of user : " + username + " in tenant : " + tenantId, e); } @@ -133,7 +142,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori return null; } DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult(); - if (isAdmin(username, tenantId)) { + if (isDeviceAdminUser(username, tenantId)) { deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers); return deviceAuthorizationResult; } @@ -150,7 +159,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori //check for group permissions boolean isAuthorized = true; for (String groupPermission : groupPermissions) { - if (!isAuthorizedViaGroup(username, deviceIdentifier, groupPermission)) { + if (!isAuthorizedViaSharedGroup(deviceIdentifier, username, groupPermission)) { //if at least one failed, authorizations fails and break the loop isAuthorized = false; break; @@ -161,7 +170,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori } else { deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier); } - } catch (GroupManagementException e) { + } catch (DeviceAccessAuthorizationException e) { throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " + deviceIdentifier.getId() + " for the user : " + username, e); @@ -171,55 +180,12 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori return deviceAuthorizationResult; } - @Override - public DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers, String username) - throws DeviceAccessAuthorizationException { - return isUserAuthorized(deviceIdentifiers, username, null); - } - - @Override - public DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers) - throws DeviceAccessAuthorizationException { - return isUserAuthorized(deviceIdentifiers, this.getUserName(), null); - } - @Override public DeviceAuthorizationResult isUserAuthorized(List deviceIdentifiers, String[] groupPermissions) throws DeviceAccessAuthorizationException { return isUserAuthorized(deviceIdentifiers, this.getUserName(), groupPermissions); } - private boolean isAdmin(String username, int tenantId) - throws DeviceAccessAuthorizationException { - try { - //Check for admin users. If the user is an admin user we authorize the access to that device. - return (isAdminUser(username, tenantId)); - } catch (UserStoreException e) { - throw new DeviceAccessAuthorizationException("Unable to authorize the access for the user : " + - username, e); - } - } - - private boolean isAuthorizedViaGroup(String username, DeviceIdentifier deviceIdentifier, String groupPermission) - throws GroupManagementException { - List authorizedGroups = - DeviceManagementDataHolder.getInstance().getGroupManagementProviderService() - .getGroups(username, groupPermission, false); - List groupsWithDevice = - DeviceManagementDataHolder.getInstance().getGroupManagementProviderService() - .getGroups(deviceIdentifier, false); - for (DeviceGroup group : authorizedGroups) { - Iterator groupsWithDeviceIterator = groupsWithDevice.iterator(); - while (groupsWithDeviceIterator.hasNext()) { - DeviceGroup deviceGroup = groupsWithDeviceIterator.next(); - if (deviceGroup.getGroupId() == group.getGroupId()) { - return true; - } - } - } - return false; - } - private boolean isDeviceOwner(DeviceIdentifier deviceIdentifier, String username) throws DeviceAccessAuthorizationException { //Check for device ownership. If the user is the owner of the device we allow the access. @@ -233,15 +199,20 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori } } - private boolean isAdminUser(String username, int tenantId) throws UserStoreException { - UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); - if (userRealm != null && userRealm.getAuthorizationManager() != null) { - return userRealm.getAuthorizationManager() - .isUserAuthorized(removeTenantDomain(username), - PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION), - CarbonConstants.UI_PERMISSION_ACTION); + private boolean isDeviceAdminUser(String username, int tenantId) throws DeviceAccessAuthorizationException { + try { + UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); + if (userRealm != null && userRealm.getAuthorizationManager() != null) { + return userRealm.getAuthorizationManager() + .isUserAuthorized(removeTenantDomain(username), + PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION), + CarbonConstants.UI_PERMISSION_ACTION); + } + return false; + } catch (UserStoreException e) { + throw new DeviceAccessAuthorizationException("Unable to authorize the access for the user : " + + username, e); } - return false; } private String getUserName() { 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/authorization/GroupAccessAuthorizationServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/authorization/GroupAccessAuthorizationServiceImpl.java new file mode 100644 index 0000000000..acceb466c1 --- /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/authorization/GroupAccessAuthorizationServiceImpl.java @@ -0,0 +1,173 @@ +/* + * 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.authorization; + +import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationException; +import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService; +import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAuthorizationResult; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.Permission; +import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.opensaml.xmlsec.signature.G; +import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; + +import javax.persistence.criteria.CriteriaBuilder; +import java.util.List; + +public class GroupAccessAuthorizationServiceImpl implements GroupAccessAuthorizationService { + + private final static String GROUP_ADMIN_PERMISSION = "/device-mgt/devices/any-group/permitted-actions-under-owning-group"; + private final static String GROUP_ADMIN = "Group Management Administrator"; + private static Log log = LogFactory.getLog(DeviceAccessAuthorizationServiceImpl.class); + + public GroupAccessAuthorizationServiceImpl() { + try { + this.addAdminPermissionToRegistry(); + } catch (PermissionManagementException e) { + log.error("Unable to add the group-admin permission to the registry.", e); + } + } + + @Override + public boolean isUserAuthorized(int groupId, String username, String[] groupPermissions) + throws GroupAccessAuthorizationException { + int tenantId = this.getTenantId(); + if (username == null || username.isEmpty()) { + username = this.getUserName(); + } + //check for admin and ownership permissions + if (isGroupAdminUser(username, tenantId) || isGroupOwner(groupId, username)) { + return true; + } + + //check for group permissions + if (groupPermissions == null || groupPermissions.length == 0) { + return false; + } else { + // if group permissions specified, check whether that permission is available in any user role of the group owner + try { + UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService() + .getTenantUserRealm(getTenantId()); + String[] userRoles = userRealm.getUserStoreManager().getRoleListOfUser(username); + boolean isAuthorized = true; + for (String groupPermission : groupPermissions) { + for (String role : userRoles) { + if (!userRealm.getAuthorizationManager(). + isRoleAuthorized(role, groupPermission, CarbonConstants.UI_PERMISSION_ACTION)) { + isAuthorized = false; + break; + } + } + } + return isAuthorized; + } catch (UserStoreException e) { + throw new GroupAccessAuthorizationException("Unable to authorize the access to group : " + + groupId + " for the user : " + + username, e); + } + } + } + + @Override + public GroupAuthorizationResult isUserAuthorized(List groupIds, String username, String[] groupPermission) + throws GroupAccessAuthorizationException { + GroupAuthorizationResult result = new GroupAuthorizationResult(); + for (Integer groupId : groupIds) { + if (isUserAuthorized(groupId, username, groupPermission)) { + result.addAuthorizedGroupId(groupId); + } else { + result.addUnauthorizedGroupId(groupId); + } + } + return result; + } + + + @Override + public boolean isUserAuthorized(int groupId, String[] groupPermissions) + throws GroupAccessAuthorizationException { + return isUserAuthorized(groupId, this.getUserName(), groupPermissions); + } + + private boolean isGroupOwner(int groupId, String username) + throws GroupAccessAuthorizationException { + //Check for group ownership. If the user is the owner of the group we allow the access. + try { + DeviceGroup group = DeviceManagementDataHolder.getInstance(). + getGroupManagementProviderService().getGroup(groupId, false); + return username.equals(group.getOwner()); + } catch (GroupManagementException e) { + throw new GroupAccessAuthorizationException("Unable to authorize the access to group : " + + groupId + " for the user : " + + username, e); + } + } + + private boolean isGroupAdminUser(String username, int tenantId) throws GroupAccessAuthorizationException { + try { + UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); + if (userRealm != null && userRealm.getAuthorizationManager() != null) { + return userRealm.getAuthorizationManager() + .isUserAuthorized(removeTenantDomain(username), + PermissionUtils.getAbsolutePermissionPath(GROUP_ADMIN_PERMISSION), + CarbonConstants.UI_PERMISSION_ACTION); + } + return false; + } catch (UserStoreException e) { + throw new GroupAccessAuthorizationException("Unable to authorize the access for the user : " + + username, e); + } + } + + private String getUserName() { + String username = CarbonContext.getThreadLocalCarbonContext().getUsername(); + if (username != null && !username.isEmpty()) { + return removeTenantDomain(username); + } + return null; + } + + private String removeTenantDomain(String username) { + String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + if (username.endsWith(tenantDomain)) { + return username.substring(0, username.lastIndexOf("@")); + } + return username; + } + + private int getTenantId() { + return CarbonContext.getThreadLocalCarbonContext().getTenantId(); + } + + private boolean addAdminPermissionToRegistry() throws PermissionManagementException { + Permission permission = new Permission(); + permission.setName(GROUP_ADMIN); + permission.setPath(PermissionUtils.getAbsolutePermissionPath(GROUP_ADMIN_PERMISSION)); + return PermissionUtils.putPermission(permission); + } + +} 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 1b2a48662a..695a6a64c9 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 @@ -27,6 +27,7 @@ import io.entgra.device.mgt.core.device.mgt.core.config.datasource.JNDILookupDef import io.entgra.device.mgt.core.device.mgt.core.dao.impl.ApplicationDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.DeviceStatusDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.DeviceTypeDAOImpl; +import io.entgra.device.mgt.core.device.mgt.core.dao.impl.TenantDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.device.GenericDeviceDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.device.OracleDeviceDAOImpl; import io.entgra.device.mgt.core.device.mgt.core.dao.impl.device.PostgreSQLDeviceDAOImpl; @@ -141,6 +142,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 1fac9ae6ae..d6f6af0a73 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 @@ -1260,33 +1260,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(); @@ -1298,9 +1301,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 d3681a43c4..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 @@ -18,6 +18,8 @@ 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; @@ -29,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; @@ -54,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 { @@ -86,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(); @@ -203,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); } } @@ -217,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) @@ -235,10 +261,12 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { String username = CarbonContext.getThreadLocalCarbonContext().getUsername(); if (StringUtils.isEmpty(username)) { + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; boolean isUserAuthorized = DeviceManagementDataHolder.getInstance(). getDeviceAccessAuthorizationService().isUserAuthorized( new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()), - device.getEnrolmentInfo().getOwner() + device.getEnrolmentInfo().getOwner(), requiredPermissions ); if (isUserAuthorized) { username = device.getEnrolmentInfo().getOwner(); @@ -252,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) { @@ -270,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/internal/DeviceManagementDataHolder.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java index 969e3ad2d8..f9ea261793 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.device.mgt.core.internal; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; +import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -78,6 +79,7 @@ public class DeviceManagementDataHolder { private ConfigurationContextService configurationContextService; private final HashMap requireDeviceAuthorization = new HashMap<>(); private DeviceAccessAuthorizationService deviceAccessAuthorizationService; + private GroupAccessAuthorizationService groupAccessAuthorizationService; private GroupManagementProviderService groupManagementProviderService; private TaskService taskService; private EmailSenderService emailSenderService; @@ -447,4 +449,12 @@ public class DeviceManagementDataHolder { public void setPublisherRESTAPIServices(PublisherRESTAPIServices publisherRESTAPIServices) { this.publisherRESTAPIServices = publisherRESTAPIServices; } + + public GroupAccessAuthorizationService getGroupAccessAuthorizationService() { + return groupAccessAuthorizationService; + } + + public void setGroupAccessAuthorizationService(GroupAccessAuthorizationService groupAccessAuthorizationService) { + this.groupAccessAuthorizationService = groupAccessAuthorizationService; + } } 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/internal/DeviceManagementServiceComponent.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementServiceComponent.java index 99d4eabf10..bb66eb3d20 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -17,7 +17,9 @@ */ package io.entgra.device.mgt.core.device.mgt.core.internal; +import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; +import io.entgra.device.mgt.core.device.mgt.core.authorization.GroupAccessAuthorizationServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.DeviceStatusManagementServiceImpl; import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import org.apache.commons.logging.Log; @@ -308,6 +310,12 @@ public class DeviceManagementServiceComponent { bundleContext.registerService(DeviceAccessAuthorizationService.class.getName(), deviceAccessAuthorizationService, null); + /* Registering GroupAccessAuthorization Service */ + GroupAccessAuthorizationService groupAccessAuthorizationService = new GroupAccessAuthorizationServiceImpl(); + DeviceManagementDataHolder.getInstance().setGroupAccessAuthorizationService(groupAccessAuthorizationService); + bundleContext.registerService(GroupAccessAuthorizationService.class.getName(), + groupAccessAuthorizationService, null); + /* Registering Geo Service */ GeoLocationProviderService geoService = new GeoLocationProviderServiceImpl(); DeviceManagementDataHolder.getInstance().setGeoLocationProviderService(geoService); 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/mgt/OperationManagerImpl.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/mgt/OperationManagerImpl.java index f7752d30dc..c2d98755f0 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/mgt/OperationManagerImpl.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/mgt/OperationManagerImpl.java @@ -18,6 +18,15 @@ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt; +import com.google.gson.Gson; +import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; +import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.device.mgt.core.notification.logger.DeviceConnectivityLogContext; +import io.entgra.device.mgt.core.notification.logger.impl.EntgraDeviceConnectivityLoggerImpl; +import io.entgra.device.mgt.core.notification.logger.impl.EntgraPolicyLoggerImpl; +import org.apache.commons.lang.StringUtils; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.ActivityPaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; @@ -221,7 +230,7 @@ public class OperationManagerImpl implements OperationManager { if (operationDto.getControl() == io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) { Map pendingOperationIDs = operationDAO - .getExistingOperationIDs(enrolments.keySet().toArray(new Integer[0]), operationCode); + .getExistingNotExecutedOperationIDs(enrolments.keySet().toArray(new Integer[0]), operationCode); for (Integer enrolmentId : pendingOperationIDs.keySet()) { operation.setId(pendingOperationIDs.get(enrolmentId)); device = enrolments.get(enrolmentId); @@ -293,7 +302,7 @@ public class OperationManagerImpl implements OperationManager { if (operationDto.getControl() == io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) { Map pendingOperationIDs = operationDAO - .getExistingOperationIDs(enrolments.keySet().toArray(new Integer[0]), operationCode); + .getExistingNotExecutedOperationIDs(enrolments.keySet().toArray(new Integer[0]), operationCode); Device device; for (Integer enrolmentId : pendingOperationIDs.keySet()) { operation.setId(pendingOperationIDs.get(enrolmentId)); @@ -367,7 +376,7 @@ public class OperationManagerImpl implements OperationManager { if (operationDto.getControl() == io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) { Map pendingOperationIDs = operationDAO - .getExistingOperationIDs(enrolments.keySet().toArray(new Integer[0]), operationCode); + .getExistingNotExecutedOperationIDs(enrolments.keySet().toArray(new Integer[0]), operationCode); Device device; for (Integer enrolmentId : pendingOperationIDs.keySet()) { operation.setId(pendingOperationIDs.get(enrolmentId)); @@ -561,9 +570,11 @@ public class OperationManagerImpl implements OperationManager { } else { boolean isAuthorized; authorizedDeviceList = new ArrayList<>(); + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; for (DeviceIdentifier devId : deviceIds) { isAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). - isUserAuthorized(devId); + isUserAuthorized(devId, requiredPermissions); if (isAuthorized) { authorizedDeviceList.add(devId); } else { @@ -845,23 +856,23 @@ public class OperationManagerImpl implements OperationManager { } if (dtoOperation != null) { - if (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND.equals(dtoOperation.getType() - )) { - io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; - commandOperation = - (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(dtoOperation.getId()); - dtoOperation.setEnabled(commandOperation.isEnabled()); - } else if (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG.equals(dtoOperation. - getType())) { - dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); - } else if (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE.equals(dtoOperation. - getType())) { - dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); - } else if (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY.equals(dtoOperation. - getType())) { - dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); - } +// if (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND.equals(dtoOperation.getType() +// )) { +// io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; +// commandOperation = +// (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. +// getOperation(dtoOperation.getId()); +// dtoOperation.setEnabled(commandOperation.isEnabled()); +// } else if (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG.equals(dtoOperation. +// getType())) { +// dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); +// } else if (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE.equals(dtoOperation. +// getType())) { +// dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); +// } else if (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY.equals(dtoOperation. +// getType())) { +// dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); +// } operation = OperationDAOUtil.convertOperation(dtoOperation); } } catch (OperationManagementDAOException e) { @@ -1054,29 +1065,29 @@ public class OperationManagerImpl implements OperationManager { io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation deviceSpecificOperation = operationDAO. getOperationByDeviceAndId(enrolmentInfo.getId(), operationId); - io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation dtoOperation = deviceSpecificOperation; - if (deviceSpecificOperation.getType(). - equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { - io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; - commandOperation = - (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(deviceSpecificOperation.getId()); - dtoOperation.setEnabled(commandOperation.isEnabled()); - } else if (deviceSpecificOperation.getType(). - equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { - dtoOperation = configOperationDAO.getOperation(deviceSpecificOperation.getId()); - } else if (deviceSpecificOperation.getType().equals( - io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) { - dtoOperation = profileOperationDAO.getOperation(deviceSpecificOperation.getId()); - } else if (deviceSpecificOperation.getType().equals( - io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY)) { - dtoOperation = policyOperationDAO.getOperation(deviceSpecificOperation.getId()); - } - if (dtoOperation == null) { - throw new OperationManagementException("Operation not found for operation Id:" + operationId + - " device id:" + deviceId.getId()); - } - dtoOperation.setStatus(deviceSpecificOperation.getStatus()); +// io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation dtoOperation = deviceSpecificOperation; +// if (deviceSpecificOperation.getType(). +// equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { +// io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; +// commandOperation = +// (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. +// getOperation(deviceSpecificOperation.getId()); +// dtoOperation.setEnabled(commandOperation.isEnabled()); +// } else if (deviceSpecificOperation.getType(). +// equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { +// dtoOperation = configOperationDAO.getOperation(deviceSpecificOperation.getId()); +// } else if (deviceSpecificOperation.getType().equals( +// io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE)) { +// dtoOperation = profileOperationDAO.getOperation(deviceSpecificOperation.getId()); +// } else if (deviceSpecificOperation.getType().equals( +// io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY)) { +// dtoOperation = policyOperationDAO.getOperation(deviceSpecificOperation.getId()); +// } +// if (dtoOperation == null) { +// throw new OperationManagementException("Operation not found for operation Id:" + operationId + +// " device id:" + deviceId.getId()); +// } +// dtoOperation.setStatus(deviceSpecificOperation.getStatus()); operation = OperationDAOUtil.convertOperation(deviceSpecificOperation); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the list of " + @@ -1159,23 +1170,23 @@ public class OperationManagerImpl implements OperationManager { throw new OperationManagementException("Operation not found for given Id:" + operationId); } - if (dtoOperation.getType() - .equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { - io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; - commandOperation = - (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(dtoOperation.getId()); - dtoOperation.setEnabled(commandOperation.isEnabled()); - } else if (dtoOperation.getType(). - equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { - dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); - } else if (dtoOperation.getType().equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type. - PROFILE)) { - dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); - } else if (dtoOperation.getType().equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type. - POLICY)) { - dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); - } +// if (dtoOperation.getType() +// .equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { +// io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; +// commandOperation = +// (io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. +// getOperation(dtoOperation.getId()); +// dtoOperation.setEnabled(commandOperation.isEnabled()); +// } else if (dtoOperation.getType(). +// equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { +// dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); +// } else if (dtoOperation.getType().equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type. +// PROFILE)) { +// dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); +// } else if (dtoOperation.getType().equals(io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation.Type. +// POLICY)) { +// dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); +// } operation = OperationDAOUtil.convertOperation(dtoOperation); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the operation with operation Id '" + @@ -1477,9 +1488,11 @@ public class OperationManagerImpl implements OperationManager { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); String user = this.getUser(); boolean isUserAuthorized; + String requiredPermission = PermissionManagerServiceImpl.getInstance().getRequiredPermission(); + String[] requiredPermissions = new String[] {requiredPermission}; try { isUserAuthorized = DeviceManagementDataHolder.getInstance() - .getDeviceAccessAuthorizationService().isUserAuthorized(deviceId, user); + .getDeviceAccessAuthorizationService().isUserAuthorized(deviceId, user, requiredPermissions); } catch (DeviceAccessAuthorizationException e) { throw new OperationManagementException("Error occurred while checking the device access permissions for '" + deviceId.getType() + "' device carrying the identifier '" + 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/mgt/dao/OperationDAO.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/mgt/dao/OperationDAO.java index 4fe22494c6..4abaf40022 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/mgt/dao/OperationDAO.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/mgt/dao/OperationDAO.java @@ -62,7 +62,7 @@ public interface OperationDAO { void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, Operation.Status existingStatus, Operation.Status newStatus) throws OperationManagementDAOException; - Map getExistingOperationIDs(Integer[] enrolmentIds, String operationCode) + Map getExistingNotExecutedOperationIDs(Integer[] enrolmentIds, String operationCode) throws OperationManagementDAOException; OperationResponseMeta addOperationResponse(int enrolmentId, io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation operation, String deviceId) 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/mgt/dao/impl/GenericOperationDAOImpl.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/mgt/dao/impl/GenericOperationDAOImpl.java index afde6acc6a..ddb77a24a4 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/mgt/dao/impl/GenericOperationDAOImpl.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/mgt/dao/impl/GenericOperationDAOImpl.java @@ -53,8 +53,13 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; -import java.util.*; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -71,15 +76,16 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection connection = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, " + - "INITIATED_BY, OPERATION_DETAILS, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?)"; + "INITIATED_BY, OPERATION_DETAILS, OPERATION_PROPERTIES, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; stmt = connection.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, operation.getType().toString()); stmt.setLong(2, DeviceManagementDAOUtil.getCurrentUTCTime()); stmt.setLong(3, 0); stmt.setString(4, operation.getCode()); stmt.setString(5, operation.getInitiatedBy()); - stmt.setObject(6, operation); - stmt.setInt(7, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.setObject(6, operation.getPayLoad()); + stmt.setObject(7, operation.getProperties()); + stmt.setInt(8, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); @@ -160,7 +166,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } @Override - public Map getExistingOperationIDs(Integer[] enrolmentIds, String operationCode) + public Map getExistingNotExecutedOperationIDs(Integer[] enrolmentIds, String operationCode) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; @@ -572,7 +578,7 @@ public class GenericOperationDAOImpl implements OperationDAO { + "dor.ID AS OP_RES_ID, de.DEVICE_ID, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID, " + "dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, " + "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, " - + "dor.OPERATION_RESPONSE, op.INITIATED_BY, dor.RECEIVED_TIMESTAMP, dor.IS_LARGE_RESPONSE FROM " + + "dor.OPERATION_RESPONSE, op.INITIATED_BY, dor.RECEIVED_TIMESTAMP, dor.IS_LARGE_RESPONSE FROM " + "DM_ENROLMENT_OP_MAPPING eom INNER JOIN DM_OPERATION op " + "ON op.ID=eom.OPERATION_ID INNER JOIN DM_ENROLMENT de " + "ON de.ID=eom.ENROLMENT_ID INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID " @@ -1185,24 +1191,14 @@ public class GenericOperationDAOImpl implements OperationDAO { Operation operation = null; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, INITIATED_BY FROM " + - "DM_OPERATION WHERE id = ?"; + String sql = "SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, INITIATED_BY, " + + "OPERATION_DETAILS, OPERATION_PROPERTIES FROM DM_OPERATION WHERE id = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); if (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); - if (rs.getLong("RECEIVED_TIMESTAMP") == 0) { - operation.setReceivedTimeStamp(""); - } else { - operation.setReceivedTimeStamp(new Timestamp(rs.getLong("RECEIVED_TIMESTAMP") * 1000L).toString()); - } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setInitiatedBy(rs.getString("INITIATED_BY")); + operation = OperationDAOUtil.getOperation(rs); } } catch (SQLException e) { @@ -1215,16 +1211,19 @@ public class GenericOperationDAOImpl implements OperationDAO { } @Override - public Operation getOperationByDeviceAndId(int enrolmentId, int operationId) throws OperationManagementDAOException { + public Operation getOperationByDeviceAndId(int enrolmentId, int operationId) + throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; Operation operation = null; try { Connection conn = OperationManagementDAOFactory.getConnection(); String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, om.STATUS, " + - "o.OPERATION_CODE, o.INITIATED_BY, om.ID AS OM_MAPPING_ID, " + - "om.UPDATED_TIMESTAMP FROM (SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP," + - "OPERATION_CODE, INITIATED_BY FROM DM_OPERATION WHERE id = ?) o INNER JOIN (SELECT * FROM " + + "o.OPERATION_CODE, o.INITIATED_BY, o.OPERATION_DETAILS, o.OPERATION_PROPERTIES, " + + "om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP, om.STATUS FROM " + + "(SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP," + + "OPERATION_CODE, INITIATED_BY, OPERATION_DETAILS, OPERATION_PROPERTIES FROM DM_OPERATION " + + "WHERE id = ?) o INNER JOIN (SELECT * FROM " + "DM_ENROLMENT_OP_MAPPING dm where dm.OPERATION_ID = ? AND dm.ENROLMENT_ID = ?) om " + "ON o.ID = om.OPERATION_ID "; stmt = conn.prepareStatement(sql); @@ -1234,20 +1233,14 @@ public class GenericOperationDAOImpl implements OperationDAO { rs = stmt.executeQuery(); if (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); - operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + operation = OperationDAOUtil.getOperation(rs); if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { operation.setReceivedTimeStamp( new Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setInitiatedBy(rs.getString("INITIATED_BY")); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); } } catch (SQLException e) { throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + @@ -1268,7 +1261,8 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection conn = OperationManagementDAOFactory.getConnection(); String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.OPERATION_CODE, " + - "o.INITIATED_BY, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + + "o.INITIATED_BY, o.OPERATION_DETAILS, o.OPERATION_PROPERTIES, om.ID AS OM_MAPPING_ID, " + + "om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC"; stmt = conn.prepareStatement(sql); @@ -1277,20 +1271,14 @@ public class GenericOperationDAOImpl implements OperationDAO { rs = stmt.executeQuery(); while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); + operation = OperationDAOUtil.getOperation(rs); + operation.setStatus(status); if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { operation.setReceivedTimeStamp( new Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setInitiatedBy(rs.getString("INITIATED_BY")); - operation.setStatus(status); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); operations.add(operation); } } catch (SQLException e) { @@ -1313,7 +1301,8 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection conn = OperationManagementDAOFactory.getConnection(); String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.OPERATION_CODE, " + - "o.INITIATED_BY, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + + "o.INITIATED_BY, o.OPERATION_DETAILS, o.OPERATION_PROPERTIES, om.ID AS OM_MAPPING_ID, " + + "om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + "o.CREATED_TIMESTAMP DESC LIMIT ?,?"; @@ -1325,20 +1314,15 @@ public class GenericOperationDAOImpl implements OperationDAO { rs = stmt.executeQuery(); while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); + operation = OperationDAOUtil.getOperation(rs); + operation.setStatus(status); if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { operation.setReceivedTimeStamp( new Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setInitiatedBy(rs.getString("INITIATED_BY")); operation.setStatus(status); - OperationDAOUtil.setActivityId(operation, rs.getInt("OM_MAPPING_ID")); operations.add(operation); } } catch (SQLException e) { @@ -1360,7 +1344,8 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection conn = OperationManagementDAOFactory.getConnection(); String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + - "o.OPERATION_CODE, o.INITIATED_BY, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP " + + "o.OPERATION_CODE, o.INITIATED_BY, o.OPERATION_DETAILS, o.OPERATION_PROPERTIES, om.STATUS, " + + "om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP " + "FROM DM_OPERATION o INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID " + "ORDER BY o.CREATED_TIMESTAMP DESC, o.ID DESC"; @@ -1369,18 +1354,13 @@ public class GenericOperationDAOImpl implements OperationDAO { rs = stmt.executeQuery(); while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); + operation = OperationDAOUtil.getOperation(rs); if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { operation.setReceivedTimeStamp( new Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setInitiatedBy(rs.getString("INITIATED_BY")); operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); operations.add(operation); } @@ -1424,6 +1404,7 @@ public class GenericOperationDAOImpl implements OperationDAO { "o.OPERATION_CODE, " + "o.INITIATED_BY, " + "o.OPERATION_DETAILS, " + + "o.OPERATION_PROPERTIES, " + "om.STATUS, " + "om.ID AS OM_MAPPING_ID, " + "om.UPDATED_TIMESTAMP " + @@ -1510,36 +1491,14 @@ public class GenericOperationDAOImpl implements OperationDAO { stmt.setInt(paramIndex, request.getRowCount()); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); + operation = OperationDAOUtil.getOperation(rs); if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { operation.setReceivedTimeStamp( new Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setInitiatedBy(rs.getString("INITIATED_BY")); - if (MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL.equals(operation.getCode())) { - byte[] operationDetails = rs.getBytes("OPERATION_DETAILS"); - try (ByteArrayInputStream bais = new ByteArrayInputStream(operationDetails); - ObjectInputStream ois = new ObjectInputStream(bais)) { - profileOperation = (ProfileOperation) ois.readObject(); - operation.setPayLoad(profileOperation.getPayLoad()); - } catch (IOException e) { - String msg = "IO Error occurred while retrieving app data of operation "; - log.error(msg, e); - throw new OperationManagementDAOException(msg, e); - } catch (ClassNotFoundException e) { - String msg = "Class not found error occurred while retrieving app data of operation "; - log.error(msg, e); - throw new OperationManagementDAOException(msg, e); - } - } operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); operations.add(operation); } } @@ -1558,7 +1517,6 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList<>(); String createdTo = null; String createdFrom = null; - ProfileOperation profileOperation = null; DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); boolean isCreatedDayProvided = false; boolean isUpdatedDayProvided = false; //updated day = received day @@ -1582,6 +1540,7 @@ public class GenericOperationDAOImpl implements OperationDAO { "o.OPERATION_CODE, " + "o.INITIATED_BY, " + "o.OPERATION_DETAILS, " + + "o.OPERATION_PROPERTIES, " + "om.STATUS, " + "om.ID AS OM_MAPPING_ID, " + "om.UPDATED_TIMESTAMP " + @@ -1668,36 +1627,14 @@ public class GenericOperationDAOImpl implements OperationDAO { stmt.setInt(paramIndex, request.getRowCount()); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); + operation = OperationDAOUtil.getOperation(rs); if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { operation.setReceivedTimeStamp( new Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setInitiatedBy(rs.getString("INITIATED_BY")); - if (MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL.equals(operation.getCode())) { - byte[] operationDetails = rs.getBytes("OPERATION_DETAILS"); - try (ByteArrayInputStream bais = new ByteArrayInputStream(operationDetails); - ObjectInputStream ois = new ObjectInputStream(bais)) { - profileOperation = (ProfileOperation) ois.readObject(); - operation.setPayLoad(profileOperation.getPayLoad()); - } catch (IOException e) { - String msg = "IO Error occurred while retrieving app data of operation "; - log.error(msg, e); - throw new OperationManagementDAOException(msg, e); - } catch (ClassNotFoundException e) { - String msg = "Class not found error occurred while retrieving app data of operation "; - log.error(msg, e); - throw new OperationManagementDAOException(msg, e); - } - } operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); operations.add(operation); } } @@ -1928,7 +1865,8 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection connection = OperationManagementDAOFactory.getConnection(); stmt = connection.prepareStatement("SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + - "o.OPERATION_CODE, o.INITIATED_BY, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + + "o.OPERATION_CODE, o.INITIATED_BY, o.OPERATION_DETAILS, o.OPERATION_PROPERTIES, " + + "om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID " + "ORDER BY om.UPDATED_TIMESTAMP ASC, om.ID ASC LIMIT 1"); @@ -1938,21 +1876,14 @@ public class GenericOperationDAOImpl implements OperationDAO { Operation operation = null; if (rs.next()) { - operation = new Operation(); - operation.setType(OperationDAOUtil.getType(rs.getString("TYPE"))); - operation.setId(rs.getInt("ID")); - operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); - + operation = OperationDAOUtil.getOperation(rs); if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { operation.setReceivedTimeStamp( new Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setInitiatedBy(rs.getString("INITIATED_BY")); operation.setStatus(Operation.Status.PENDING); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); } return operation; } catch (SQLException e) { @@ -1971,8 +1902,9 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, OPERATION_CODE, o.INITIATED_BY," + - " om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM " + + String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, OPERATION_CODE, " + + "o.INITIATED_BY, o.OPERATION_DETAILS, o.OPERATION_PROPERTIES, " + + "om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM " + "(SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, INITIATED_BY " + "FROM DM_OPERATION o WHERE o.TYPE = ?) o INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC"; @@ -1984,19 +1916,14 @@ public class GenericOperationDAOImpl implements OperationDAO { rs = stmt.executeQuery(); while (rs.next()) { - operation = new Operation(); - operation.setId(rs.getInt("ID")); - operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); - operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); + operation = OperationDAOUtil.getOperation(rs); + operation.setStatus(status); if (rs.getLong("UPDATED_TIMESTAMP") == 0) { operation.setReceivedTimeStamp(""); } else { operation.setReceivedTimeStamp( new Timestamp((rs.getLong("UPDATED_TIMESTAMP") * 1000)).toString()); } - operation.setCode(rs.getString("OPERATION_CODE")); - operation.setInitiatedBy(rs.getString("INITIATED_BY")); - OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); operations.add(operation); } } catch (SQLException e) { @@ -2009,7 +1936,8 @@ public class GenericOperationDAOImpl implements OperationDAO { } @Override - public Map> getOperationMappingsByStatus(Operation.Status opStatus, Operation.PushNotificationStatus pushNotificationStatus, + public Map> getOperationMappingsByStatus(Operation.Status opStatus, + Operation.PushNotificationStatus pushNotificationStatus, int limit) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; @@ -2055,7 +1983,8 @@ public class GenericOperationDAOImpl implements OperationDAO { @Override public Map> getAllocatedOperationMappingsByStatus(Operation.Status opStatus, - Operation.PushNotificationStatus pushNotificationStatus, int limit, int activeServerCount, int serverIndex) + Operation.PushNotificationStatus pushNotificationStatus, + int limit, int activeServerCount, int serverIndex) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; @@ -2268,7 +2197,7 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getDeviceType() != null || (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) || activityPaginationRequest.getSince() != 0 || - activityPaginationRequest.getStatus() != null) { + activityPaginationRequest.getStatuses() != null) { sql.append("(SELECT DISTINCT OPERATION_ID FROM DM_ENROLMENT_OP_MAPPING eom WHERE TENANT_ID = ? "); @@ -2301,8 +2230,12 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { sql.append("AND TYPE = ? "); } - if (activityPaginationRequest.getStatus() != null) { - sql.append("AND STATUS = ? "); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + sql.append("AND STATUS IN ("); + for (int i = 0; i < activityPaginationRequest.getStatuses().size() - 1; i++) { + sql.append("?, "); + } + sql.append("?) "); } sql.append("ORDER BY OPERATION_ID ASC limit ? , ? ) eom_ordered " + @@ -2356,8 +2289,12 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { sql.append("AND eom.TYPE = ? "); } - if (activityPaginationRequest.getStatus() != null) { - sql.append("AND eom.STATUS = ? "); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + sql.append("AND eom.STATUS IN ("); + for (int i = 0; i < activityPaginationRequest.getStatuses().size() - 1; i++) { + sql.append("?, "); + } + sql.append("?) "); } sql.append("ORDER BY eom.OPERATION_ID, eom.UPDATED_TIMESTAMP"); @@ -2368,7 +2305,7 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getDeviceType() != null || (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) || activityPaginationRequest.getSince() != 0 || - activityPaginationRequest.getStatus() != null) { + activityPaginationRequest.getStatuses() != null) { if (activityPaginationRequest.getDeviceType() != null) { stmt.setString(index++, activityPaginationRequest.getDeviceType()); @@ -2397,8 +2334,10 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { stmt.setString(index++, activityPaginationRequest.getType().name()); } - if (activityPaginationRequest.getStatus() != null) { - stmt.setString(index++, activityPaginationRequest.getStatus().name()); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + for (io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation.Status status : activityPaginationRequest.getStatuses()) { + stmt.setString(index++, status.name()); + } } stmt.setInt(index++, activityPaginationRequest.getOffset()); @@ -2459,8 +2398,10 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { stmt.setString(index++, activityPaginationRequest.getType().name()); } - if (activityPaginationRequest.getStatus() != null) { - stmt.setString(index, activityPaginationRequest.getStatus().name()); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + for (io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation.Status status : activityPaginationRequest.getStatuses()) { + stmt.setString(index++, status.name()); + } } try (ResultSet rs = stmt.executeQuery()) { @@ -2492,7 +2433,7 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getDeviceType() != null || (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) || activityPaginationRequest.getSince() != 0 || - activityPaginationRequest.getStatus() != null) { + activityPaginationRequest.getStatuses() != null) { sql.append("SELECT count(DISTINCT OPERATION_ID) AS ACTIVITY_COUNT " + "FROM DM_ENROLMENT_OP_MAPPING WHERE TENANT_ID = ? "); @@ -2522,8 +2463,12 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { sql.append("AND TYPE = ? "); } - if (activityPaginationRequest.getStatus() != null) { - sql.append("AND STATUS = ? "); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + sql.append("AND STATUS IN ("); + for (int i = 0; i < activityPaginationRequest.getStatuses().size() - 1; i++) { + sql.append("?, "); + } + sql.append("?) "); } } else { @@ -2551,7 +2496,7 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getDeviceType() != null || (activityPaginationRequest.getDeviceIds() != null && !activityPaginationRequest.getDeviceIds().isEmpty()) || activityPaginationRequest.getSince() != 0 || - activityPaginationRequest.getStatus() != null) { + activityPaginationRequest.getStatuses() != null) { if (activityPaginationRequest.getDeviceType() != null) { stmt.setString(index++, activityPaginationRequest.getDeviceType()); } @@ -2575,8 +2520,10 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { stmt.setString(index++, activityPaginationRequest.getType().name()); } - if (activityPaginationRequest.getStatus() != null) { - stmt.setString(index++, activityPaginationRequest.getStatus().name()); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + for (io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation.Status status : activityPaginationRequest.getStatuses()) { + stmt.setString(index++, status.name()); + } } } else { if (activityPaginationRequest.getOperationCode() != null) { @@ -2658,8 +2605,12 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { sql.append("AND TYPE = ? "); } - if (activityPaginationRequest.getStatus() != null) { - sql.append("AND STATUS = ? "); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + sql.append("AND STATUS IN ("); + for (int i = 0; i < activityPaginationRequest.getStatuses().size() - 1; i++) { + sql.append("?, "); + } + sql.append("?) "); } sql.append("ORDER BY ID ASC limit ? , ? ) eom " + @@ -2696,8 +2647,10 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { stmt.setString(index++, activityPaginationRequest.getType().name()); } - if (activityPaginationRequest.getStatus() != null) { - stmt.setString(index++, activityPaginationRequest.getStatus().name()); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + for (io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation.Status status : activityPaginationRequest.getStatuses()) { + stmt.setString(index++, status.name()); + } } stmt.setInt(index++, activityPaginationRequest.getOffset()); @@ -2740,7 +2693,6 @@ public class GenericOperationDAOImpl implements OperationDAO { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); StringBuilder sql = new StringBuilder(); - sql.append("SELECT count(DISTINCT ID) AS ACTIVITY_COUNT " + "FROM DM_ENROLMENT_OP_MAPPING WHERE TENANT_ID = ? "); @@ -2769,8 +2721,12 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { sql.append("AND TYPE = ? "); } - if (activityPaginationRequest.getStatus() != null) { - sql.append("AND STATUS = ? "); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + sql.append("AND STATUS IN ("); + for (int i = 0; i < activityPaginationRequest.getStatuses().size() - 1; i++) { + sql.append("?, "); + } + sql.append("?) "); } if (activityPaginationRequest.getStartTimestamp() > 0 && activityPaginationRequest.getEndTimestamp() > 0) { @@ -2804,8 +2760,10 @@ public class GenericOperationDAOImpl implements OperationDAO { if (activityPaginationRequest.getType() != null) { stmt.setString(index++, activityPaginationRequest.getType().name()); } - if (activityPaginationRequest.getStatus() != null) { - stmt.setString(index++, activityPaginationRequest.getStatus().name()); + if (activityPaginationRequest.getStatuses() != null && !activityPaginationRequest.getStatuses().isEmpty()) { + for (io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Operation.Status status : activityPaginationRequest.getStatuses()) { + stmt.setString(index++, status.name()); + } } if (isTimeDurationFilteringProvided) { 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/mgt/dao/util/OperationDAOUtil.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/mgt/dao/util/OperationDAOUtil.java index bac0fb0648..4161d7b4c2 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/mgt/dao/util/OperationDAOUtil.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/mgt/dao/util/OperationDAOUtil.java @@ -42,6 +42,7 @@ import java.util.Date; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Properties; import java.util.TreeMap; public class OperationDAOUtil { @@ -328,4 +329,60 @@ public class OperationDAOUtil { deviceActivity.setUpdatedTimestamp(new Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); return deviceActivity; } + + public static Operation getOperation(ResultSet rs) throws OperationManagementDAOException, SQLException { + Operation operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(new Timestamp(rs.getLong("CREATED_TIMESTAMP") * 1000L).toString()); + if (rs.getLong("RECEIVED_TIMESTAMP") == 0) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp( + new Timestamp((rs.getLong("RECEIVED_TIMESTAMP") * 1000)).toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setInitiatedBy(rs.getString("INITIATED_BY")); + byte[] operationDetails = rs.getBytes("OPERATION_DETAILS"); + if (!rs.wasNull()) { + try (ByteArrayInputStream bais = new ByteArrayInputStream(operationDetails); + ObjectInputStream ois = new ObjectInputStream(bais)) { + operation.setPayLoad(ois.readObject()); + } catch (IOException e) { + String msg = "IO Error occurred while retrieving operation details"; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } catch (ClassNotFoundException e) { + String msg = "Class not found error occurred while retrieving operation details"; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } catch (Exception e) { + String msg = "Error occurred while retrieving operation details"; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } + } + byte[] operationProperties = rs.getBytes("OPERATION_PROPERTIES"); + if (!rs.wasNull()) { + try (ByteArrayInputStream bais = new ByteArrayInputStream(operationProperties); + ObjectInputStream ois = new ObjectInputStream(bais)) { + operation.setProperties((Properties) ois.readObject()); + } catch (IOException e) { + String msg = "IO Error occurred while retrieving operation properties"; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } catch (ClassNotFoundException e) { + String msg = "Class not found error occurred while retrieving operation properties"; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } catch (Exception e) { + String msg = "Error occurred while retrieving operation properties"; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); + } + } + OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); + return operation; + } + } 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/permission/mgt/PermissionManagerServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java index 7de2a3a9c9..8b7c9244ad 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java @@ -32,6 +32,7 @@ public class PermissionManagerServiceImpl implements PermissionManagerService { private static PermissionManagerServiceImpl registryBasedPermissionManager; private static APIResourcePermissions apiResourcePermissions; + private ThreadLocal requiredPermission = null; private PermissionManagerServiceImpl() { } @@ -64,4 +65,16 @@ public class PermissionManagerServiceImpl implements PermissionManagerService { public List getPermission(String context) throws PermissionManagementException { return apiResourcePermissions.getPermissions(context); } + + public String getRequiredPermission() { + if (requiredPermission == null) { + requiredPermission = new ThreadLocal<>(); + } + return requiredPermission.get(); + } + + public void setRequiredPermission(String permission) { + requiredPermission = new ThreadLocal<>(); + requiredPermission.set(permission); + } } 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 d0eed42fd1..4488127481 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 @@ -1062,4 +1062,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 47f059446a..853926f8eb 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 */ @@ -5195,4 +5197,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/service/GroupManagementProviderServiceImpl.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/GroupManagementProviderServiceImpl.java index 9bcd5f7e7a..27e8b6bba0 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/GroupManagementProviderServiceImpl.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/GroupManagementProviderServiceImpl.java @@ -17,7 +17,6 @@ */ package io.entgra.device.mgt.core.device.mgt.core.service; - import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; @@ -33,6 +32,20 @@ import io.entgra.device.mgt.core.device.mgt.core.geo.task.GeoFenceEventOperation import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationMgtConstants; import io.entgra.device.mgt.core.device.mgt.core.util.DeviceManagerUtil; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupConstants; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceTypesOfGroups; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupAlreadyExistException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupNotExistException; +import io.entgra.device.mgt.core.device.mgt.common.group.mgt.RoleDoesNotExistException; +import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceDAO; +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.GroupDAO; +import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOFactory; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -581,10 +594,24 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } else { List allDeviceGroupIdsOfUser = getGroupIds(username); rootGroups = this.getGroups(allDeviceGroupIdsOfUser, tenantId); - if (requireGroupProps) { + try { + GroupManagementDAOFactory.openConnection(); for (DeviceGroup rootGroup : rootGroups) { - populateGroupProperties(rootGroup, tenantId); + parentPath = DeviceManagerUtil.createParentPath(rootGroup); + childrenGroups = groupDAO.getChildrenGroups(parentPath, tenantId); + createGroupWithChildren( + rootGroup, childrenGroups, requireGroupProps, tenantId, request.getDepth(), 0); + if (requireGroupProps) { + populateGroupProperties(rootGroup, tenantId); + } } + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source to retrieve all groups " + + "with hierarchy when username is provided"; + log.error(msg, e); + throw new GroupManagementException(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); } } } catch (GroupManagementDAOException 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/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 fe830736a9..cf0faa9391 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 @@ -86,13 +86,13 @@ public abstract class DynamicPartitionedScheduleTask implements Task { if (localHashIndex.equals(String.valueOf(taskContext.getServerHashIndex()))) { if (log.isDebugEnabled()) { log.debug("Executing dynamically scheduled task (" + getTaskName() + - ") for current server hash index: " + localHashIndex); + ") for current server hash index: " + taskContext.getServerHashIndex()); } executeDynamicTask(); } else { if (log.isDebugEnabled()) { log.debug("Ignoring execution of task (" + getTaskName() + - ") not belonging to current serer hash index: " + localHashIndex); + ") not belonging to current server hash index: " + taskContext.getServerHashIndex()); } } } else { 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 005274375a..5f9200fa80 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 @@ -29,6 +29,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; @@ -50,24 +51,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/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java index 4350031c02..10c81e2755 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/authorization/DeviceAccessAuthorizationServiceTest.java @@ -190,7 +190,7 @@ public class DeviceAccessAuthorizationServiceTest { public void userAuthDevIdUserName() throws Exception { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER); for (DeviceIdentifier deviceId : deviceIds) { - Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceId, ADMIN_USER), + Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceId, ADMIN_USER, new String[]{NON_ADMIN_PERMISSION}), "Device access authorization for admin user failed"); } } @@ -199,7 +199,7 @@ public class DeviceAccessAuthorizationServiceTest { public void userAuthDevIdUserNameResult() throws DeviceAccessAuthorizationException { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER); DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService. - isUserAuthorized(deviceIds, ADMIN_USER); + isUserAuthorized(deviceIds, ADMIN_USER, new String[]{NON_ADMIN_PERMISSION}); Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 5, "Expected 5 authorized devices for admin user"); Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0, @@ -210,7 +210,7 @@ public class DeviceAccessAuthorizationServiceTest { public void userAuthDevId() throws Exception { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER); for (DeviceIdentifier deviceId : deviceIds) { - Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceId), + Assert.assertTrue(deviceAccessAuthorizationService.isUserAuthorized(deviceId, new String[]{NON_ADMIN_PERMISSION}), "Authorize user from device identifier failed"); } } @@ -219,7 +219,7 @@ public class DeviceAccessAuthorizationServiceTest { public void userAuthDevIdResult() throws Exception { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER); DeviceAuthorizationResult deviceAuthorizationResult = deviceAccessAuthorizationService. - isUserAuthorized(deviceIds); + isUserAuthorized(deviceIds, new String[]{NON_ADMIN_PERMISSION}); Assert.assertEquals(deviceAuthorizationResult.getAuthorizedDevices().size(), 5, "Expected 5 authorized devices for admin user"); Assert.assertEquals(deviceAuthorizationResult.getUnauthorizedDevices().size(), 0, 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.core/src/test/resources/sql/h2.sql b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql index 8cd5bce74e..9aefaa3229 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql @@ -140,6 +140,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( OPERATION_CODE VARCHAR(1000) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) 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 266a25d121..0d1682bb77 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql index a67b29fa20..4070434f9e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql @@ -70,46 +70,12 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( OPERATION_CODE VARCHAR(1000) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); -CREATE TABLE IF NOT EXISTS DM_CONFIG_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - OPERATION_CONFIG BLOB DEFAULT NULL, - ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_COMMAND_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_command FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_POLICY_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_policy FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_PROFILE_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_profile FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INTEGER NOT NULL, 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 30526524a7..0259952c15 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index 1e9ff562cf..04511dd516 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.41-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 f56e40b647..afdab1034e 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.41-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 adf6351260..03fe012c5d 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 @@ -182,7 +182,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 6791c0f881..4cf88ac8fe 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 @@ -45,6 +45,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(); @@ -53,17 +54,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) { @@ -92,7 +93,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 { @@ -106,7 +107,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(); @@ -116,12 +117,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 { @@ -136,35 +138,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 + " is 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; } @@ -224,7 +198,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); } @@ -235,13 +209,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 { @@ -253,6 +238,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic throw new HeartBeatManagementException(msg); } } + @Override public void notifyClusterFormationChanged(int elapsedTimeInSeconds) throws HeartBeatManagementException { if (HeartBeatBeaconConfig.getInstance().isEnabled()) { @@ -273,7 +259,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); @@ -367,8 +354,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); @@ -391,4 +378,5 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } return activeServers; } + } diff --git a/components/heartbeat-management/pom.xml b/components/heartbeat-management/pom.xml index d30eddcd04..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.41-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 e4794b126e..90cca1b623 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.41-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 8d05b8586d..d148e5350d 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index f1f39df1b7..b5ff1e53de 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.41-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 0f2a80f939..cea7bf2427 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.41-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 946727e504..11da1dcc0d 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.41-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 caf31d200d..9c115b8376 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index 929eb1738a..4e0d108447 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -89,6 +89,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( OPERATION_CODE VARCHAR(1000) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) diff --git a/components/operation-template-mgt/pom.xml b/components/operation-template-mgt/pom.xml index f0b861c909..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.41-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 2f3d785212..c820f790cc 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.41-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 50c25c2982..0269781461 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.41-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 9a8a5af862..0ce9e6c51c 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.41-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 18ebe836d6..2f67e4ebbe 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.41-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/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 c5d661c567..df059cb714 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 @@ -158,6 +158,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/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index 2a8c24a2df..7b1a56acd7 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -136,6 +136,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( OPERATION_CODE VARCHAR(1000) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) diff --git a/components/policy-mgt/pom.xml b/components/policy-mgt/pom.xml index 7775b05fcd..acf5646047 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.41-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 04ed5ee3e9..1c2e2c8aec 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.41-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 6a598bf1f6..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 @@ -27,12 +27,11 @@ 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 4ed402739c..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 @@ -18,24 +18,16 @@ package io.entgra.device.mgt.core.subtype.mgt.util; -import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubType; import io.entgra.device.mgt.core.subtype.mgt.dto.DeviceSubTypeCacheKey; 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 492d35162c..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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/components/task-mgt/pom.xml b/components/task-mgt/pom.xml index f6e60da0e1..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.41-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 29285f6a54..a57bf4e783 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml 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 5c28cc8ee6..bddeafbc64 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.41-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/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 2b5a521507..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 @@ -89,6 +89,7 @@ public class TaskManagementServiceImpl implements TaskManagementService { // add into the dynamic task tables TaskManagementDAOFactory.beginTransaction(); dynamicTaskId = dynamicTaskDAO.addTask(dynamicTask, tenantId); + dynamicTask.setDynamicTaskId(dynamicTaskId); dynamicTaskPropDAO.addTaskProperties(dynamicTaskId, dynamicTask.getProperties(), tenantId); try { diff --git a/components/task-mgt/task-manager/pom.xml b/components/task-mgt/task-manager/pom.xml index a74dafdd10..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.41-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 0784671184..fb063ca6c3 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.41-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 5b1945e686..aed0d3dc8b 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 @@ -45,8 +45,11 @@ import java.util.Timer; import java.util.TimerTask; public class IoTSStartupHandler implements ServerStartupObserver { + private static final Log log = LogFactory.getLog(IoTSStartupHandler.class); + private static int lastHashIndex = -1; + @Override public void completingServerStartup() { } @@ -80,6 +83,22 @@ public class IoTSStartupHandler implements ServerStartupObserver { Map> tenantedDynamicTasks = TaskWatcherDataHolder.getInstance() .getTaskManagementService().getDynamicTasksForAllTenants(); + int serverHashIdx; + try { + serverHashIdx = TaskWatcherDataHolder.getInstance().getHeartBeatService() + .getServerCtxInfo().getLocalServerHashIdx(); + } catch (HeartBeatManagementException e) { + String msg = "Failed to get server hash index."; + log.error(msg, e); + throw new TaskManagementException(msg, e); + } + + if (serverHashIdx != lastHashIndex) { + log.info("Server hash index changed. Old: " + lastHashIndex + ", new: " + serverHashIdx); + deleteAllDynamicNTasks(nTaskService, tenantedDynamicTasks, serverHashIdx); + lastHashIndex = serverHashIdx; + } + scheduleMissingTasks(nTaskService, tenantedDynamicTasks); deleteObsoleteTasks(nTaskService, tenantedDynamicTasks); @@ -96,7 +115,45 @@ public class IoTSStartupHandler implements ServerStartupObserver { } - private static void scheduleMissingTasks(TaskService nTaskService, Map> tenantedDynamicTasks, int serverHashIdx) throws TaskException { + List tenants = getAllTenants(); + + TaskManager taskManager; + + 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)) { + nTaskService.registerTaskType(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE); + } + taskManager = nTaskService.getTaskManager(TaskMgtConstants.Task.DYNAMIC_TASK_TYPE); + List tasks = taskManager.getAllTasks(); + // Remove all applicable dynamic tasks from the nTask core + for (TaskInfo taskInfo : tasks) { + for (DynamicTask dt : tenantedDynamicTasks.get(tenant.getId())) { + if (tenant.getId() == dt.getTenantId() + && taskInfo.getName() + .equals(TaskManagementUtil.generateNTaskName(dt.getDynamicTaskId(), serverHashIdx))) { + taskManager.deleteTask(taskInfo.getName()); + if (log.isDebugEnabled()) { + log.debug("Task '" + taskInfo.getName() + "' deleted as server hash changed."); + } + } + } + } + PrivilegedCarbonContext.endTenantFlow(); + } + } + + private void scheduleMissingTasks(TaskService nTaskService, Map> tenantedDynamicTasks) throws TaskException, TaskManagementException { @@ -187,26 +244,10 @@ public class IoTSStartupHandler implements ServerStartupObserver { } } - private static void deleteObsoleteTasks(TaskService nTaskService, - Map> tenantedDynamicTasks) + private void deleteObsoleteTasks(TaskService nTaskService, + Map> tenantedDynamicTasks) throws TaskManagementException, TaskException { - List tenants = new ArrayList<>(); - try { - RealmService realmService = TaskWatcherDataHolder.getInstance().getRealmService(); - Tenant[] tenantArray = realmService.getTenantManager().getAllTenants(); - if (tenantArray != null && tenantArray.length != 0) { - tenants.addAll(Arrays.asList(tenantArray)); - } - Tenant superTenant = new Tenant(); - superTenant.setId(-1234); - tenants.add(superTenant); - } catch (UserStoreException e) { - String msg = "Unable to load tenants"; - log.error(msg, e); - return; - } - TaskManager taskManager; Set hashIds; try { @@ -217,6 +258,8 @@ public class IoTSStartupHandler implements ServerStartupObserver { throw new TaskManagementException(msg, e); } + List tenants = getAllTenants(); + for (Tenant tenant : tenants) { if (tenantedDynamicTasks.get(tenant.getId()) == null) { if (log.isTraceEnabled()) { @@ -258,4 +301,23 @@ public class IoTSStartupHandler implements ServerStartupObserver { } } + private List getAllTenants() { + List tenants = new ArrayList<>(); + try { + RealmService realmService = TaskWatcherDataHolder.getInstance().getRealmService(); + Tenant[] tenantArray = realmService.getTenantManager().getAllTenants(); + if (tenantArray != null && tenantArray.length != 0) { + tenants.addAll(Arrays.asList(tenantArray)); + } + Tenant superTenant = new Tenant(); + superTenant.setId(-1234); + tenants.add(superTenant); + return tenants; + } catch (UserStoreException e) { + String msg = "Unable to load tenants"; + log.error(msg, e); + return new ArrayList<>(); + } + } + } diff --git a/components/task-mgt/task-watcher/pom.xml b/components/task-mgt/task-watcher/pom.xml index f075b06b9c..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.41-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 b367397132..6e431bb444 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.41-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 beb1a890e0..b6902e627e 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml @@ -74,7 +74,19 @@ org.wso2.carbon.stratos.common.exception;version="[4.9,5)", org.wso2.carbon.stratos.common.listeners;version="[4.9,5)", org.wso2.carbon.user.api;version="[1.0,2)", - org.wso2.carbon.user.core.service;version="[4.8,5)" + org.wso2.carbon.user.core.service;version="[4.8,5)", + org.apache.commons.logging, + io.entgra.device.mgt.core.application.mgt.common.*, + io.entgra.device.mgt.core.application.mgt.core.config, + io.entgra.device.mgt.core.device.mgt.core, + io.entgra.device.mgt.core.tenant.mgt.common.*, + io.entgra.device.mgt.core.device.mgt.common.metadata.mgt, + io.entgra.device.mgt.core.device.mgt.common.exceptions, + io.entgra.device.mgt.core.device.mgt.common.permission.mgt, + 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.* !io.entgra.device.mgt.core.tenant.mgt.core.internal, 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 55f20e1ae9..de63497e87 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 @@ -26,8 +26,12 @@ import io.entgra.device.mgt.core.device.mgt.common.roles.config.Role; 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.device.mgt.core.permission.mgt.PermissionUtils; -import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException; +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; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -46,6 +50,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 +122,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 dec3a93094..c439aa49fc 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 f73477ff17..b6f117f9fa 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 b5addd2794..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.41-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 e8de74b3c5..6d31f64182 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.41-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 b8e4ebb5f6..1e6168030f 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/pom.xml b/components/transport-mgt/pom.xml index cf83a5a86d..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.41-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 c980017596..2761242fd0 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.41-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 bdeaf8c537..f2e414622d 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.41-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 a48bccdf5e..e303131331 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.41-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 10c48a75ec..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.41-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 19690b5363..f4e00ec39d 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.41-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/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 e68f4f05f1..33d8dd420b 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 @@ -53,6 +53,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 b0f514f05c..3451a4addf 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 @@ -69,6 +69,7 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; +import java.util.Base64; import java.util.Enumeration; import java.util.HashMap; import java.util.List; @@ -616,7 +617,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"); @@ -628,8 +629,11 @@ public class HandlerUtil { tokenResultResponse = constructProxyResponseByErrorCode(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."); @@ -647,6 +651,10 @@ public class HandlerUtil { 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( @@ -655,6 +663,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()); diff --git a/components/ui-request-interceptor/pom.xml b/components/ui-request-interceptor/pom.xml index 0c6244c963..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.41-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 35b07df406..0cefdf699c 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java index 15a6ce3de3..c9bf8974a7 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java @@ -134,6 +134,7 @@ public class PermissionAuthorizer { } if (isUserAuthorized) { + PermissionManagerServiceImpl.getInstance().setRequiredPermission(requiredPermission); return WebappAuthenticator.Status.SUCCESS; } else { return WebappAuthenticator.Status.FAILURE; diff --git a/components/webapp-authenticator-framework/pom.xml b/components/webapp-authenticator-framework/pom.xml index b2dbd49b65..a6c571c66e 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.41-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 5ee2379a0c..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.41-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 84c8edb65c..560f6452cf 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.41-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 f8dffca5f7..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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/pom.xml b/features/analytics-mgt/pom.xml index 28c032bfc2..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.41-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 68397e5fd1..f0bdb82879 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.41-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 34162d786e..7c20ffc5db 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.41-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 7e97d37e80..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.41-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 2afa1b6615..cbfe3c2175 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.41-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 e3f3d3f28b..eeeb2e049f 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/pom.xml b/features/apimgt-extensions/pom.xml index e442524a65..53b97bb223 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.41-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 6615e46d12..54d1f6a6c0 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/application-mgt/pom.xml b/features/application-mgt/pom.xml index cc19155edf..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.41-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 ec1828cb6c..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 @@ -22,7 +22,7 @@ io.entgra.device.mgt.core cea-mgt-feature - 5.0.41-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 fa0608b760..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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/cea-mgt-feature/pom.xml b/features/cea-mgt-feature/pom.xml index 5641cfe43c..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.41-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 6343a00c20..12e1fbc543 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.41-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 e94b775e2e..48337cc7bb 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.41-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 44ff923f26..e77a04ff7a 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index 1cd8e2f9a5..079da28c61 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.41-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 8cc3dc0933..2d2f098e0a 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.41-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 028e2d7249..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.41-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 4486e06cdd..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.41-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 ff8bd881f4..3eb2959539 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.41-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 e27b0bb6d9..ec6b79b9f5 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.41-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 238d0841a5..9f10c7c42e 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.41-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 07b6f9226b..05294d9c12 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.41-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 003ee60333..05eb2f4783 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.41-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 e978938c14..b2761e8c91 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.41-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 fa391ff69d..e554e69ca1 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.41-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 b15e6b8148..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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/pom.xml b/features/device-mgt-extensions/pom.xml index 4be5bb8315..dbee6fe6a5 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.41-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 b9d04a4bb4..319c5dd6b8 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.41-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 4d7e9af438..35671dd032 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.41-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/archival/mysql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/mysql.sql index 7854ee1181..d7cf6837bc 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/mysql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/mysql.sql @@ -7,6 +7,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION_ARCH ( OPERATION_CODE VARCHAR(50) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, ARCHIVED_AT TIMESTAMP DEFAULT NOW() )ENGINE = InnoDB; diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/postgresql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/postgresql.sql index 726f5b9a7c..ec4513bf5b 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/postgresql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/postgresql.sql @@ -6,6 +6,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION_ARCH ( OPERATION_CODE VARCHAR(50) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BYTEA DEFAULT NULL, + OPERATION_PROPERTIES BYTEA DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW() ); 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 d9efaf48fc..8b2858ca80 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 @@ -91,6 +91,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( OPERATION_CODE VARCHAR(1000) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INT NOT NULL, PRIMARY KEY (ID) 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 cee731c034..6c7aa649fd 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 @@ -125,6 +125,7 @@ CREATE TABLE DM_OPERATION ( OPERATION_CODE VARCHAR(50) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS VARBINARY(MAX) DEFAULT NULL, + OPERATION_PROPERTIES VARBINARY(MAX) DEFAULT NULL, ENABLED BIT NOT NULL DEFAULT 0, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) 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 7ddaf22af6..065862a36b 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 @@ -106,6 +106,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( OPERATION_CODE VARCHAR(50) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INT NOT NULL, PRIMARY KEY (ID) 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 6e99bb43ee..eccc831141 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 @@ -181,6 +181,7 @@ CREATE TABLE DM_OPERATION ( INITIATED_BY VARCHAR2(100) NULL, ENABLED NUMBER(10) DEFAULT 0 NOT NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, TENANT_ID INTEGER NOT NULL, CONSTRAINT PK_DM_OPERATION PRIMARY KEY (ID) ) 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 5d5c7446e6..371baa0763 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 @@ -99,6 +99,7 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( OPERATION_CODE VARCHAR(50) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BYTEA DEFAULT NULL, + OPERATION_PROPERTIES BYTEA DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cleanup-scripts/mysql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cleanup-scripts/mysql.sql index df58b1cf84..5a43717800 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cleanup-scripts/mysql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cleanup-scripts/mysql.sql @@ -157,6 +157,7 @@ CREATE TABLE NEW_DM_OPERATION ( OPERATION_CODE VARCHAR(50) NOT NULL, INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, + OPERATION_PROPERTIES BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID) ); @@ -218,8 +219,8 @@ SELECT CONCAT(NOW(), ': Inserted ', ROW_COUNT(),' records to DM_ENROLMENT_OP_MAP Insert data into NEW_DM_OPERATION from DM_OPERATION only with the OPERATION_IDs from DM_ENROLMENT_OP_MAPPING */ SELECT CONCAT(NOW(), ': Inserting data into DM_OPERATION FROM OLD_DM_OPERATION.') AS ''; -INSERT INTO DM_OPERATION (ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, INITIATED_BY, OPERATION_DETAILS, ENABLED) -SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, INITIATED_BY, OPERATION_DETAILS, ENABLED +INSERT INTO DM_OPERATION (ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, INITIATED_BY, OPERATION_DETAILS, OPERATION_PROPERTIES, ENABLED) +SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, INITIATED_BY, OPERATION_DETAILS, OPERATION_PROPERTIES, ENABLED FROM OLD_DM_OPERATION WHERE ID IN(SELECT OPERATION_ID FROM DM_ENROLMENT_OP_MAPPING); SELECT CONCAT(NOW(), ': Inserted ', ROW_COUNT(),' records to DM_OPERATION.') AS ''; 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 bca456b02e..d3a38c2985 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.41-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 ab66829646..638e8f7982 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.41-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 76c430b786..d4f8a3f38a 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml index 9ba5f83686..92cb189ffb 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.41-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 c2b39e1872..e59f18e0bc 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/heartbeat-management/pom.xml b/features/heartbeat-management/pom.xml index 52bf889e4c..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.41-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 2d172748d8..9712d5f1c4 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/jwt-client/pom.xml b/features/jwt-client/pom.xml index d63af936d7..596e1056d8 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.41-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 0ae0cb9ac2..cf99e5eb87 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/logger/pom.xml b/features/logger/pom.xml index ddf8e91e8d..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.41-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 3d232765c7..7f3add5546 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.41-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 3a29bf350c..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.41-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 65602bcff4..1b8501dccf 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/policy-mgt/pom.xml b/features/policy-mgt/pom.xml index b1b05d45c9..c23879d58b 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.41-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 d19239d1b8..3023d62758 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../../../pom.xml diff --git a/features/subtype-mgt/pom.xml b/features/subtype-mgt/pom.xml index 7c8b555c8a..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.41-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 12cb222542..43eeef843f 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../../../pom.xml diff --git a/features/task-mgt/pom.xml b/features/task-mgt/pom.xml index 16b841f8dc..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.41-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 8ec47e9bbb..b5890212b4 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/tenant-mgt/pom.xml b/features/tenant-mgt/pom.xml index 28e985f832..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.41-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 4ac63d5493..585594a383 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.41-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 f58f655efc..1fab957e6c 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/pom.xml b/features/transport-mgt/pom.xml index cf5f83d5c3..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.41-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 c6204f96eb..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.41-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 950f6bccd3..61030ff1da 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.41-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 52c2807727..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.41-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 ac3a9b3cf9..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.41-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 0628bc0b09..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.41-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 6929a135aa..4a4c0a0ca2 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../pom.xml diff --git a/features/webapp-authenticator-framework/pom.xml b/features/webapp-authenticator-framework/pom.xml index f9b3f7dc69..f2dc6b9ea0 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.41-SNAPSHOT + 5.0.42-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index 0f3c78a558..dcbac2b442 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.41-SNAPSHOT + 5.0.42-SNAPSHOT WSO2 Carbon - Device Management - Parent https://entgra.io WSO2 Connected Device Manager Components @@ -2084,7 +2084,7 @@ 1.2.11-wso2v25 - 5.0.41-SNAPSHOT + 5.0.42-SNAPSHOT 4.9.2 @@ -2131,8 +2131,8 @@ 1.3 2.9.1 31.0.1-jre - 4.6.0 - 1.13.0 + 4.12.0 + 3.6.0 11.0 1.1.1 1.2