From 9ccf3a5fa5ca9600dad78c041eb3c4b492d81fbf Mon Sep 17 00:00:00 2001 From: inoshperera Date: Fri, 23 Jun 2023 23:18:30 +0530 Subject: [PATCH 01/36] Add vpp user apis fixes https://roadmap.entgra.net/issues/10162 --- .../mgt/common/dto/ProxyResponse.java | 37 +++ .../mgt/common/dto/VppItuneUserDTO.java | 67 ++++ .../mgt/common/dto/VppUserDTO.java | 76 +++++ .../services/VPPApplicationManager.java | 34 +++ .../wrapper/VppItuneUserRequestWrapper.java | 40 +++ .../core/impl/VppApplicationManagerImpl.java | 107 +++++++ ...ApplicationManagementServiceComponent.java | 8 + .../mgt/core/internal/DataHolder.java | 11 + .../application/mgt/core/util/Constants.java | 12 + .../mgt/core/util/VppHttpUtil.java | 285 ++++++++++++++++++ 10 files changed, 677 insertions(+) create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ProxyResponse.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneUserDTO.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppUserDTO.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/VPPApplicationManager.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneUserRequestWrapper.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/VppApplicationManagerImpl.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/VppHttpUtil.java 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/dto/ProxyResponse.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ProxyResponse.java new file mode 100644 index 0000000000..80d5f94df1 --- /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/dto/ProxyResponse.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.dto; + +public class ProxyResponse { + + private int code; + private String data; + private String executorResponse; + + public int getCode() { return code; } + + public void setCode(int code) { this.code = code; } + + public String getData() { return data; } + + public void setData(String data) { this.data = data; } + + public String getExecutorResponse() { return executorResponse; } + + public void setExecutorResponse(String executorResponse) { this.executorResponse = executorResponse; } +} \ No newline at end of file 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/dto/VppItuneUserDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneUserDTO.java new file mode 100644 index 0000000000..d9ebb4ee59 --- /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/dto/VppItuneUserDTO.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppItuneUserDTO { + String clientUserId; + String inviteCode; + String status; + String email; + String managedId; + + public String getClientUserId() { + return clientUserId; + } + + public void setClientUserId(String clientUserId) { + this.clientUserId = clientUserId; + } + + public String getInviteCode() { + return inviteCode; + } + + public void setInviteCode(String inviteCode) { + this.inviteCode = inviteCode; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getManagedId() { + return managedId; + } + + public void setManagedId(String managedId) { + this.managedId = managedId; + } + +} \ No newline at end of file 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/dto/VppUserDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppUserDTO.java new file mode 100644 index 0000000000..e2915fec97 --- /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/dto/VppUserDTO.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppUserDTO extends VppItuneUserDTO { + int id; + String dmUsername; + int tenantId; + String createdTime; + String lastUpdatedTime; + String tmpPassword; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDmUsername() { + return dmUsername; + } + + public void setDmUsername(String dmUsername) { + this.dmUsername = dmUsername; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + public String getLastUpdatedTime() { + return lastUpdatedTime; + } + + public void setLastUpdatedTime(String lastUpdatedTime) { + this.lastUpdatedTime = lastUpdatedTime; + } + + public String getTmpPassword() { + return tmpPassword; + } + + public void setTmpPassword(String tmpPassword) { + this.tmpPassword = tmpPassword; + } + +} \ No newline at end of file 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/VPPApplicationManager.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/VPPApplicationManager.java new file mode 100644 index 0000000000..0fa5164f0b --- /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/VPPApplicationManager.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.device.mgt.core.application.mgt.common.services; + +import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; + +import java.io.IOException; + +public interface VPPApplicationManager { + + VppUserDTO getUserByDMUsername() throws ApplicationManagementException; + + VppUserDTO addUser(VppUserDTO userDTO) throws ApplicationManagementException; + + ProxyResponse callVPPBackend(String url, String payload, String accessToken, String method) throws IOException; +} 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/VppItuneUserRequestWrapper.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/VppItuneUserRequestWrapper.java new file mode 100644 index 0000000000..726a7dbadd --- /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/VppItuneUserRequestWrapper.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.wrapper; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; + +import java.util.ArrayList; +import java.util.List; + +public class VppItuneUserRequestWrapper { + + List user; + + public VppItuneUserRequestWrapper() { + user = new ArrayList<>(); + } + public List getUser() { + return user; + } + + public void setUser(List user) { + this.user = user; + } + +} \ No newline at end of file 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java new file mode 100644 index 0000000000..c9e27bebbc --- /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/VppApplicationManagerImpl.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.device.mgt.core.application.mgt.core.impl; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserRequestWrapper; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; +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.internal.DataHolder; +import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; +import io.entgra.device.mgt.core.application.mgt.core.util.Constants; +import io.entgra.device.mgt.core.application.mgt.core.util.VppHttpUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpStatus; + +import java.io.IOException; + +public class VppApplicationManagerImpl implements VPPApplicationManager { + private static final String APP_API = "https://vpp.itunes.apple.com/mdm/v2"; + private static final String ASSETS = APP_API + "/assets"; + private static final String USER_CREATE = APP_API + "users/create"; + private static final String TOKEN = ""; + + private static final Log log = LogFactory.getLog(VppApplicationManagerImpl.class); + private ApplicationDAO applicationDAO; + private SPApplicationDAO spApplicationDAO; + private VisibilityDAO visibilityDAO; + private final LifecycleStateManager lifecycleStateManager; + + public VppApplicationManagerImpl() { + initDataAccessObjects(); + lifecycleStateManager = DataHolder.getInstance().getLifecycleStateManager(); + } + + private void initDataAccessObjects() { + this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); + this.visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO(); + this.spApplicationDAO = ApplicationManagementDAOFactory.getSPApplicationDAO(); + } + + + @Override + public VppUserDTO getUserByDMUsername() throws ApplicationManagementException { + // TODO: Return from DAO in a tenanted manner + return null; + } + + @Override + public VppUserDTO addUser(VppUserDTO userDTO) throws ApplicationManagementException { + // Call the API to add + try { + VppItuneUserDTO ituneUserDTO = userDTO; + VppItuneUserRequestWrapper wrapper = new VppItuneUserRequestWrapper(); + wrapper.getUser().add(ituneUserDTO); + + Gson gson = new Gson(); + String userPayload = gson.toJson(wrapper); + + ProxyResponse proxyResponse = callVPPBackend(USER_CREATE, userPayload, TOKEN, Constants.POST); + if (proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == HttpStatus.SC_CREATED) { + // TODO: Save the user in the DAO + + + + } + } catch (IOException e) { + String msg = "Error while callng VPP backend"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + + + return null; + } + + @Override + public ProxyResponse callVPPBackend(String url, + String payload, + String accessToken, + String method) throws IOException { + return VppHttpUtil.execute(url, payload, accessToken, method); + } +} 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 d15ae1eb5d..0a373b4282 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 @@ -18,7 +18,9 @@ package io.entgra.device.mgt.core.application.mgt.core.internal; import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; import io.entgra.device.mgt.core.application.mgt.core.impl.AppmDataHandlerImpl; +import io.entgra.device.mgt.core.application.mgt.core.impl.VppApplicationManagerImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; @@ -116,6 +118,12 @@ public class ApplicationManagementServiceComponent { DataHolder.getInstance().setConfigManager(configManager); bundleContext.registerService(AppmDataHandler.class.getName(), configManager, null); + + // TODO: Get the new instance from extension like others + VppApplicationManagerImpl vppApplicationManager = new VppApplicationManagerImpl(); + DataHolder.getInstance().setVppApplicationManager(vppApplicationManager); + bundleContext.registerService(VPPApplicationManager.class.getName(), vppApplicationManager, null); + ScheduledAppSubscriptionTaskManager taskManager = new ScheduledAppSubscriptionTaskManager(); taskManager.scheduleCleanupTask(); diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java index 6d5000a986..b8905829ad 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 @@ -23,6 +23,7 @@ import io.entgra.device.mgt.core.application.mgt.common.services.AppmDataHandler 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; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.ntask.core.service.TaskService; @@ -39,6 +40,8 @@ public class DataHolder { private SPApplicationManager SPApplicationManager; + private VPPApplicationManager vppApplicationManager; + private ApplicationManager applicationManager; private ReviewManager reviewManager; @@ -142,4 +145,12 @@ public class DataHolder { public void setISApplicationManager(SPApplicationManager SPApplicationManager) { this.SPApplicationManager = SPApplicationManager; } + + public VPPApplicationManager getVppApplicationManager() { + return vppApplicationManager; + } + + public void setVppApplicationManager(VPPApplicationManager vppApplicationManager) { + this.vppApplicationManager = vppApplicationManager; + } } 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 5864242acf..bd676bf3e8 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 @@ -100,6 +100,18 @@ public class Constants { } public static final Map AGENT_FILE_NAMES = Collections.unmodifiableMap(AGENT_DATA); + public static final String BEARER = "Bearer "; + + public static final String EXECUTOR_EXCEPTION_PREFIX = "ExecutorException-"; + public static final String TOKEN_IS_EXPIRED = "ACCESS_TOKEN_IS_EXPIRED"; + + public static final int INTERNAL_ERROR_CODE = 500; + + public static final String GET = "GET"; + public static final String POST = "POST"; + public static final String PUT = "PUT"; + public static final String DELETE = "DELETE"; + /** * Database types supported by Application Management. 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/VppHttpUtil.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/VppHttpUtil.java new file mode 100644 index 0000000000..216a8de71f --- /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/VppHttpUtil.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.device.mgt.core.application.mgt.core.util; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +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.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; + +public class VppHttpUtil { + private static final Log log = LogFactory.getLog(VppHttpUtil.class); + + public static ProxyResponse execute(String url, + String payload, + String accessToken, + String method) throws IOException { + + HttpRequestBase endpoint = null; + if (Constants.GET.equalsIgnoreCase(method) || Constants.DELETE.equalsIgnoreCase(method)) { + endpoint = new HttpGet(url); + addHeaders(endpoint, accessToken); + return VppHttpUtil.execute(endpoint); + } else if (Constants.POST.equalsIgnoreCase(method)) { + endpoint = new HttpPost(url); + } else if (Constants.PUT.equalsIgnoreCase(method)) { + endpoint = new HttpPut(url); + } + addHeaders(endpoint, accessToken); + + + if (payload != null) { + HttpEntity forwardRequestBody = new StringEntity(payload, ContentType.APPLICATION_JSON.toString(), "utf-8"); + if (Constants.POST.equalsIgnoreCase(method)) { + ((HttpPost) endpoint).setEntity(forwardRequestBody); + } else if (Constants.PUT.equalsIgnoreCase(method)) { + ((HttpPut) endpoint).setEntity(forwardRequestBody); + } + + } + if (log.isDebugEnabled()) { + log.info("Forwarding request to " + url); + } + return VppHttpUtil.execute(endpoint); + } + + private static void addHeaders(HttpRequestBase endpoint, String accessToken) { + endpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); + endpoint.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()); + endpoint.setHeader(HttpHeaders.AUTHORIZATION, Constants.BEARER + accessToken); + } + + + /*** + * + * @param httpRequest - httpMethod e.g:- HttpPost, HttpGet + * @return response as string + * @throws IOException IO exception returns if error occurs when executing the httpMethod + */ + private static ProxyResponse execute(HttpRequestBase httpRequest) throws IOException { + try (CloseableHttpClient client = getHttpClient()) { + HttpResponse response = client.execute(httpRequest); + ProxyResponse proxyResponse = new ProxyResponse(); + + if (response == null) { + log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest + .getURI().toString()); + proxyResponse.setCode(Constants.INTERNAL_ERROR_CODE); + proxyResponse.setExecutorResponse(Constants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey( + Constants.INTERNAL_ERROR_CODE)); + return proxyResponse; + } else { + int statusCode = response.getStatusLine().getStatusCode(); + try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { + StringBuilder result = new StringBuilder(); + String line; + while ((line = rd.readLine()) != null) { + result.append(line); + } + + String jsonString = result.toString(); + if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { + proxyResponse.setCode(statusCode); + proxyResponse.setData(jsonString); + proxyResponse.setExecutorResponse("SUCCESS"); + return proxyResponse; + } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { + if (jsonString.contains("Access token expired") || jsonString + .contains("Invalid input. Access token validation failed")) { + proxyResponse.setCode(statusCode); + proxyResponse.setExecutorResponse(Constants.TOKEN_IS_EXPIRED); + return proxyResponse; + } else { + log.error( + "Received " + statusCode + " response for http request : " + httpRequest.getMethod() + + " " + httpRequest.getURI().toString() + ". Error message: " + jsonString); + proxyResponse.setCode(statusCode); + proxyResponse.setData(jsonString); + proxyResponse.setExecutorResponse( + Constants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); + return proxyResponse; + } + } + log.error("Received " + statusCode + + " response for http request : " + httpRequest.getMethod() + " " + httpRequest.getURI() + .toString() + ". Error message: " + jsonString); + proxyResponse.setCode(statusCode); + proxyResponse.setData(jsonString); + proxyResponse + .setExecutorResponse(Constants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); + return proxyResponse; + } + } + } + } + + /*** + * + * @param statusCode Provide status code, e.g:- 400, 401, 500 etc + * @return relative status code key for given status code. + */ + public static String getStatusKey(int statusCode) { + String statusCodeKey; + + switch (statusCode) { + case HttpStatus.SC_INTERNAL_SERVER_ERROR: + statusCodeKey = "internalServerError"; + break; + case HttpStatus.SC_BAD_REQUEST: + statusCodeKey = "badRequest"; + break; + case HttpStatus.SC_UNAUTHORIZED: + statusCodeKey = "unauthorized"; + break; + case HttpStatus.SC_FORBIDDEN: + statusCodeKey = "forbidden"; + break; + case HttpStatus.SC_NOT_FOUND: + statusCodeKey = "notFound"; + break; + case HttpStatus.SC_METHOD_NOT_ALLOWED: + statusCodeKey = "methodNotAllowed"; + break; + case HttpStatus.SC_NOT_ACCEPTABLE: + statusCodeKey = "notAcceptable"; + break; + case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: + statusCodeKey = "unsupportedMediaType"; + break; + default: + statusCodeKey = "defaultPage"; + break; + } + return statusCodeKey; + } + + + /*** + * Handle error requests. + * + * @param resp {@link HttpServletResponse} + * @param proxyResponse {@link ProxyResponse} + * @throws IOException If error occurred when trying to send the error response. + */ + public static void handleError(HttpServletResponse resp, ProxyResponse proxyResponse) throws IOException { + Gson gson = new Gson(); + if (proxyResponse == null) { + proxyResponse = new ProxyResponse(); + proxyResponse.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); + proxyResponse.setExecutorResponse(Constants.EXECUTOR_EXCEPTION_PREFIX + VppHttpUtil + .getStatusKey(Constants.INTERNAL_ERROR_CODE)); + } + resp.setStatus(proxyResponse.getCode()); + resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); + resp.setCharacterEncoding(Consts.UTF_8.name()); + + proxyResponse.setExecutorResponse(null); + try (PrintWriter writer = resp.getWriter()) { + writer.write(gson.toJson(proxyResponse)); + } + } + + /** + * Handle error requests with custom error codes. + * + * @param resp {@link HttpServletResponse} + * @param errorCode HTTP error status code + * @throws IOException If error occurred when trying to send the error response. + */ + public static void handleError(HttpServletResponse resp, int errorCode) + throws IOException { + ProxyResponse proxyResponse = new ProxyResponse(); + proxyResponse.setCode(errorCode); + proxyResponse.setExecutorResponse( + Constants.EXECUTOR_EXCEPTION_PREFIX + VppHttpUtil.getStatusKey(errorCode)); + VppHttpUtil.handleError(resp, proxyResponse); + } + + /*** + * + * @param resp {@link HttpServletResponse} + * Return Success Response. + */ + public static void handleSuccess(HttpServletResponse resp, ProxyResponse proxyResponse) throws IOException { + if (proxyResponse == null) { + handleError(resp, null); + return; + } + resp.setStatus(proxyResponse.getCode()); + resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); + resp.setCharacterEncoding(Consts.UTF_8.name()); + JSONObject response = new JSONObject(); + String responseData = proxyResponse.getData(); + + if (!StringUtils.isEmpty(responseData)) { + try { + if (responseData.startsWith("{")) { + JSONObject responseDataJsonObj = new JSONObject(responseData); + response.put("data", responseDataJsonObj); + } else if (responseData.startsWith("[")) { + JSONArray responseDataJsonArr = new JSONArray(responseData); + response.put("data", responseDataJsonArr); + } else { + log.warn("Response data is not valid json string >> " + responseData); + response.put("data", responseData); + } + } catch (JSONException e) { + log.error("Response data is not passable"); + response.put("data", responseData); + } + } + + try (PrintWriter writer = resp.getWriter()) { + writer.write(response.toString()); + } + } + + /** + * Retrieve Http client based on hostname verification. + * + * @return {@link CloseableHttpClient} http client + */ + public static CloseableHttpClient getHttpClient() { + return HttpClients.custom().setMaxConnTotal(1).setMaxConnPerRoute(1).build(); + } + +} From cc8470d3c0970427ca2d31594e026d14b0f49b6c Mon Sep 17 00:00:00 2001 From: inoshperera Date: Mon, 26 Jun 2023 19:10:17 +0530 Subject: [PATCH 02/36] add vpp user services --- .../mgt/common/dto/VppPaginationDTO.java | 76 +++++++++++++++ .../mgt/common/dto/VppUserDTO.java | 16 ++++ .../services/VPPApplicationManager.java | 8 +- .../wrapper/VppItuneUserRequestWrapper.java | 10 +- .../wrapper/VppItuneUserResponseWrapper.java | 40 ++++++++ .../core/impl/VppApplicationManagerImpl.java | 93 ++++++++++++++++--- .../application/mgt/core/util/Constants.java | 28 +++--- .../mgt/core/util/VppHttpUtil.java | 30 +++--- 8 files changed, 255 insertions(+), 46 deletions(-) create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppPaginationDTO.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneUserResponseWrapper.java 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/dto/VppPaginationDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppPaginationDTO.java new file mode 100644 index 0000000000..32c4f12f9b --- /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/dto/VppPaginationDTO.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppPaginationDTO { + + int currentPageIndex; + int size; + String tokenExpirationDate; + int totalPages; + String uId; + String versionId; + + public int getCurrentPageIndex() { + return currentPageIndex; + } + + public void setCurrentPageIndex(int currentPageIndex) { + this.currentPageIndex = currentPageIndex; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public String getTokenExpirationDate() { + return tokenExpirationDate; + } + + public void setTokenExpirationDate(String tokenExpirationDate) { + this.tokenExpirationDate = tokenExpirationDate; + } + + public int getTotalPages() { + return totalPages; + } + + public void setTotalPages(int totalPages) { + this.totalPages = totalPages; + } + + public String getuId() { + return uId; + } + + public void setuId(String uId) { + this.uId = uId; + } + + public String getVersionId() { + return versionId; + } + + public void setVersionId(String versionId) { + this.versionId = versionId; + } +} 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/dto/VppUserDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppUserDTO.java index e2915fec97..4ea7929014 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppUserDTO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppUserDTO.java @@ -73,4 +73,20 @@ public class VppUserDTO extends VppItuneUserDTO { this.tmpPassword = tmpPassword; } + @Override + public String toString() { + return "VppUserDTO{" + + "id=" + id + + ", dmUsername='" + dmUsername + '\'' + + ", tenantId=" + tenantId + + ", createdTime='" + createdTime + '\'' + + ", lastUpdatedTime='" + lastUpdatedTime + '\'' + + ", tmpPassword='" + tmpPassword + '\'' + + ", clientUserId='" + clientUserId + '\'' + + ", inviteCode='" + inviteCode + '\'' + + ", status='" + status + '\'' + + ", email='" + email + '\'' + + ", managedId='" + managedId + '\'' + + '}'; + } } \ No newline at end of file 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/VPPApplicationManager.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/VPPApplicationManager.java index 0fa5164f0b..4b08001e08 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/VPPApplicationManager.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/VPPApplicationManager.java @@ -26,9 +26,13 @@ import java.io.IOException; public interface VPPApplicationManager { - VppUserDTO getUserByDMUsername() throws ApplicationManagementException; - VppUserDTO addUser(VppUserDTO userDTO) throws ApplicationManagementException; + VppUserDTO getUserByDMUsername(String emmUsername) throws ApplicationManagementException; + + void updateUser(VppUserDTO userDTO) throws ApplicationManagementException; + + void syncUsers(String clientId) throws ApplicationManagementException; + ProxyResponse callVPPBackend(String url, String payload, String accessToken, String method) throws IOException; } 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/VppItuneUserRequestWrapper.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/VppItuneUserRequestWrapper.java index 726a7dbadd..4189fa557a 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/VppItuneUserRequestWrapper.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/VppItuneUserRequestWrapper.java @@ -24,17 +24,17 @@ import java.util.List; public class VppItuneUserRequestWrapper { - List user; + List users; public VppItuneUserRequestWrapper() { - user = new ArrayList<>(); + users = new ArrayList<>(); } public List getUser() { - return user; + return users; } - public void setUser(List user) { - this.user = user; + public void setUser(List users) { + this.users = users; } } \ No newline at end of file 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/VppItuneUserResponseWrapper.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/VppItuneUserResponseWrapper.java new file mode 100644 index 0000000000..64ee578241 --- /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/VppItuneUserResponseWrapper.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.wrapper; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppPaginationDTO; + +import java.util.ArrayList; +import java.util.List; + +public class VppItuneUserResponseWrapper extends VppPaginationDTO { + + List users; + + public VppItuneUserResponseWrapper() { + users = new ArrayList<>(); + } + public List getUser() { + return users; + } + + public void setUser(List users) { + this.users = users; + } +} 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index c9e27bebbc..6ec3023def 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -18,13 +18,17 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserRequestWrapper; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserResponseWrapper; import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.VisibilityDAO; @@ -42,7 +46,9 @@ import java.io.IOException; public class VppApplicationManagerImpl implements VPPApplicationManager { private static final String APP_API = "https://vpp.itunes.apple.com/mdm/v2"; private static final String ASSETS = APP_API + "/assets"; - private static final String USER_CREATE = APP_API + "users/create"; + private static final String USER_CREATE = APP_API + "/users/create"; + private static final String USER_UPDATE = APP_API + "/users/update"; + private static final String USER_GET = APP_API + "/users"; private static final String TOKEN = ""; private static final Log log = LogFactory.getLog(VppApplicationManagerImpl.class); @@ -62,13 +68,6 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { this.spApplicationDAO = ApplicationManagementDAOFactory.getSPApplicationDAO(); } - - @Override - public VppUserDTO getUserByDMUsername() throws ApplicationManagementException { - // TODO: Return from DAO in a tenanted manner - return null; - } - @Override public VppUserDTO addUser(VppUserDTO userDTO) throws ApplicationManagementException { // Call the API to add @@ -78,23 +77,90 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { wrapper.getUser().add(ituneUserDTO); Gson gson = new Gson(); +// Gson gson = new GsonBuilder() +// .setExclusionStrategies(new NullEmptyExclusionStrategy()) +// .create(); String userPayload = gson.toJson(wrapper); - ProxyResponse proxyResponse = callVPPBackend(USER_CREATE, userPayload, TOKEN, Constants.POST); - if (proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == HttpStatus.SC_CREATED) { - // TODO: Save the user in the DAO + ProxyResponse proxyResponse = callVPPBackend(USER_CREATE, userPayload, TOKEN, Constants.VPP.POST); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { + // Create user does not return any useful data. Its needed to call the backend again + ProxyResponse getUserResponse = callVPPBackend(USER_GET + Constants.VPP.CLIENT_USER_ID_PARAM + + userDTO.getClientUserId(), userPayload, TOKEN, Constants.VPP.GET); + if ((getUserResponse.getCode() == HttpStatus.SC_OK || getUserResponse.getCode() == + HttpStatus.SC_CREATED) && getUserResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { + VppItuneUserResponseWrapper vppItuneUserResponseWrapper = gson.fromJson + (getUserResponse.getData(), VppItuneUserResponseWrapper.class); + userDTO.setInviteCode(vppItuneUserResponseWrapper.getUser().get(0) + .getInviteCode()); + userDTO.setStatus(vppItuneUserResponseWrapper.getUser().get(0).getStatus()); + log.error("userDTO " + userDTO.toString()); + // TODO: Save the userDTO in the DAO + + + return userDTO; + } + } + } catch (IOException e) { + String msg = "Error while calling VPP backend to add user"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + return null; + } + + @Override + public VppUserDTO getUserByDMUsername(String emmUsername) throws ApplicationManagementException { + // TODO: Return from DAO in a tenanted manner + return null; + } + + @Override + public void updateUser(VppUserDTO userDTO) throws ApplicationManagementException { + VppItuneUserDTO ituneUserDTO = userDTO; + VppItuneUserRequestWrapper wrapper = new VppItuneUserRequestWrapper(); + wrapper.getUser().add(ituneUserDTO); + + Gson gson = new Gson(); + String userPayload = gson.toJson(wrapper); + try { + ProxyResponse proxyResponse = callVPPBackend(USER_UPDATE, userPayload, TOKEN, Constants.VPP.POST); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { + + log.error("userDTO " + userDTO.toString()); + // TODO: Save the userDTO in the DAO } } catch (IOException e) { - String msg = "Error while callng VPP backend"; + String msg = "Error while callng VPP backend to update"; log.error(msg, e); throw new ApplicationManagementException(msg, e); } + } + @Override + public void syncUsers(String clientId) throws ApplicationManagementException { + ProxyResponse proxyResponse = null; + try { + proxyResponse = callVPPBackend(USER_GET, null, TOKEN, Constants + .VPP.GET); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { + log.error("proxyResponse " + proxyResponse.getData()); + Gson gson = new Gson(); + VppItuneUserResponseWrapper vppUserResponseWrapper = gson.fromJson + (proxyResponse.getData(), VppItuneUserResponseWrapper.class); + } + } catch (IOException e) { + String msg = "Error while syncing VPP users with backend"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } - return null; } @Override @@ -104,4 +170,5 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { String method) throws IOException { return VppHttpUtil.execute(url, payload, accessToken, method); } + } 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 bd676bf3e8..ce61c1a81b 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 @@ -100,17 +100,23 @@ public class Constants { } public static final Map AGENT_FILE_NAMES = Collections.unmodifiableMap(AGENT_DATA); - public static final String BEARER = "Bearer "; - - public static final String EXECUTOR_EXCEPTION_PREFIX = "ExecutorException-"; - public static final String TOKEN_IS_EXPIRED = "ACCESS_TOKEN_IS_EXPIRED"; - - public static final int INTERNAL_ERROR_CODE = 500; - - public static final String GET = "GET"; - public static final String POST = "POST"; - public static final String PUT = "PUT"; - public static final String DELETE = "DELETE"; + public static final class VPP { + public static final String GET = "GET"; + public static final String BEARER = "Bearer "; + public static final String EXECUTOR_EXCEPTION_PREFIX = "ExecutorException-"; + public static final String TOKEN_IS_EXPIRED = "ACCESS_TOKEN_IS_EXPIRED"; + public static final int INTERNAL_ERROR_CODE = 500; + public static final String POST = "POST"; + public static final String PUT = "PUT"; + public static final String DELETE = "DELETE"; + public static final String CLIENT_USER_ID = "clientUserId"; + public static final String EVENT_ID = "eventId"; + public static final String CLIENT_USER_ID_PARAM = "?clientUserId="; + public static final String TOTAL_PAGES = "totalPages"; + + private VPP() { + } + } /** 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/VppHttpUtil.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/VppHttpUtil.java index 216a8de71f..620339a1bf 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/VppHttpUtil.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/VppHttpUtil.java @@ -55,13 +55,13 @@ public class VppHttpUtil { String method) throws IOException { HttpRequestBase endpoint = null; - if (Constants.GET.equalsIgnoreCase(method) || Constants.DELETE.equalsIgnoreCase(method)) { + if (Constants.VPP.GET.equalsIgnoreCase(method) || Constants.VPP.DELETE.equalsIgnoreCase(method)) { endpoint = new HttpGet(url); addHeaders(endpoint, accessToken); return VppHttpUtil.execute(endpoint); - } else if (Constants.POST.equalsIgnoreCase(method)) { + } else if (Constants.VPP.POST.equalsIgnoreCase(method)) { endpoint = new HttpPost(url); - } else if (Constants.PUT.equalsIgnoreCase(method)) { + } else if (Constants.VPP.PUT.equalsIgnoreCase(method)) { endpoint = new HttpPut(url); } addHeaders(endpoint, accessToken); @@ -69,9 +69,9 @@ public class VppHttpUtil { if (payload != null) { HttpEntity forwardRequestBody = new StringEntity(payload, ContentType.APPLICATION_JSON.toString(), "utf-8"); - if (Constants.POST.equalsIgnoreCase(method)) { + if (Constants.VPP.POST.equalsIgnoreCase(method)) { ((HttpPost) endpoint).setEntity(forwardRequestBody); - } else if (Constants.PUT.equalsIgnoreCase(method)) { + } else if (Constants.VPP.PUT.equalsIgnoreCase(method)) { ((HttpPut) endpoint).setEntity(forwardRequestBody); } @@ -85,7 +85,7 @@ public class VppHttpUtil { private static void addHeaders(HttpRequestBase endpoint, String accessToken) { endpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); endpoint.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()); - endpoint.setHeader(HttpHeaders.AUTHORIZATION, Constants.BEARER + accessToken); + endpoint.setHeader(HttpHeaders.AUTHORIZATION, Constants.VPP.BEARER + accessToken); } @@ -103,9 +103,9 @@ public class VppHttpUtil { if (response == null) { log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest .getURI().toString()); - proxyResponse.setCode(Constants.INTERNAL_ERROR_CODE); - proxyResponse.setExecutorResponse(Constants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey( - Constants.INTERNAL_ERROR_CODE)); + proxyResponse.setCode(Constants.VPP.INTERNAL_ERROR_CODE); + proxyResponse.setExecutorResponse(Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + getStatusKey( + Constants.VPP.INTERNAL_ERROR_CODE)); return proxyResponse; } else { int statusCode = response.getStatusLine().getStatusCode(); @@ -126,7 +126,7 @@ public class VppHttpUtil { if (jsonString.contains("Access token expired") || jsonString .contains("Invalid input. Access token validation failed")) { proxyResponse.setCode(statusCode); - proxyResponse.setExecutorResponse(Constants.TOKEN_IS_EXPIRED); + proxyResponse.setExecutorResponse(Constants.VPP.TOKEN_IS_EXPIRED); return proxyResponse; } else { log.error( @@ -135,7 +135,7 @@ public class VppHttpUtil { proxyResponse.setCode(statusCode); proxyResponse.setData(jsonString); proxyResponse.setExecutorResponse( - Constants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); + Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); return proxyResponse; } } @@ -145,7 +145,7 @@ public class VppHttpUtil { proxyResponse.setCode(statusCode); proxyResponse.setData(jsonString); proxyResponse - .setExecutorResponse(Constants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); + .setExecutorResponse(Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); return proxyResponse; } } @@ -205,8 +205,8 @@ public class VppHttpUtil { if (proxyResponse == null) { proxyResponse = new ProxyResponse(); proxyResponse.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); - proxyResponse.setExecutorResponse(Constants.EXECUTOR_EXCEPTION_PREFIX + VppHttpUtil - .getStatusKey(Constants.INTERNAL_ERROR_CODE)); + proxyResponse.setExecutorResponse(Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + VppHttpUtil + .getStatusKey(Constants.VPP.INTERNAL_ERROR_CODE)); } resp.setStatus(proxyResponse.getCode()); resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); @@ -230,7 +230,7 @@ public class VppHttpUtil { ProxyResponse proxyResponse = new ProxyResponse(); proxyResponse.setCode(errorCode); proxyResponse.setExecutorResponse( - Constants.EXECUTOR_EXCEPTION_PREFIX + VppHttpUtil.getStatusKey(errorCode)); + Constants.VPP.EXECUTOR_EXCEPTION_PREFIX + VppHttpUtil.getStatusKey(errorCode)); VppHttpUtil.handleError(resp, proxyResponse); } From cd42a2c48fea2b15222c258ada529eccf0562a02 Mon Sep 17 00:00:00 2001 From: osh Date: Wed, 28 Jun 2023 20:03:16 +0530 Subject: [PATCH 03/36] Adding the DAO layer for vpp user management fixes https://roadmap.entgra.net/issues/10169 --- .../mgt/core/dao/VppApplicationDAO.java | 14 ++ .../ApplicationManagementDAOFactory.java | 36 ++++- .../vpp/GenericVppApplicationDAOImpl.java | 152 ++++++++++++++++++ .../impl/vpp/OracleVppApplicationDAOImpl.java | 64 ++++++++ .../impl/vpp/PostgreSQLVppApplicationDAO.java | 63 ++++++++ .../vpp/SQLServerVppApplicationDAOImpl.java | 4 + .../core/impl/VppApplicationManagerImpl.java | 80 +++++++-- .../application/mgt/core/util/DAOUtil.java | 38 +++++ 8 files changed, 435 insertions(+), 16 deletions(-) create mode 100644 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 create mode 100644 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 create mode 100644 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/OracleVppApplicationDAOImpl.java create mode 100644 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/PostgreSQLVppApplicationDAO.java create mode 100644 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/SQLServerVppApplicationDAOImpl.java 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 new file mode 100644 index 0000000000..ae2b75e515 --- /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/dao/VppApplicationDAO.java @@ -0,0 +1,14 @@ +package io.entgra.device.mgt.core.application.mgt.core.dao; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; + + +public interface VppApplicationDAO { + + int addVppUser(VppUserDTO userDTO) throws ApplicationManagementDAOException; + + VppUserDTO updateVppUser(VppUserDTO userDTO) throws ApplicationManagementDAOException; + + VppUserDTO getUserByDMUsername(String emmUsername) 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/common/ApplicationManagementDAOFactory.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/common/ApplicationManagementDAOFactory.java index e7996ee804..1a29b33b2d 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/common/ApplicationManagementDAOFactory.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/common/ApplicationManagementDAOFactory.java @@ -17,7 +17,7 @@ */ package io.entgra.device.mgt.core.application.mgt.core.dao.common; -import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.*; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication.GenericSPApplicationDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication.OracleSPApplicationDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.spapplication.PostgreSQLSPApplicationDAOImpl; @@ -26,16 +26,14 @@ import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.Generi import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.OracleVisibilityDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.PostgreSQLVisibilityDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.visibility.SQLServerVisibilityDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp.GenericVppApplicationDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp.OracleVppApplicationDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp.PostgreSQLVppApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp.SQLServerVppApplicationDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.exception.UnsupportedDatabaseEngineException; -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.ReviewDAO; -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.impl.application.PostgreSQLApplicationDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.SQLServerApplicationDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.application.release.OracleApplicationReleaseDAOImpl; @@ -232,4 +230,28 @@ public class ApplicationManagementDAOFactory { } throw new IllegalStateException("Database engine has not initialized properly."); } + + + /** + * To get the instance of VppApplicationImplementation of the particular database engine. + * @return specific VppApplicationImplementation + */ + public static VppApplicationDAO getVppApplicationDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + return new GenericVppApplicationDAOImpl(); + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new PostgreSQLVppApplicationDAO(); + case Constants.DataBaseTypes.DB_TYPE_ORACLE: + return new OracleVppApplicationDAOImpl(); + case Constants.DataBaseTypes.DB_TYPE_MSSQL: + return new SQLServerVppApplicationDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } } 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 new file mode 100644 index 0000000000..3dc356b764 --- /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/dao/impl/vpp/GenericVppApplicationDAOImpl.java @@ -0,0 +1,152 @@ +package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.core.dao.VppApplicationDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.*; + +public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements VppApplicationDAO { + private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); + + @Override + public int addVppUser(VppUserDTO userDTO) + throws ApplicationManagementDAOException { + int vppUserId = -1; + String sql = "INSERT INTO " + + "AP_VPP_USER(" + + "CLIENT_USER_ID, " + + "DM_USERNAME, " + + "TENANT_ID, " + + "EMAIL, " + + "INVITE_CODE, " + + "STATUS," + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "MANAGED_ID," + + "TEMP_PASSWORD) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + long currentTime = System.currentTimeMillis(); + stmt.setString(1, userDTO.getClientUserId()); + stmt.setString(2, userDTO.getDmUsername()); + stmt.setInt(3, userDTO.getTenantId()); + stmt.setString(4, userDTO.getEmail()); + stmt.setString(5, userDTO.getInviteCode()); + stmt.setString(6, userDTO.getStatus()); + stmt.setLong(7, currentTime); + stmt.setLong(8, currentTime); + stmt.setString(9, userDTO.getManagedId()); + stmt.setString(10, userDTO.getTmpPassword()); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + vppUserId = rs.getInt(1); + } + } + return vppUserId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the vpp user."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + public VppUserDTO updateVppUser(VppUserDTO userDTO) + throws ApplicationManagementDAOException { + + String sql = "UPDATE " + + "AP_VPP_USER " + + "SET " + + "CLIENT_USER_ID = ?," + + "DM_USERNAME = ?, " + + "TENANT_ID = ?, " + + "EMAIL = ?, " + + "INVITE_CODE = ?, " + + "STATUS = ?, " + + "LAST_UPDATED_TIME = ?, " + + "MANAGED_ID = ?, " + + "TEMP_PASSWORD = ? " + + "WHERE ID = ?"; + try { + Connection conn = this.getDBConnection(); + long updatedTime = System.currentTimeMillis(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, userDTO.getClientUserId()); + stmt.setString(2, userDTO.getDmUsername()); + stmt.setInt(3, userDTO.getTenantId()); + stmt.setString(4, userDTO.getEmail()); + stmt.setString(5, userDTO.getInviteCode()); + stmt.setString(6, userDTO.getStatus()); + stmt.setLong(7, updatedTime); + stmt.setString(8, userDTO.getManagedId()); + stmt.setString(9, userDTO.getTmpPassword()); + stmt.setInt(10, userDTO.getId()); + stmt.executeUpdate(); + if (stmt.executeUpdate() == 1) { + return userDTO; + } + return null; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when updating the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to updating the vpp user."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + public VppUserDTO getUserByDMUsername(String emmUsername) + throws ApplicationManagementDAOException { + String sql = "SELECT " + + "ID, " + + "CLIENT_USER_ID, " + + "TENANT_ID, " + + "EMAIL, " + + "INVITE_CODE, " + + "STATUS, " + + "CREATED_TIME, " + + "LAST_UPDATED_TIME, " + + "MANAGED_ID, " + + "TEMP_PASSWORD " + + "FROM AP_VPP_USER " + + "WHERE DM_USERNAME = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, emmUsername); + try (ResultSet rs = stmt.executeQuery()) { + return DAOUtil.loadVppUser(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when retrieving vpp user by EMM Username."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to retrieve vpp user by EMM Username."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one user for: " + emmUsername; + 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/vpp/OracleVppApplicationDAOImpl.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/OracleVppApplicationDAOImpl.java new file mode 100644 index 0000000000..fd5f5cc9d3 --- /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/dao/impl/vpp/OracleVppApplicationDAOImpl.java @@ -0,0 +1,64 @@ +package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.*; + +public class OracleVppApplicationDAOImpl extends GenericVppApplicationDAOImpl { + + private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); + + @Override + public int addVppUser(VppUserDTO userDTO) + throws ApplicationManagementDAOException { + int vppUserId = -1; + String sql = "INSERT INTO " + + "AP_VPP_USER(" + + "CLIENT_USER_ID, " + + "DM_USERNAME, " + + "TENANT_ID, " + + "EMAIL, " + + "INVITE_CODE, " + + "STATUS," + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "MANAGED_ID," + + "TEMP_PASSWORD) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, new String[] {"ID"})) { + long currentTime = System.currentTimeMillis(); + stmt.setString(1, userDTO.getClientUserId()); + stmt.setString(2, userDTO.getDmUsername()); + stmt.setInt(3, userDTO.getTenantId()); + stmt.setString(4, userDTO.getEmail()); + stmt.setString(5, userDTO.getInviteCode()); + stmt.setString(6, userDTO.getStatus()); + stmt.setLong(7, currentTime); + stmt.setLong(8, currentTime); + stmt.setString(9, userDTO.getManagedId()); + stmt.setString(10, userDTO.getTmpPassword()); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + vppUserId = rs.getInt(1); + } + } + return vppUserId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the vpp user."; + 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/vpp/PostgreSQLVppApplicationDAO.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/PostgreSQLVppApplicationDAO.java new file mode 100644 index 0000000000..7dd20ff6f4 --- /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/dao/impl/vpp/PostgreSQLVppApplicationDAO.java @@ -0,0 +1,63 @@ +package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.*; + +public class PostgreSQLVppApplicationDAO extends GenericVppApplicationDAOImpl { + + private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); + + public int addVppUser(VppUserDTO userDTO) + throws ApplicationManagementDAOException { + int vppUserId = -1; + String sql = "INSERT INTO " + + "AP_VPP_USER(" + + "CLIENT_USER_ID, " + + "DM_USERNAME, " + + "TENANT_ID, " + + "EMAIL, " + + "INVITE_CODE, " + + "STATUS," + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "MANAGED_ID," + + "TEMP_PASSWORD) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, new String[]{"ID"})) { + long currentTime = System.currentTimeMillis(); + stmt.setString(1, userDTO.getClientUserId()); + stmt.setString(2, userDTO.getDmUsername()); + stmt.setInt(3, userDTO.getTenantId()); + stmt.setString(4, userDTO.getEmail()); + stmt.setString(5, userDTO.getInviteCode()); + stmt.setString(6, userDTO.getStatus()); + stmt.setLong(7, currentTime); + stmt.setLong(8, currentTime); + stmt.setString(9, userDTO.getManagedId()); + stmt.setString(10, userDTO.getTmpPassword()); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + vppUserId = rs.getInt(1); + } + } + return vppUserId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the vpp user."; + 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/vpp/SQLServerVppApplicationDAOImpl.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/SQLServerVppApplicationDAOImpl.java new file mode 100644 index 0000000000..dc110b03f4 --- /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/dao/impl/vpp/SQLServerVppApplicationDAOImpl.java @@ -0,0 +1,4 @@ +package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; + +public class SQLServerVppApplicationDAOImpl extends GenericVppApplicationDAOImpl { +} 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index 6ec3023def..011a2e3868 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -24,6 +24,8 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.common.exception.TransactionManagementException; import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserRequestWrapper; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; @@ -32,9 +34,12 @@ import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserResp import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.VisibilityDAO; +import io.entgra.device.mgt.core.application.mgt.core.dao.VppApplicationDAO; 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.internal.DataHolder; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; +import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.VppHttpUtil; import org.apache.commons.logging.Log; @@ -56,6 +61,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { private SPApplicationDAO spApplicationDAO; private VisibilityDAO visibilityDAO; private final LifecycleStateManager lifecycleStateManager; + private VppApplicationDAO vppApplicationDAO; public VppApplicationManagerImpl() { initDataAccessObjects(); @@ -66,6 +72,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); this.visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO(); this.spApplicationDAO = ApplicationManagementDAOFactory.getSPApplicationDAO(); + this.vppApplicationDAO = ApplicationManagementDAOFactory.getVppApplicationDAO(); } @Override @@ -96,10 +103,30 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { .getInviteCode()); userDTO.setStatus(vppItuneUserResponseWrapper.getUser().get(0).getStatus()); log.error("userDTO " + userDTO.toString()); - // TODO: Save the userDTO in the DAO - - - return userDTO; + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.addVppUser(userDTO) != -1) { + ConnectionManagerUtil.commitDBTransaction(); + return userDTO; + } + ConnectionManagerUtil.rollbackDBTransaction(); + return null; + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while adding the Vpp User."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for adding Vpp User."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for adding Vpp User."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } } } @@ -113,8 +140,20 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { @Override public VppUserDTO getUserByDMUsername(String emmUsername) throws ApplicationManagementException { - // TODO: Return from DAO in a tenanted manner - return null; + try { + ConnectionManagerUtil.openDBConnection(); + return vppApplicationDAO.getUserByDMUsername(emmUsername); + } catch (DBConnectionException e) { + String msg = "DB Connection error occurs while getting vpp User data related to EMM user " + emmUsername + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while getting vpp User data related to EMM user " + emmUsername + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } } @Override @@ -131,12 +170,35 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { log.error("userDTO " + userDTO.toString()); - // TODO: Save the userDTO in the DAO - + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.updateVppUser(userDTO) == null) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Unable to update the Vpp user " +userDTO.getId(); + log.error(msg); + throw new ApplicationManagementException(msg); + } + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while updating the Vpp User."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for Vpp User update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for Vpp User update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } } } catch (IOException e) { - String msg = "Error while callng VPP backend to update"; + String msg = "Error while calling VPP backend to update"; log.error(msg, e); throw new ApplicationManagementException(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/util/DAOUtil.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/DAOUtil.java index 1960230759..89b5ac01ca 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/DAOUtil.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/DAOUtil.java @@ -32,6 +32,7 @@ import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDT import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ReviewDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import java.sql.PreparedStatement; @@ -43,6 +44,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Date; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -344,6 +346,42 @@ public class DAOUtil { return subscriptionDTOS; } + public static VppUserDTO loadVppUser(ResultSet rs) throws SQLException, UnexpectedServerErrorException { + List vppUserDTOS = loadVppUsers(rs); + if (vppUserDTOS.isEmpty()) { + return null; + } + if (vppUserDTOS.size() > 1) { + String msg = "Internal server error. Found more than one vpp user for requested emmUsername"; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return vppUserDTOS.get(0); + } + + public static List loadVppUsers (ResultSet rs) throws SQLException { + List vppUserDTOS = new ArrayList<>(); + while (rs.next()) { + VppUserDTO vppUserDTO = new VppUserDTO(); + vppUserDTO.setId(rs.getInt("ID")); + vppUserDTO.setClientUserId(rs.getString("CLIENT_USER_ID")); + vppUserDTO.setTenantId(rs.getInt("TENANT_ID")); + vppUserDTO.setEmail(rs.getString("EMAIL")); + vppUserDTO.setInviteCode(rs.getString("INVITE_CODE")); + vppUserDTO.setStatus(rs.getString("STATUS")); + vppUserDTO.setManagedId(rs.getString("MANAGED_ID")); + vppUserDTO.setTmpPassword(rs.getString("TEMP_PASSWORD")); + if (rs.getLong("CREATED_TIME") != 0) { + vppUserDTO.setCreatedTime(new Date(rs.getLong(("CREATED_TIME")) * 1000).toString()); + } + if (rs.getLong("LAST_UPDATED_TIME") != 0) { + vppUserDTO.setLastUpdatedTime(new Date(rs.getLong(("LAST_UPDATED_TIME")) * 1000).toString()); + } + vppUserDTOS.add(vppUserDTO); + } + return vppUserDTOS; + } + /** * Cleans up the statement and resultset after executing the query * From 665702d50447682288a329532a85fe9caec0ea64 Mon Sep 17 00:00:00 2001 From: inoshperera Date: Wed, 28 Jun 2023 21:08:20 +0530 Subject: [PATCH 04/36] Add asset apis Fixes https://roadmap.entgra.net/issues/10178 --- .../mgt/common/dto/ItuneAppDTO.java | 95 ++++++ .../mgt/common/dto/VppAssetDTO.java | 67 ++++ .../mgt/common/dto/VppItuneAssetDTO.java | 109 +++++++ .../mgt/common/dto/VppPaginationDTO.java | 9 + .../services/VPPApplicationManager.java | 5 + .../wrapper/VppItuneAssetResponseWrapper.java | 39 +++ .../core/impl/VppApplicationManagerImpl.java | 135 +++++++- .../core/util/ApplicationManagementUtil.java | 295 +++++++++++++++++- .../application/mgt/core/util/Constants.java | 28 +- 9 files changed, 766 insertions(+), 16 deletions(-) create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ItuneAppDTO.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssetDTO.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneAssetDTO.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppItuneAssetResponseWrapper.java 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/dto/ItuneAppDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/ItuneAppDTO.java new file mode 100644 index 0000000000..a76a9ec12b --- /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/dto/ItuneAppDTO.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.dto; + +public class ItuneAppDTO { + int id; + String packageName; + String version; + String description; + String title; + String paymentMethod; + String iconURL; + String category; + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getIconURL() { + return iconURL; + } + + public void setIconURL(String iconURL) { + this.iconURL = iconURL; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getPaymentMethod() { + return paymentMethod; + } + + public void setPaymentMethod(String paymentMethod) { + this.paymentMethod = paymentMethod; + } + +} 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/dto/VppAssetDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssetDTO.java new file mode 100644 index 0000000000..1ce0d3c3cf --- /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/dto/VppAssetDTO.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppAssetDTO extends VppItuneAssetDTO { + int id; + int appId; + int tenantId; + String createdTime; + String lastUpdatedTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getAppId() { + return appId; + } + + public void setAppId(int appId) { + this.appId = appId; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + public String getLastUpdatedTime() { + return lastUpdatedTime; + } + + public void setLastUpdatedTime(String lastUpdatedTime) { + this.lastUpdatedTime = lastUpdatedTime; + } + +} \ No newline at end of file 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/dto/VppItuneAssetDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppItuneAssetDTO.java new file mode 100644 index 0000000000..71e9429c68 --- /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/dto/VppItuneAssetDTO.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the String LicenseString ); 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 + * String AS ISString 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.dto; + +import java.util.List; + +public class VppItuneAssetDTO { + + + String adamId; + String assignedCount; + String availableCount; + String deviceAssignable; + String pricingParam; + String productType; + String retiredCount; + String revocable; + + List supportedPlatforms; + + public List getSupportedPlatforms() { + return supportedPlatforms; + } + + public void setSupportedPlatforms(List supportedPlatforms) { + this.supportedPlatforms = supportedPlatforms; + } + + public String getAdamId() { + return adamId; + } + + public void setAdamId(String adamId) { + this.adamId = adamId; + } + + public String getAssignedCount() { + return assignedCount; + } + + public void setAssignedCount(String assignedCount) { + this.assignedCount = assignedCount; + } + + public String getAvailableCount() { + return availableCount; + } + + public void setAvailableCount(String availableCount) { + this.availableCount = availableCount; + } + + public String getDeviceAssignable() { + return deviceAssignable; + } + + public void setDeviceAssignable(String deviceAssignable) { + this.deviceAssignable = deviceAssignable; + } + + public String getPricingParam() { + return pricingParam; + } + + public void setPricingParam(String pricingParam) { + this.pricingParam = pricingParam; + } + + public String getProductType() { + return productType; + } + + public void setProductType(String productType) { + this.productType = productType; + } + + public String getRetiredCount() { + return retiredCount; + } + + public void setRetiredCount(String retiredCount) { + this.retiredCount = retiredCount; + } + + public String getRevocable() { + return revocable; + } + + public void setRevocable(String revocable) { + this.revocable = revocable; + } + + +} \ No newline at end of file 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/dto/VppPaginationDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppPaginationDTO.java index 32c4f12f9b..95cf054f9c 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppPaginationDTO.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppPaginationDTO.java @@ -22,6 +22,7 @@ public class VppPaginationDTO { int currentPageIndex; int size; String tokenExpirationDate; + int nextPageIndex; int totalPages; String uId; String versionId; @@ -50,6 +51,14 @@ public class VppPaginationDTO { this.tokenExpirationDate = tokenExpirationDate; } + public int getNextPageIndex() { + return nextPageIndex; + } + + public void setNextPageIndex(int nextPageIndex) { + this.nextPageIndex = nextPageIndex; + } + public int getTotalPages() { return totalPages; } 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/VPPApplicationManager.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/VPPApplicationManager.java index 4b08001e08..55a3ee51b8 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/VPPApplicationManager.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/VPPApplicationManager.java @@ -19,6 +19,7 @@ package io.entgra.device.mgt.core.application.mgt.common.services; import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; @@ -34,5 +35,9 @@ public interface VPPApplicationManager { void syncUsers(String clientId) throws ApplicationManagementException; + void syncAssets(int nextPageIndex) throws ApplicationManagementException; + + VppAssetDTO getAssetByAppId(String appId) throws ApplicationManagementException; + ProxyResponse callVPPBackend(String url, String payload, String accessToken, String method) throws IOException; } 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/VppItuneAssetResponseWrapper.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/VppItuneAssetResponseWrapper.java new file mode 100644 index 0000000000..26c45207ab --- /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/VppItuneAssetResponseWrapper.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.wrapper; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppPaginationDTO; + +import java.util.ArrayList; +import java.util.List; + +public class VppItuneAssetResponseWrapper extends VppPaginationDTO { + + List assets; + + public List getAssets() { + return assets; + } + + public void setAssets(List assets) { + this.assets = assets; + } + +} 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index 6ec3023def..37cf50a394 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -18,16 +18,18 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; -import com.google.gson.ExclusionStrategy; -import com.google.gson.FieldAttributes; import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import io.entgra.device.mgt.core.application.mgt.common.dto.ItuneAppDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserRequestWrapper; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneAssetResponseWrapper; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserRequestWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserResponseWrapper; import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.SPApplicationDAO; @@ -35,11 +37,13 @@ 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.internal.DataHolder; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; +import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.VppHttpUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpStatus; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.IOException; @@ -50,8 +54,14 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { private static final String USER_UPDATE = APP_API + "/users/update"; private static final String USER_GET = APP_API + "/users"; private static final String TOKEN = ""; + private static final String LOOKUP_API = "https://uclient-api.itunes.apple" + + ".com/WebObjects/MZStorePlatform.woa/wa/lookup?version=2&id="; + private static final String LOOKUP_API_PREFIX = + "&p=mdm-lockup&caller=MDM&platform=enterprisestore&cc=us&l=en"; + private static final Log log = LogFactory.getLog(VppApplicationManagerImpl.class); + private ApplicationDAO applicationDAO; private SPApplicationDAO spApplicationDAO; private VisibilityDAO visibilityDAO; @@ -154,6 +164,56 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { Gson gson = new Gson(); VppItuneUserResponseWrapper vppUserResponseWrapper = gson.fromJson (proxyResponse.getData(), VppItuneUserResponseWrapper.class); + // TODO: to implement later + } + } catch (IOException e) { + String msg = "Error while syncing VPP users with backend"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + + } + + @Override + public void syncAssets(int nextPageIndex) throws ApplicationManagementException { + ProxyResponse proxyResponse = null; + try { + String url = ASSETS; + if (nextPageIndex > 0) { // Not the first page + url += "?pageIndex=" + nextPageIndex; + } + proxyResponse = callVPPBackend(url, null, TOKEN, Constants.VPP.GET); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { + Gson gson = new Gson(); + VppItuneAssetResponseWrapper vppItuneAssetResponse = gson.fromJson + (proxyResponse.getData(), VppItuneAssetResponseWrapper.class); + if (vppItuneAssetResponse.getSize() > 0) { + for (VppAssetDTO vppAssetDTO : vppItuneAssetResponse.getAssets()) { + vppAssetDTO.setTenantId(PrivilegedCarbonContext + .getThreadLocalCarbonContext().getTenantId()); + vppAssetDTO.setCreatedTime(String.valueOf(System.currentTimeMillis())); + vppAssetDTO.setLastUpdatedTime(String.valueOf(System.currentTimeMillis())); + } + + for (VppAssetDTO vppAssetDTO : vppItuneAssetResponse.getAssets()) { + ItuneAppDTO ituneAppDTO = lookupAsset(vppAssetDTO.getAdamId()); + ApplicationManagementUtil.persistApp(ituneAppDTO); + } + + // TODO: Store/update vppItuneAssetResponse.getAssets() in the DB + + // TODO: END of DAO access + + } + + + if (vppItuneAssetResponse.getCurrentPageIndex() == (vppItuneAssetResponse + .getTotalPages() - 1)) { + return; + } else { + syncAssets(vppItuneAssetResponse.getNextPageIndex()); + } } } catch (IOException e) { String msg = "Error while syncing VPP users with backend"; @@ -161,6 +221,73 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { throw new ApplicationManagementException(msg, e); } + + } + + private ItuneAppDTO lookupAsset(String packageName) throws ApplicationManagementException { + String lookupURL = LOOKUP_API + packageName + LOOKUP_API_PREFIX; + try { + ProxyResponse proxyResponse = callVPPBackend(lookupURL, null, TOKEN, Constants.VPP.GET); + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.GET_APP_DATA_RESPONSE_START)) { + String responseData = proxyResponse.getData(); + JsonObject responseJson = new JsonParser().parse(responseData) + .getAsJsonObject(); + + JsonObject results = responseJson.getAsJsonObject(Constants.ApplicationProperties.RESULTS); + JsonObject result = results.getAsJsonObject(packageName); + + String iconUrl = result.getAsJsonObject(Constants.ApplicationProperties.ARTWORK) + .get(Constants.ApplicationProperties.URL).getAsString(); + int lastSlashIndex = iconUrl.lastIndexOf("/"); + if (lastSlashIndex != -1) { + iconUrl = iconUrl.substring(0, lastSlashIndex + 1) + Constants.VPP.REMOTE_FILE_NAME; + } + + String descriptionStandard = result.getAsJsonObject(Constants.ApplicationProperties.DESCRIPTION) + .get(Constants.ApplicationProperties.STANDARD).getAsString(); + if (descriptionStandard != null && !descriptionStandard.isEmpty()) { + descriptionStandard = descriptionStandard.substring(0, 199); + } + String name = result.get(Constants.ApplicationProperties.NAME).getAsString(); + double price = result.getAsJsonArray(Constants.ApplicationProperties.OFFERS).get(0) + .getAsJsonObject().get(Constants.ApplicationProperties.PRICE).getAsDouble(); + String version = result.getAsJsonArray(Constants.ApplicationProperties.OFFERS) + .get(0).getAsJsonObject().get(Constants.ApplicationProperties.VERSION) + .getAsJsonObject().get(Constants.ApplicationProperties.DISPLAY).getAsString(); + + String[] genreNames = new Gson().fromJson(result.getAsJsonArray(Constants.ApplicationProperties.GENRE_NAMES), + String[].class); + + ItuneAppDTO ituneAppDTO = new ItuneAppDTO(); + ituneAppDTO.setPackageName(packageName); + ituneAppDTO.setVersion(version); + ituneAppDTO.setDescription(descriptionStandard); + ituneAppDTO.setTitle(name); + + if (Constants.ApplicationProperties.PRICE_ZERO.equalsIgnoreCase(String.valueOf(price))) { + ituneAppDTO.setPaymentMethod(Constants.ApplicationProperties.FREE_SUB_METHOD); + } else { + ituneAppDTO.setPaymentMethod(Constants.ApplicationProperties.PAID_SUB_METHOD); + } + ituneAppDTO.setIconURL(iconUrl); + ituneAppDTO.setCategory(genreNames[0]); + + return ituneAppDTO; + } + } catch (IOException e) { + String msg = "Error while looking up the app details"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + return null; + } + + + public VppAssetDTO getAssetByAppId(String appId) throws ApplicationManagementException { + // App ID is the app id of the App management database + VppAssetDTO assetDTO = null; // TODO: load from the DB + return assetDTO; } @Override 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 55bf0b1a72..8ae9a580f4 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 @@ -18,15 +18,21 @@ package io.entgra.device.mgt.core.application.mgt.core.util; import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; -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.device.mgt.common.Base64File; import io.entgra.device.mgt.core.application.mgt.common.FileDataHolder; +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.ItuneAppDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; +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.ReviewManager; import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationUpdateWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppReleaseWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppWrapper; @@ -35,18 +41,31 @@ import io.entgra.device.mgt.core.application.mgt.common.wrapper.PublicAppRelease 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 org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.application.mgt.common.exception.InvalidConfigurationException; -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.ReviewManager; -import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +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.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.core.common.util.FileUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -247,4 +266,258 @@ public class ApplicationManagementUtil { throw new InvalidConfigurationException(msg, e); } } + + public static void persistApp(ItuneAppDTO product) throws ApplicationManagementException { + 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); + + if (existingApps != null && existingApps.size() > 0) { + Application app = existingApps.get(0); + if (product.getPackageName().equals(app.getPackageName())) { + 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); + } else { + publicAppReleaseWrapper.setPrice(1.0); + } + + publicAppReleaseWrapper.setDescription(product.getDescription()); + publicAppReleaseWrapper.setReleaseType("ga"); + publicAppReleaseWrapper.setVersion(product.getVersion()); + publicAppReleaseWrapper.setSupportedOsVersions("4.0-12.3"); + applicationManager.updatePubAppRelease(app.getApplicationReleases().get(0).getUuid(), + publicAppReleaseWrapper, applicationArtifact); + 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); + } + } + } + } + + private static PublicAppWrapper generatePubAppWrapper(ItuneAppDTO product, List categories) { + PublicAppWrapper publicAppWrapper = new PublicAppWrapper(); + publicAppWrapper.setName(product.getTitle()); + publicAppWrapper.setDescription(product.getDescription()); + publicAppWrapper.setCategories( + Collections.singletonList(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY));//Default category + for (Category category : categories) { + if (product.getCategory() == null) { + List pubAppCategories = new ArrayList<>(); + pubAppCategories.add(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY); + publicAppWrapper.setCategories(pubAppCategories); + break; + } else if (product.getCategory().equalsIgnoreCase(category.getCategoryName())) { + List pubAppCategories = new ArrayList<>(); + pubAppCategories.add(category.getCategoryName()); + pubAppCategories.add(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY); + publicAppWrapper.setCategories(pubAppCategories); + break; + } + } + if (product.getPaymentMethod().equalsIgnoreCase(Constants.ApplicationProperties.FREE_SUB_METHOD)) { + publicAppWrapper.setSubMethod(Constants.ApplicationProperties.FREE_SUB_METHOD); + } else { + publicAppWrapper.setSubMethod(Constants.ApplicationProperties.PAID_SUB_METHOD); + } + // TODO: purchase an app from app store and see how to capture the real value for price + // field. + publicAppWrapper.setPaymentCurrency("$"); + publicAppWrapper.setDeviceType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS); + return publicAppWrapper; + } + + private static ApplicationUpdateWrapper generatePubAppUpdateWrapper(ItuneAppDTO product, List categories) { + ApplicationUpdateWrapper applicationUpdateWrapper = new ApplicationUpdateWrapper(); + applicationUpdateWrapper.setName(product.getTitle()); + applicationUpdateWrapper.setDescription(product.getDescription()); + applicationUpdateWrapper.setCategories( + Collections.singletonList(Constants + .ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY));//Default + // add the default APPLE_STORE_SYNCED_APP_CATEGORY + for (Category category : categories) { + if (product.getCategory() == null) { + List pubAppCategories = new ArrayList<>(); + pubAppCategories.add(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY); + applicationUpdateWrapper.setCategories(pubAppCategories); + break; + } else if (product.getCategory().equalsIgnoreCase(category.getCategoryName())) { + List pubAppCategories = new ArrayList<>(); + pubAppCategories.add(category.getCategoryName()); + pubAppCategories.add(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY); + applicationUpdateWrapper.setCategories(pubAppCategories); + break; + } + } + if (product.getPaymentMethod().equalsIgnoreCase(Constants.ApplicationProperties.FREE_SUB_METHOD)) { + applicationUpdateWrapper.setSubMethod(Constants.ApplicationProperties.FREE_SUB_METHOD); + } else { + applicationUpdateWrapper.setSubMethod(Constants.ApplicationProperties.PAID_SUB_METHOD); + } + // TODO: purchase an app from Playstore and see how to capture the real value for price field. + applicationUpdateWrapper.setPaymentCurrency("$"); + return applicationUpdateWrapper; + } + + private static ApplicationArtifact generateArtifacts(ItuneAppDTO product) throws ApplicationManagementException { + ApplicationArtifact applicationArtifact = new ApplicationArtifact(); + String prefix = product.getPackageName(); + try { + String iconName = prefix + "_icon"; + applicationArtifact.setIconName(iconName); + InputStream iconInputStream = getInputStream(iconName, product.getIconURL()); + applicationArtifact.setIconStream(iconInputStream); + Map screenshotMap = new HashMap<>(); + // TODO: look for a way to get screenshots + + for (int a = 0; a < 3; a++) { + String screenshotName = product.getPackageName() + a; + InputStream screenshotInputStream = getInputStream(screenshotName, product.getIconURL()); + screenshotMap.put(screenshotName, screenshotInputStream); + } + + applicationArtifact.setScreenshots(screenshotMap); + return applicationArtifact; + } catch (ApplicationManagementException e) { + String msg = "Error occurred while generating Application artifact"; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + } + + private static InputStream getInputStream(String filename, String url) throws ApplicationManagementException { + URL website; + try { + website = new URL(url); + } catch (MalformedURLException e) { + String msg = "Error occurred while converting the url " + url; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + ReadableByteChannel rbc = null; + FileOutputStream fos = null; + try { + rbc = Channels.newChannel(website.openStream()); + fos = new FileOutputStream(System.getProperty("java.io.tmpdir") + + File.separator + filename); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + } catch (IOException e) { + String msg = "Error occurred while opening stream for url " + url; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } finally { + try { + fos.close(); + rbc.close(); + } catch (IOException e) { + } + } + + File file = new File(System.getProperty("java.io.tmpdir") + File.separator + filename); + InputStream targetStream; + try { + targetStream = new FileInputStream(file); + } catch (FileNotFoundException e) { + String msg = "Error occurred while reading the tmp file " + System.getProperty("java.io.tmpdir") + + File.separator + filename; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + file.deleteOnExit(); + return targetStream; + } + + private static void updateImages(PublicAppReleaseWrapper appReleaseWrapper, String iconName, + InputStream iconStream, Map + screenshotsMaps) throws IOException { + List screenshots = new ArrayList<>(); + Base64File iconFile = new Base64File(iconName, + convertStreamToBase64(iconStream)); + appReleaseWrapper.setIcon(iconFile); + if (screenshotsMaps.size() > 0) { + for (Map.Entry screenshotEntry : screenshotsMaps.entrySet()) { + Base64File screenshot = new Base64File(screenshotEntry.getKey(), + convertStreamToBase64(screenshotEntry.getValue())); + screenshots.add(screenshot); + } + appReleaseWrapper.setScreenshots(screenshots); + } + } + + private static String convertStreamToBase64(InputStream inputStream) throws IOException { + final int bufLen = 4 * 0x400; // 4KB + byte[] buf = new byte[bufLen]; + int readLen; + + try { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + while ((readLen = inputStream.read(buf, 0, bufLen)) != -1) + outputStream.write(buf, 0, readLen); + + return Base64.getEncoder().encodeToString(outputStream.toByteArray()); + } + } catch (IOException e) { + String msg = "Error while converting image to base64"; + log.error(msg); + throw e; + } finally { + try { + inputStream.close(); + } catch (IOException 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/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 ce61c1a81b..7b804e7fa8 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 @@ -109,10 +109,11 @@ public class Constants { public static final String POST = "POST"; public static final String PUT = "PUT"; public static final String DELETE = "DELETE"; - public static final String CLIENT_USER_ID = "clientUserId"; public static final String EVENT_ID = "eventId"; public static final String CLIENT_USER_ID_PARAM = "?clientUserId="; public static final String TOTAL_PAGES = "totalPages"; + public static final String GET_APP_DATA_RESPONSE_START = "results"; + public static final String REMOTE_FILE_NAME = "512x512w.png"; private VPP() { } @@ -182,4 +183,29 @@ public class Constants { public static final String AUTHORIZATION = "Authorization"; public static final String AUTHORIZATION_HEADER_VALUE = "Bearer "; } + + public final class ApplicationProperties { + private ApplicationProperties() { + throw new AssertionError(); + } + + public static final String NAME = "name"; + public static final String VERSION = "version"; + public static final String FREE_SUB_METHOD = "FREE"; + public static final String PAID_SUB_METHOD = "PAID"; + public static final String TYPE = "type";; + public static final String PACKAGE_NAME = "packageName"; + public static final String APPLE_STORE_SYNCED_APP_CATEGORY = "APPLE_STORE_SYNCED_APP"; + + public static final String RESULTS = "results"; + public static final String ARTWORK = "artwork"; + public static final String URL = "url"; + public static final String DESCRIPTION = "description"; + public static final String STANDARD = "standard"; + public static final String OFFERS = "offers"; + public static final String PRICE = "price"; + public static final String DISPLAY = "display"; + public static final String GENRE_NAMES = "genreNames"; + public static final String PRICE_ZERO = "0.0"; + } } From 2e799a545feb33dfd4618f38e9d5ed31e53cd615 Mon Sep 17 00:00:00 2001 From: osh Date: Wed, 28 Jun 2023 21:43:06 +0530 Subject: [PATCH 05/36] Resolve comments --- .../mgt/core/dao/VppApplicationDAO.java | 24 ++++++++++++-- .../vpp/GenericVppApplicationDAOImpl.java | 31 +++++++++++++++---- .../impl/vpp/OracleVppApplicationDAOImpl.java | 22 +++++++++++-- .../impl/vpp/PostgreSQLVppApplicationDAO.java | 22 +++++++++++-- .../vpp/SQLServerVppApplicationDAOImpl.java | 18 +++++++++++ .../core/impl/VppApplicationManagerImpl.java | 12 +++++-- 6 files changed, 113 insertions(+), 16 deletions(-) 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 ae2b75e515..6ebec3f0e7 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 @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package io.entgra.device.mgt.core.application.mgt.core.dao; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; @@ -6,9 +24,9 @@ import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManag public interface VppApplicationDAO { - int addVppUser(VppUserDTO userDTO) throws ApplicationManagementDAOException; + int addVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException; - VppUserDTO updateVppUser(VppUserDTO userDTO) throws ApplicationManagementDAOException; + VppUserDTO updateVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException; - VppUserDTO getUserByDMUsername(String emmUsername) throws ApplicationManagementDAOException; + VppUserDTO getUserByDMUsername(String emmUsername, 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/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 3dc356b764..2bafc338f3 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 @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; @@ -16,7 +34,7 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); @Override - public int addVppUser(VppUserDTO userDTO) + public int addVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException { int vppUserId = -1; String sql = "INSERT INTO " @@ -38,7 +56,7 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp long currentTime = System.currentTimeMillis(); stmt.setString(1, userDTO.getClientUserId()); stmt.setString(2, userDTO.getDmUsername()); - stmt.setInt(3, userDTO.getTenantId()); + stmt.setInt(3, tenantId); stmt.setString(4, userDTO.getEmail()); stmt.setString(5, userDTO.getInviteCode()); stmt.setString(6, userDTO.getStatus()); @@ -65,7 +83,7 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp } } - public VppUserDTO updateVppUser(VppUserDTO userDTO) + public VppUserDTO updateVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException { String sql = "UPDATE " @@ -87,7 +105,7 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, userDTO.getClientUserId()); stmt.setString(2, userDTO.getDmUsername()); - stmt.setInt(3, userDTO.getTenantId()); + stmt.setInt(3, tenantId); stmt.setString(4, userDTO.getEmail()); stmt.setString(5, userDTO.getInviteCode()); stmt.setString(6, userDTO.getStatus()); @@ -112,7 +130,7 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp } } - public VppUserDTO getUserByDMUsername(String emmUsername) + public VppUserDTO getUserByDMUsername(String emmUsername, int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT " + "ID, " @@ -126,11 +144,12 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp + "MANAGED_ID, " + "TEMP_PASSWORD " + "FROM AP_VPP_USER " - + "WHERE DM_USERNAME = ?"; + + "WHERE DM_USERNAME = ? AND TENANT_ID = ?"; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, emmUsername); + stmt.setInt(2, tenantId); try (ResultSet rs = stmt.executeQuery()) { return DAOUtil.loadVppUser(rs); } 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/OracleVppApplicationDAOImpl.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/OracleVppApplicationDAOImpl.java index fd5f5cc9d3..480f18006e 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/OracleVppApplicationDAOImpl.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/OracleVppApplicationDAOImpl.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; @@ -13,7 +31,7 @@ public class OracleVppApplicationDAOImpl extends GenericVppApplicationDAOImpl { private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); @Override - public int addVppUser(VppUserDTO userDTO) + public int addVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException { int vppUserId = -1; String sql = "INSERT INTO " @@ -35,7 +53,7 @@ public class OracleVppApplicationDAOImpl extends GenericVppApplicationDAOImpl { long currentTime = System.currentTimeMillis(); stmt.setString(1, userDTO.getClientUserId()); stmt.setString(2, userDTO.getDmUsername()); - stmt.setInt(3, userDTO.getTenantId()); + stmt.setInt(3, tenantId); stmt.setString(4, userDTO.getEmail()); stmt.setString(5, userDTO.getInviteCode()); stmt.setString(6, userDTO.getStatus()); 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/PostgreSQLVppApplicationDAO.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/PostgreSQLVppApplicationDAO.java index 7dd20ff6f4..5d9fe7a8f6 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/PostgreSQLVppApplicationDAO.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/PostgreSQLVppApplicationDAO.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; @@ -12,7 +30,7 @@ public class PostgreSQLVppApplicationDAO extends GenericVppApplicationDAOImpl { private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); - public int addVppUser(VppUserDTO userDTO) + public int addVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException { int vppUserId = -1; String sql = "INSERT INTO " @@ -34,7 +52,7 @@ public class PostgreSQLVppApplicationDAO extends GenericVppApplicationDAOImpl { long currentTime = System.currentTimeMillis(); stmt.setString(1, userDTO.getClientUserId()); stmt.setString(2, userDTO.getDmUsername()); - stmt.setInt(3, userDTO.getTenantId()); + stmt.setInt(3, tenantId); stmt.setString(4, userDTO.getEmail()); stmt.setString(5, userDTO.getInviteCode()); stmt.setString(6, userDTO.getStatus()); 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/SQLServerVppApplicationDAOImpl.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/SQLServerVppApplicationDAOImpl.java index dc110b03f4..da4e4828da 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/SQLServerVppApplicationDAOImpl.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/SQLServerVppApplicationDAOImpl.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; public class SQLServerVppApplicationDAOImpl extends GenericVppApplicationDAOImpl { 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index 011a2e3868..468fc17304 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -45,6 +45,7 @@ import io.entgra.device.mgt.core.application.mgt.core.util.VppHttpUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpStatus; +import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.IOException; @@ -77,6 +78,9 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { @Override public VppUserDTO addUser(VppUserDTO userDTO) throws ApplicationManagementException { + + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + // Call the API to add try { VppItuneUserDTO ituneUserDTO = userDTO; @@ -105,7 +109,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { log.error("userDTO " + userDTO.toString()); try { ConnectionManagerUtil.beginDBTransaction(); - if (vppApplicationDAO.addVppUser(userDTO) != -1) { + if (vppApplicationDAO.addVppUser(userDTO, tenantId) != -1) { ConnectionManagerUtil.commitDBTransaction(); return userDTO; } @@ -140,9 +144,10 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { @Override public VppUserDTO getUserByDMUsername(String emmUsername) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { ConnectionManagerUtil.openDBConnection(); - return vppApplicationDAO.getUserByDMUsername(emmUsername); + return vppApplicationDAO.getUserByDMUsername(emmUsername, tenantId); } catch (DBConnectionException e) { String msg = "DB Connection error occurs while getting vpp User data related to EMM user " + emmUsername + "."; log.error(msg, e); @@ -158,6 +163,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { @Override public void updateUser(VppUserDTO userDTO) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); VppItuneUserDTO ituneUserDTO = userDTO; VppItuneUserRequestWrapper wrapper = new VppItuneUserRequestWrapper(); wrapper.getUser().add(ituneUserDTO); @@ -173,7 +179,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { try { ConnectionManagerUtil.beginDBTransaction(); - if (vppApplicationDAO.updateVppUser(userDTO) == null) { + if (vppApplicationDAO.updateVppUser(userDTO, tenantId) == null) { ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Unable to update the Vpp user " +userDTO.getId(); log.error(msg); From 54111b4d94da207ae3fe6619aad2917799bdf847 Mon Sep 17 00:00:00 2001 From: inoshperera Date: Fri, 30 Jun 2023 13:32:47 +0530 Subject: [PATCH 06/36] Add association apis fixes https://roadmap.entgra.net/issues/10182 --- .../mgt/common/dto/VppAssociationDTO.java | 113 ++++++++++++++++++ .../mgt/common/response/Application.java | 14 +++ .../services/VPPApplicationManager.java | 4 + .../wrapper/VppAssociateRequestWrapper.java | 47 ++++++++ .../core/impl/SubscriptionManagerImpl.java | 53 ++++++++ .../core/impl/VppApplicationManagerImpl.java | 59 ++++++++- ...ApplicationManagementServiceComponent.java | 19 ++- .../application/mgt/core/util/APIUtil.java | 30 ++++- .../core/util/ApplicationManagementUtil.java | 7 ++ .../application/mgt/core/util/Constants.java | 3 + .../mgt/core/util/VppHttpUtil.java | 20 ++++ 11 files changed, 355 insertions(+), 14 deletions(-) create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssociationDTO.java create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/wrapper/VppAssociateRequestWrapper.java 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/dto/VppAssociationDTO.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/dto/VppAssociationDTO.java new file mode 100644 index 0000000000..b2178febfa --- /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/dto/VppAssociationDTO.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.dto; + +public class VppAssociationDTO { + int id; + String adamId; + String clientUserId; + String pricingParam; + String associationType; + + int assetId; + int clientId; + int tenantId; + String createdTime; + String lastUpdatedTime; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getAdamId() { + return adamId; + } + + public void setAdamId(String adamId) { + this.adamId = adamId; + } + + public String getClientUserId() { + return clientUserId; + } + + public void setClientUserId(String clientUserId) { + this.clientUserId = clientUserId; + } + + public String getPricingParam() { + return pricingParam; + } + + public void setPricingParam(String pricingParam) { + this.pricingParam = pricingParam; + } + + public String getAssociationType() { + return associationType; + } + + public void setAssociationType(String associationType) { + this.associationType = associationType; + } + + public int getAssetId() { + return assetId; + } + + public void setAssetId(int assetId) { + this.assetId = assetId; + } + + public int getClientId() { + return clientId; + } + + public void setClientId(int clientId) { + this.clientId = clientId; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + public String getLastUpdatedTime() { + return lastUpdatedTime; + } + + public void setLastUpdatedTime(String lastUpdatedTime) { + this.lastUpdatedTime = lastUpdatedTime; + } + +} \ No newline at end of file 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/response/Application.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/response/Application.java index 025f352e4c..0d62a46a5b 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/response/Application.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/response/Application.java @@ -108,6 +108,12 @@ public class Application { value = "if the app is favoured by the user") private boolean isFavourite; + @ApiModelProperty(name = "isExternalAppStoreApp", + value = "Is the app coming from an external application store", + required = true, + example = "true or false") + private boolean isExternalAppStoreApp; + public String getPackageName() { return packageName; } @@ -194,4 +200,12 @@ public class Application { public void setFavourite(boolean favourite) { isFavourite = favourite; } + + public boolean isExternalAppStoreApp() { + return isExternalAppStoreApp; + } + + public void setExternalAppStoreApp(boolean externalAppStoreApp) { + isExternalAppStoreApp = externalAppStoreApp; + } } 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/VPPApplicationManager.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/VPPApplicationManager.java index 55a3ee51b8..1113a22777 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/VPPApplicationManager.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/VPPApplicationManager.java @@ -24,6 +24,7 @@ import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import java.io.IOException; +import java.util.List; public interface VPPApplicationManager { @@ -40,4 +41,7 @@ public interface VPPApplicationManager { VppAssetDTO getAssetByAppId(String appId) throws ApplicationManagementException; ProxyResponse callVPPBackend(String url, String payload, String accessToken, String method) throws IOException; + + boolean addAssociation(VppAssetDTO asset, List vppUsers) 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/wrapper/VppAssociateRequestWrapper.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/VppAssociateRequestWrapper.java new file mode 100644 index 0000000000..7cea9d52c8 --- /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/VppAssociateRequestWrapper.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.device.mgt.core.application.mgt.common.wrapper; + +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; + +import java.util.ArrayList; +import java.util.List; + +public class VppAssociateRequestWrapper { + + List assets; + List clientUserIds; + + public List getAssets() { + return assets; + } + + public void setAssets(List assets) { + this.assets = assets; + } + + public List getClientUserIds() { + return clientUserIds; + } + + public void setClientUserIds(List clientUserIds) { + this.clientUserIds = clientUserIds; + } + +} \ No newline at end of file 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/SubscriptionManagerImpl.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/SubscriptionManagerImpl.java index d89039dee5..bb8dd4f6f8 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/SubscriptionManagerImpl.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/SubscriptionManagerImpl.java @@ -19,7 +19,13 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; import com.google.gson.Gson; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.core.dao.VppApplicationDAO; import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; +import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.application.mgt.core.util.VppHttpUtil; import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; import io.entgra.device.mgt.core.notification.logger.AppInstallLogContext; import io.entgra.device.mgt.core.notification.logger.impl.EntgraAppInstallLoggerImpl; @@ -118,12 +124,14 @@ public class SubscriptionManagerImpl implements SubscriptionManager { private static final EntgraLogger log = new EntgraAppInstallLoggerImpl(SubscriptionManagerImpl.class); private SubscriptionDAO subscriptionDAO; private ApplicationDAO applicationDAO; + private VppApplicationDAO vppApplicationDAO; private LifecycleStateManager lifecycleStateManager; public SubscriptionManagerImpl() { this.lifecycleStateManager = DataHolder.getInstance().getLifecycleStateManager(); this.subscriptionDAO = ApplicationManagementDAOFactory.getSubscriptionDAO(); this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); + this.vppApplicationDAO = ApplicationManagementDAOFactory.getVppApplicationDAO(); } @Override @@ -148,6 +156,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { ApplicationDTO applicationDTO = getApplicationDTO(applicationUUID); ApplicationSubscriptionInfo applicationSubscriptionInfo = getAppSubscriptionInfo(applicationDTO, subType, params); + performExternalStoreSubscription(applicationDTO, applicationSubscriptionInfo); ApplicationInstallResponse applicationInstallResponse = performActionOnDevices( applicationSubscriptionInfo.getAppSupportingDeviceTypeName(), applicationSubscriptionInfo.getDevices(), applicationDTO, subType, applicationSubscriptionInfo.getSubscribers(), action, properties, isOperationReExecutingDisabled); @@ -156,6 +165,50 @@ public class SubscriptionManagerImpl implements SubscriptionManager { return applicationInstallResponse; } + private void performExternalStoreSubscription(ApplicationDTO applicationDTO, + ApplicationSubscriptionInfo + applicationSubscriptionInfo) throws ApplicationManagementException { + try { + // Only for iOS devices + if (DeviceTypes.IOS.toString().equalsIgnoreCase(APIUtil.getDeviceTypeData(applicationDTO + .getDeviceTypeId()).getName())) { + // TODO: replace getAssetByAppId with the correct one in DAO + // Check if the app trying to subscribe is a VPP asset. + VppAssetDTO storedAsset = vppApplicationDAO.getAssetByAppId(applicationDTO.getId()); + if (storedAsset != null) { // This is a VPP asset + List users = new ArrayList<>(); + List devices = applicationSubscriptionInfo.getDevices();// get + // subscribed device list, so that we can extract the users of those devices. + for (Device device : devices) { + VppUserDTO user = vppApplicationDAO.getUserByDMUsername(device.getEnrolmentInfo() + .getOwner(), PrivilegedCarbonContext.getThreadLocalCarbonContext() + .getTenantId(true)); + users.add(user); + } + VPPApplicationManager vppManager = APIUtil.getVPPManager(); + vppManager.addAssociation(storedAsset, users); + } + } + } catch (BadRequestException e) { + String msg = "Device Type not found"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Unexpected error while getting device type"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = "Error while getting the device user"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementException e) { + String msg = "Error while associating user"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + + } + @Override public void createScheduledSubscription(ScheduledSubscriptionDTO subscriptionDTO) throws SubscriptionManagementException { 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index 15ec5e3a15..52f4a30dc2 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -24,13 +24,15 @@ import com.google.gson.JsonParser; import io.entgra.device.mgt.core.application.mgt.common.dto.ItuneAppDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneAssetDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; -import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; -import io.entgra.device.mgt.core.application.mgt.common.exception.TransactionManagementException; -import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserRequestWrapper; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; +import io.entgra.device.mgt.core.application.mgt.common.exception.TransactionManagementException; import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; +import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppAssociateRequestWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneAssetResponseWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserRequestWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserResponseWrapper; @@ -52,6 +54,8 @@ import org.apache.http.HttpStatus; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; public class VppApplicationManagerImpl implements VPPApplicationManager { private static final String APP_API = "https://vpp.itunes.apple.com/mdm/v2"; @@ -59,6 +63,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { private static final String USER_CREATE = APP_API + "/users/create"; private static final String USER_UPDATE = APP_API + "/users/update"; private static final String USER_GET = APP_API + "/users"; + private static final String ASSIGNMENTS_POST = APP_API + "/assets/associate"; private static final String TOKEN = ""; private static final String LOOKUP_API = "https://uclient-api.itunes.apple" + ".com/WebObjects/MZStorePlatform.woa/wa/lookup?version=2&id="; @@ -267,6 +272,8 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { for (VppAssetDTO vppAssetDTO : vppItuneAssetResponse.getAssets()) { ItuneAppDTO ituneAppDTO = lookupAsset(vppAssetDTO.getAdamId()); ApplicationManagementUtil.persistApp(ituneAppDTO); + + } // TODO: Store/update vppItuneAssetResponse.getAssets() in the DB @@ -366,4 +373,50 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { return VppHttpUtil.execute(url, payload, accessToken, method); } + public boolean addAssociation(VppAssetDTO asset, List vppUsers) throws + ApplicationManagementException { + + List associations = new ArrayList<>(); // To save to UEM DBs + List clientUserIds = new ArrayList<>(); // Need this to send to vpp backend. + if (asset != null) { + for (VppUserDTO vppUserDTO : vppUsers) { + VppAssociationDTO associationDTO = VppHttpUtil.getAssociation(vppUserDTO, asset); + associations.add(associationDTO); + clientUserIds.add(vppUserDTO.getClientUserId()); + } + + if (associations.size() > 0) { + //TODO: Add or Update associations + try { + + // Create the VPP backend payload + List assets = new ArrayList<>(); + VppItuneAssetDTO assetDTO = new VppItuneAssetDTO(); + assetDTO.setAdamId(asset.getAdamId()); + assetDTO.setPricingParam(asset.getPricingParam()); + assets.add(assetDTO); + + VppAssociateRequestWrapper vppAssociate = new VppAssociateRequestWrapper(); + vppAssociate.setAssets(assets); + vppAssociate.setClientUserIds(clientUserIds); + + Gson gson = new Gson(); + String payload = gson.toJson(vppAssociate); + + ProxyResponse proxyResponse = callVPPBackend(ASSIGNMENTS_POST, payload, TOKEN, + Constants.VPP.POST); + return true; + + } catch (IOException e) { + String msg = "Error while adding associations"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + + } + + return false; + } + } 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 0a373b4282..267105e5f7 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 @@ -17,26 +17,25 @@ */ package io.entgra.device.mgt.core.application.mgt.core.internal; -import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; -import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; -import io.entgra.device.mgt.core.application.mgt.core.impl.AppmDataHandlerImpl; -import io.entgra.device.mgt.core.application.mgt.core.impl.VppApplicationManagerImpl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; 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.ReviewManager; +import io.entgra.device.mgt.core.application.mgt.common.services.SPApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; 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.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.application.mgt.core.task.ScheduledAppSubscriptionTaskManager; import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.user.core.service.RealmService; @@ -118,9 +117,9 @@ public class ApplicationManagementServiceComponent { DataHolder.getInstance().setConfigManager(configManager); bundleContext.registerService(AppmDataHandler.class.getName(), configManager, null); - // TODO: Get the new instance from extension like others - VppApplicationManagerImpl vppApplicationManager = new VppApplicationManagerImpl(); + VPPApplicationManager vppApplicationManager = ApplicationManagementUtil + .getVPPManagerInstance(); DataHolder.getInstance().setVppApplicationManager(vppApplicationManager); bundleContext.registerService(VPPApplicationManager.class.getName(), vppApplicationManager, null); 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 407b4ebcac..5a76974288 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 @@ -71,6 +71,7 @@ public class APIUtil { private static volatile SubscriptionManager subscriptionManager; private static volatile ReviewManager reviewManager; private static volatile AppmDataHandler appmDataHandler; + private static volatile VPPApplicationManager vppApplicationManager; public static SPApplicationManager getSPApplicationManager() { if (SPApplicationManager == null) { @@ -200,6 +201,29 @@ public class APIUtil { return reviewManager; } + public static VPPApplicationManager getVPPManager() { + try { + if (vppApplicationManager == null) { + synchronized (APIUtil.class) { + if (vppApplicationManager == null) { + vppApplicationManager = ApplicationManagementUtil.getVPPManagerInstance(); + if (vppApplicationManager == null) { + String msg = "Vpp Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + } + } + } catch (Exception e) { + String msg = "Error occurred while getting the vpp manager"; + log.error(msg); + throw new IllegalStateException(msg); + } + return vppApplicationManager; + } + + /** * To get the DataHandler from the osgi context. * @return AppmDataHandler instance in the current osgi context. @@ -424,9 +448,13 @@ public class APIUtil { } List applicationReleases = new ArrayList<>(); if (ApplicationType.PUBLIC.toString().equals(applicationDTO.getType()) && application.getCategories() - .contains("GooglePlaySyncedApp")) { + .contains(Constants.GOOGLE_PLAY_SYNCED_APP)) { application.setAndroidEnterpriseApp(true); } + if (ApplicationType.PUBLIC.toString().equals(applicationDTO.getType()) && application.getCategories() + .contains(Constants.ApplicationProperties.APPLE_STORE_SYNCED_APP_CATEGORY)) { + application.setExternalAppStoreApp(true); + } for (ApplicationReleaseDTO applicationReleaseDTO : applicationDTO.getApplicationReleaseDTOs()) { applicationReleases.add(releaseDtoToRelease(applicationReleaseDTO)); } 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 8ae9a580f4..e32a77448b 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 @@ -32,6 +32,7 @@ import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationStor 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; +import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationUpdateWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.ApplicationWrapper; import io.entgra.device.mgt.core.application.mgt.common.wrapper.CustomAppReleaseWrapper; @@ -44,6 +45,7 @@ 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.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; @@ -202,6 +204,11 @@ public class ApplicationManagementUtil { return getInstance(extension, LifecycleStateManager.class); } + public static VPPApplicationManager getVPPManagerInstance() { + // TODO: implement as an extension + return new VppApplicationManagerImpl(); + } + /** * This is useful to delete application artifacts if any error occurred while creating release/application * after uploading the artifacts 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 7b804e7fa8..f689d56828 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 @@ -73,6 +73,7 @@ public class Constants { public static final String GOOGLE_PLAY_STORE_URL = "https://play.google.com/store/apps/details?id="; public static final String APPLE_STORE_URL = "https://itunes.apple.com/country/app/app-name/id"; + public static final String GOOGLE_PLAY_SYNCED_APP = "GooglePlaySyncedApp"; // Subscription task related constants public static final String SUBSCRIBERS = "SUBSCRIBERS"; @@ -207,5 +208,7 @@ public class Constants { public static final String DISPLAY = "display"; public static final String GENRE_NAMES = "genreNames"; public static final String PRICE_ZERO = "0.0"; + public static final String ASSOCIATION_DEVICE = "ASSOCIATION_DEVICE"; + public static final String ASSOCIATION_USER = "ASSOCIATION_USER"; } } 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/VppHttpUtil.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/VppHttpUtil.java index 620339a1bf..c915b8407d 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/VppHttpUtil.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/VppHttpUtil.java @@ -20,6 +20,9 @@ package io.entgra.device.mgt.core.application.mgt.core.util; import com.google.gson.Gson; import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -39,6 +42,7 @@ import org.apache.http.impl.client.HttpClients; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; @@ -282,4 +286,20 @@ public class VppHttpUtil { return HttpClients.custom().setMaxConnTotal(1).setMaxConnPerRoute(1).build(); } + public static VppAssociationDTO getAssociation(VppUserDTO user, VppAssetDTO asset) { + VppAssociationDTO associationDTO = new VppAssociationDTO(); + associationDTO.setAdamId(asset.getAdamId()); + associationDTO.setClientUserId(user.getClientUserId()); + associationDTO.setPricingParam(asset.getPricingParam()); + associationDTO.setAssociationType(Constants.ApplicationProperties.ASSOCIATION_USER); + + associationDTO.setAssetId(asset.getId()); + associationDTO.setClientId(user.getId()); + associationDTO.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext() + .getTenantId(true)); + associationDTO.setCreatedTime(String.valueOf(System.currentTimeMillis())); + associationDTO.setLastUpdatedTime(String.valueOf(System.currentTimeMillis())); + return associationDTO; + } + } From 1263c09079374134ab73a3f04a743710159f97f4 Mon Sep 17 00:00:00 2001 From: osh Date: Fri, 30 Jun 2023 19:05:59 +0530 Subject: [PATCH 07/36] Add DAOs for asset management fixes https://roadmap.entgra.net/issues/10179 --- .../application/mgt/common/DepConfig.java | 77 +++++++++ .../services/VPPApplicationManager.java | 2 +- .../mgt/core/dao/VppApplicationDAO.java | 7 + .../vpp/GenericVppApplicationDAOImpl.java | 156 ++++++++++++++++++ .../core/impl/VppApplicationManagerImpl.java | 116 +++++++++++-- .../core/util/ApplicationManagementUtil.java | 7 + .../application/mgt/core/util/DAOUtil.java | 54 +++++- .../mgt/core/DeviceManagementConstants.java | 1 + 8 files changed, 400 insertions(+), 20 deletions(-) create mode 100644 components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DepConfig.java 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/DepConfig.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DepConfig.java new file mode 100644 index 0000000000..712ad11df2 --- /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/DepConfig.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.device.mgt.core.application.mgt.common; + +public class DepConfig { + + private String agentPackageName; + private String consumerKey; + private String consumerSecret; + private String accessToken; + private String accessSecret; + private String accessTokenExpiry; + + public String getAgentPackageName() { + return agentPackageName; + } + + public void setAgentPackageName(String agentPackageName) { + this.agentPackageName = agentPackageName; + } + + public String getConsumerKey() { + return consumerKey; + } + + public void setConsumerKey(String consumerKey) { + this.consumerKey = consumerKey; + } + + public String getConsumerSecret() { + return consumerSecret; + } + + public void setConsumerSecret(String consumerSecret) { + this.consumerSecret = consumerSecret; + } + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public String getAccessSecret() { + return accessSecret; + } + + public void setAccessSecret(String accessSecret) { + this.accessSecret = accessSecret; + } + + public String getAccessTokenExpiry() { + return accessTokenExpiry; + } + + public void setAccessTokenExpiry(String accessTokenExpiry) { + this.accessTokenExpiry = accessTokenExpiry; + } +} 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/VPPApplicationManager.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/VPPApplicationManager.java index 55a3ee51b8..8c28055c6b 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/VPPApplicationManager.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/VPPApplicationManager.java @@ -37,7 +37,7 @@ public interface VPPApplicationManager { void syncAssets(int nextPageIndex) throws ApplicationManagementException; - VppAssetDTO getAssetByAppId(String appId) throws ApplicationManagementException; + VppAssetDTO getAssetByAppId(int appId) throws ApplicationManagementException; ProxyResponse callVPPBackend(String url, String payload, String accessToken, String method) throws IOException; } 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 6ebec3f0e7..df84ed1e27 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 @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.application.mgt.core.dao; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; @@ -29,4 +30,10 @@ public interface VppApplicationDAO { VppUserDTO updateVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException; VppUserDTO getUserByDMUsername(String emmUsername, int tenantId) throws ApplicationManagementDAOException; + + VppAssetDTO getAssetByAppId(int appId, int tenantId) throws ApplicationManagementDAOException; + + int addAsset(VppAssetDTO vppAssetDTO, int tenantId) throws ApplicationManagementDAOException; + + VppAssetDTO updateAsset(VppAssetDTO vppAssetDTO, 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/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 2bafc338f3..13c26d75f6 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 @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.VppApplicationDAO; @@ -29,6 +30,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.sql.*; +import java.util.List; public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements VppApplicationDAO { private static final Log log = LogFactory.getLog(GenericVppApplicationDAOImpl.class); @@ -83,6 +85,7 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp } } + @Override public VppUserDTO updateVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException { @@ -130,6 +133,7 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp } } + @Override public VppUserDTO getUserByDMUsername(String emmUsername, int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT " @@ -168,4 +172,156 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp throw new ApplicationManagementDAOException(msg, e); } } + + @Override + public VppAssetDTO getAssetByAppId(int appId, int tenantId) + throws ApplicationManagementDAOException { + String sql = "SELECT " + + "ID, " + + "APP_ID, " + + "TENANT_ID, " + + "CREATED_TIME, " + + "LAST_UPDATED_TIME, " + + "ADAM_ID, " + + "ASSIGNED_COUNT, " + + "DEVICE_ASSIGNABLE, " + + "PRICING_PARAMS, " + + "PRODUCT_TYPE, " + + "RETIRED_COUNT, " + + "REVOCABLE " +// + "SUPPORTED_PLATFORMS " + + "FROM AP_ASSETS " + + "WHERE APP_ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, appId); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + return DAOUtil.loadAsset(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when retrieving asset data of app id "+ appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to retrieve asset by app id."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one app for app id: " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public int addAsset(VppAssetDTO vppAssetDTO, int tenantId) + throws ApplicationManagementDAOException { + int assetId = -1; + String sql = "INSERT INTO " + + "AP_ASSETS(" + + "APP_ID, " + + "TENANT_ID, " + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "ADAM_ID," + + "ASSIGNED_COUNT," + + "DEVICE_ASSIGNABLE," + + "PRICING_PARAMS," + + "PRODUCT_TYPE," + + "RETIRED_COUNT," + + "REVOCABLE) " +// + "SUPPORTED_PLATFORMS) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + long currentTime = System.currentTimeMillis(); + stmt.setInt(1, vppAssetDTO.getAppId()); + stmt.setInt(2, tenantId); + stmt.setLong(3, currentTime); + stmt.setLong(4, currentTime); + stmt.setString(5, vppAssetDTO.getAdamId()); + stmt.setString(6, vppAssetDTO.getAssignedCount()); + stmt.setString(7, vppAssetDTO.getDeviceAssignable()); + stmt.setString(8, vppAssetDTO.getPricingParam()); + stmt.setString(9, vppAssetDTO.getProductType()); + stmt.setString(10, vppAssetDTO.getRetiredCount()); + stmt.setString(11, vppAssetDTO.getRevocable()); +// List platformList = vppAssetDTO.getSupportedPlatforms(); +// String platformString = String.join(",", platformList); +// stmt.setString(12, platformString); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + assetId = rs.getInt(1); + } + } + return assetId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the asset."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the asset."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public VppAssetDTO updateAsset(VppAssetDTO vppAssetDTO, int tenantId) + throws ApplicationManagementDAOException { + + String sql = "UPDATE " + + "AP_ASSETS " + + "SET " + + "APP_ID = ?," + + "LAST_UPDATED_TIME = ?, " + + "ADAM_ID = ?, " + + "ASSIGNED_COUNT = ?, " + + "DEVICE_ASSIGNABLE = ?, " + + "PRICING_PARAMS = ?, " + + "PRODUCT_TYPE = ?, " + + "RETIRED_COUNT = ?, " + + "REVOCABLE = ? " +// + "SUPPORTED_PLATFORMS = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + long updatedTime = System.currentTimeMillis(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, vppAssetDTO.getAppId()); + stmt.setLong(2, updatedTime); + stmt.setString(3, vppAssetDTO.getAdamId()); + stmt.setString(4, vppAssetDTO.getAssignedCount()); + stmt.setString(5, vppAssetDTO.getDeviceAssignable()); + stmt.setString(6, vppAssetDTO.getPricingParam()); + stmt.setString(7, vppAssetDTO.getProductType()); + stmt.setString(8, vppAssetDTO.getRetiredCount()); + stmt.setString(9, vppAssetDTO.getRevocable()); +// List platformList = vppAssetDTO.getSupportedPlatforms(); +// String platformString = String.join(",", platformList); +// stmt.setString(10, platformString); + stmt.setInt(10, vppAssetDTO.getId()); + stmt.setLong(11, tenantId); + stmt.executeUpdate(); + if (stmt.executeUpdate() == 1) { + return vppAssetDTO; + } + return null; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when updating the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to updating the vpp user."; + 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/impl/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index 15ec5e3a15..e99f0eb44b 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -21,12 +21,14 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import io.entgra.device.mgt.core.application.mgt.common.DepConfig; import io.entgra.device.mgt.core.application.mgt.common.dto.ItuneAppDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppItuneUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.common.exception.TransactionManagementException; +import io.entgra.device.mgt.core.application.mgt.common.response.Application; import io.entgra.device.mgt.core.application.mgt.common.wrapper.VppItuneUserRequestWrapper; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; @@ -46,12 +48,19 @@ import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagement import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.VppHttpUtil; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpStatus; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.io.IOException; +import java.util.List; public class VppApplicationManagerImpl implements VPPApplicationManager { private static final String APP_API = "https://vpp.itunes.apple.com/mdm/v2"; @@ -245,6 +254,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { @Override public void syncAssets(int nextPageIndex) throws ApplicationManagementException { ProxyResponse proxyResponse = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { String url = ASSETS; if (nextPageIndex > 0) { // Not the first page @@ -267,15 +277,66 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { for (VppAssetDTO vppAssetDTO : vppItuneAssetResponse.getAssets()) { ItuneAppDTO ituneAppDTO = lookupAsset(vppAssetDTO.getAdamId()); ApplicationManagementUtil.persistApp(ituneAppDTO); + List applications = ApplicationManagementUtil.getAppDetails(vppAssetDTO.getAdamId()); + for (Application application :applications) { + VppAssetDTO vppAssetDTOs = getAssetByAppId(application.getId()); + if (vppAssetDTOs == null) { + vppAssetDTOs = new VppAssetDTO(); + vppAssetDTOs.setAppId(application.getId()); + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.addAsset(vppAssetDTOs, tenantId) != -1) { + ConnectionManagerUtil.commitDBTransaction(); + } + ConnectionManagerUtil.rollbackDBTransaction(); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while adding the Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for adding Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for adding Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } else { + vppAssetDTOs.setAppId(application.getId()); + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.updateAsset(vppAssetDTOs, tenantId) == null) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Unable to update the asset: " +vppAssetDTOs.getAdamId(); + log.error(msg); + throw new ApplicationManagementException(msg); + } + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while updating the Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for Asset update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for Asset update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + } } - - // TODO: Store/update vppItuneAssetResponse.getAssets() in the DB - - // TODO: END of DAO access - } - if (vppItuneAssetResponse.getCurrentPageIndex() == (vppItuneAssetResponse .getTotalPages() - 1)) { return; @@ -288,8 +349,6 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { log.error(msg, e); throw new ApplicationManagementException(msg, e); } - - } private ItuneAppDTO lookupAsset(String packageName) throws ApplicationManagementException { @@ -352,10 +411,22 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { } - public VppAssetDTO getAssetByAppId(String appId) throws ApplicationManagementException { - // App ID is the app id of the App management database - VppAssetDTO assetDTO = null; // TODO: load from the DB - return assetDTO; + public VppAssetDTO getAssetByAppId(int appId) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + return vppApplicationDAO.getAssetByAppId(appId, tenantId); + } catch (DBConnectionException e) { + String msg = "DB Connection error occurs while getting asset related to app with app id " + appId + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while getting asset data related to app with app id " + appId + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } } @Override @@ -366,4 +437,25 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { return VppHttpUtil.execute(url, payload, accessToken, method); } + public String getVppToken() throws ApplicationManagementException { + String token = ""; + MetadataManagementService meta = DeviceManagementDataHolder + .getInstance().getMetadataManagementService(); + Metadata metadata = null; + try { + metadata = meta.retrieveMetadata(DeviceManagementConstants.DEP_META_KEY); + if (metadata != null) { + + Gson g = new Gson(); + DepConfig depConfigs = g.fromJson(metadata.getMetaValue(), DepConfig.class); + token = depConfigs.getAccessToken(); + return token; + } + }catch (MetadataManagementException e) { + String msg = "Error when retrieving metadata of vpp feature"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + return token; + } } 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 8ae9a580f4..d506bc854d 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 @@ -520,4 +520,11 @@ public class ApplicationManagementUtil { } } } + + public static List getAppDetails(String adamId) throws ApplicationManagementException { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + List packageNamesOfApps = new ArrayList<>(); + packageNamesOfApps.add(adamId); + return applicationManager.getApplications(packageNamesOfApps); + } } 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/DAOUtil.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/DAOUtil.java index 89b5ac01ca..f152d27f4f 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/DAOUtil.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/DAOUtil.java @@ -19,20 +19,14 @@ package io.entgra.device.mgt.core.application.mgt.core.util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; -import io.entgra.device.mgt.core.application.mgt.common.dto.IdentityServerDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.*; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus; import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; -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.DeviceSubscriptionDTO; -import io.entgra.device.mgt.core.application.mgt.common.dto.ReviewDTO; -import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO; -import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import java.sql.PreparedStatement; @@ -382,6 +376,52 @@ public class DAOUtil { return vppUserDTOS; } + public static VppAssetDTO loadAsset(ResultSet rs) throws SQLException, UnexpectedServerErrorException { + List vppAssetDTOS = loadAssets(rs); + if (vppAssetDTOS.isEmpty()) { + return null; + } + if (vppAssetDTOS.size() > 1) { + String msg = "Internal server error. Found more than one asset for given app id."; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return vppAssetDTOS.get(0); + } + + public static List loadAssets (ResultSet rs) throws SQLException { + List vppAssetDTOS = new ArrayList<>(); + while (rs.next()) { + VppAssetDTO vppAssetDTO = new VppAssetDTO(); + vppAssetDTO.setId(rs.getInt("ID")); + vppAssetDTO.setAppId(rs.getInt("APP_ID")); + vppAssetDTO.setTenantId(rs.getInt("TENANT_ID")); + if (rs.getLong("CREATED_TIME") != 0) { + vppAssetDTO.setCreatedTime(new Date(rs.getLong(("CREATED_TIME")) * 1000).toString()); + } + if (rs.getLong("LAST_UPDATED_TIME") != 0) { + vppAssetDTO.setLastUpdatedTime(new Date(rs.getLong(("LAST_UPDATED_TIME")) * 1000).toString()); + } + vppAssetDTO.setAdamId(rs.getString("ADAM_ID")); + vppAssetDTO.setAssignedCount(rs.getString("ASSIGNED_COUNT")); + vppAssetDTO.setDeviceAssignable(rs.getString("DEVICE_ASSIGNABLE")); + vppAssetDTO.setPricingParam(rs.getString("PRICING_PARAMS")); + vppAssetDTO.setProductType(rs.getString("PRODUCT_TYPE")); + vppAssetDTO.setRetiredCount(rs.getString("RETIRED_COUNT")); + vppAssetDTO.setRevocable(rs.getString("REVOCABLE")); +// String jsonString = rs.getString("SUPPORTED_PLATFORMS"); +// ObjectMapper objectMapper = new ObjectMapper(); +// try { +// List platformList = objectMapper.readValue(jsonString, new TypeReference>() {}); +// vppAssetDTO.setSupportedPlatforms(platformList); +// } catch (IOException e) { +// e.printStackTrace(); +// } + vppAssetDTOS.add(vppAssetDTO); + } + return vppAssetDTOS; + } + /** * Cleans up the statement and resultset after executing the query * 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/DeviceManagementConstants.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConstants.java index 58be3dae82..770c6db022 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementConstants.java @@ -29,6 +29,7 @@ public final class DeviceManagementConstants { public static final String GEOFENCE_CACHE = "GEOFENCE_CACHE"; public static final String BILLING_CACHE = "BILLING_CACHE"; public static final String META_KEY = "PER_DEVICE_COST"; + public static final String DEP_META_KEY = "DEP_CONFIG"; public static final String ACTIVE_STATUS = "ACTIVE"; public static final String ENROLLMENT_NOTIFICATION_API_ENDPOINT = "/api/device-mgt/enrollment-notification"; public static final String URL_SEPERATOR = "/"; From 026986cd93e1ba3c0fe41be5d18c1d94f2b879f3 Mon Sep 17 00:00:00 2001 From: inoshperera Date: Wed, 5 Jul 2023 17:16:38 +0530 Subject: [PATCH 08/36] Add DAO improvements for user APIs Fixes https://roadmap.entgra.net/issues/10169 --- .../services/VPPApplicationManager.java | 4 + .../vpp/GenericVppApplicationDAOImpl.java | 76 +++++++++++++------ .../core/impl/VppApplicationManagerImpl.java | 16 +++- .../application/mgt/core/util/Constants.java | 2 +- .../application/mgt/core/util/DAOUtil.java | 25 +++++- .../main/resources/conf/application-mgt.xml | 1 + .../repository/conf/application-mgt.xml.j2 | 1 + 7 files changed, 93 insertions(+), 32 deletions(-) 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/VPPApplicationManager.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/VPPApplicationManager.java index f537764c62..443aed228f 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/VPPApplicationManager.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/VPPApplicationManager.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.application.mgt.common.services; import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; @@ -44,4 +45,7 @@ public interface VPPApplicationManager { boolean addAssociation(VppAssetDTO asset, List vppUsers) throws ApplicationManagementException; + + VppAssociationDTO getUserAssociation(String adamId, String emmUsername) throws + ApplicationManagementException; } 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 13c26d75f6..3ec5487261 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 @@ -89,34 +89,61 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp public VppUserDTO updateVppUser(VppUserDTO userDTO, int tenantId) throws ApplicationManagementDAOException { - String sql = "UPDATE " - + "AP_VPP_USER " - + "SET " - + "CLIENT_USER_ID = ?," - + "DM_USERNAME = ?, " - + "TENANT_ID = ?, " - + "EMAIL = ?, " - + "INVITE_CODE = ?, " - + "STATUS = ?, " - + "LAST_UPDATED_TIME = ?, " - + "MANAGED_ID = ?, " - + "TEMP_PASSWORD = ? " - + "WHERE ID = ?"; + String sql = "UPDATE AP_VPP_USER SET "; + if (userDTO.getClientUserId() != null && !userDTO.getClientUserId().isEmpty()) { + sql += "CLIENT_USER_ID = ?,"; + } + if (userDTO.getDmUsername() != null && !userDTO.getDmUsername().isEmpty()) { + sql += "DM_USERNAME = ?,"; + } + if (userDTO.getEmail() != null && !userDTO.getEmail().isEmpty()) { + sql += "EMAIL = ?,"; + } + if (userDTO.getInviteCode() != null && !userDTO.getInviteCode().isEmpty()) { + sql += "INVITE_CODE = ?,"; + } + if (userDTO.getStatus() != null && !userDTO.getStatus().isEmpty()) { + sql += "STATUS = ?,"; + } + if (userDTO.getManagedId() != null && !userDTO.getManagedId().isEmpty()) { + sql += "MANAGED_ID = ?,"; + } + if (userDTO.getTmpPassword() != null && !userDTO.getTmpPassword().isEmpty()) { + sql += "TEMP_PASSWORD = ?,"; + } + + sql += " TENANT_ID = ?, LAST_UPDATED_TIME = ? WHERE ID = ?"; + try { Connection conn = this.getDBConnection(); long updatedTime = System.currentTimeMillis(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, userDTO.getClientUserId()); - stmt.setString(2, userDTO.getDmUsername()); - stmt.setInt(3, tenantId); - stmt.setString(4, userDTO.getEmail()); - stmt.setString(5, userDTO.getInviteCode()); - stmt.setString(6, userDTO.getStatus()); - stmt.setLong(7, updatedTime); - stmt.setString(8, userDTO.getManagedId()); - stmt.setString(9, userDTO.getTmpPassword()); - stmt.setInt(10, userDTO.getId()); - stmt.executeUpdate(); + int x = 0; + + if (userDTO.getClientUserId() != null && !userDTO.getClientUserId().isEmpty()) { + stmt.setString(++x, userDTO.getClientUserId()); + } + if (userDTO.getDmUsername() != null && !userDTO.getDmUsername().isEmpty()) { + stmt.setString(++x, userDTO.getDmUsername()); + } + if (userDTO.getEmail() != null && !userDTO.getEmail().isEmpty()) { + stmt.setString(++x, userDTO.getEmail()); + } + if (userDTO.getInviteCode() != null && !userDTO.getInviteCode().isEmpty()) { + stmt.setString(++x, userDTO.getInviteCode()); + } + if (userDTO.getStatus() != null && !userDTO.getStatus().isEmpty()) { + stmt.setString(++x, userDTO.getStatus()); + } + if (userDTO.getManagedId() != null && !userDTO.getManagedId().isEmpty()) { + stmt.setString(++x, userDTO.getManagedId()); + } + if (userDTO.getTmpPassword() != null && !userDTO.getTmpPassword().isEmpty()) { + stmt.setString(++x, userDTO.getTmpPassword()); + } + stmt.setInt(++x, tenantId); + stmt.setLong(++x, updatedTime); + stmt.setInt(++x, userDTO.getId()); if (stmt.executeUpdate() == 1) { return userDTO; } @@ -147,6 +174,7 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp + "LAST_UPDATED_TIME, " + "MANAGED_ID, " + "TEMP_PASSWORD " + + "DM_USERNAME " + "FROM AP_VPP_USER " + "WHERE DM_USERNAME = ? AND TENANT_ID = ?"; 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/impl/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index b86ef9d2a3..f6ab0d92a8 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -110,9 +110,6 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { wrapper.getUser().add(ituneUserDTO); Gson gson = new Gson(); -// Gson gson = new GsonBuilder() -// .setExclusionStrategies(new NullEmptyExclusionStrategy()) -// .create(); String userPayload = gson.toJson(wrapper); ProxyResponse proxyResponse = callVPPBackend(USER_CREATE, userPayload, TOKEN, Constants.VPP.POST); @@ -131,8 +128,12 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { log.error("userDTO " + userDTO.toString()); try { ConnectionManagerUtil.beginDBTransaction(); - if (vppApplicationDAO.addVppUser(userDTO, tenantId) != -1) { + int id = vppApplicationDAO.addVppUser(userDTO, tenantId); + if (id != -1) { ConnectionManagerUtil.commitDBTransaction(); + userDTO.setId(id); + userDTO.setTenantId(PrivilegedCarbonContext + .getThreadLocalCarbonContext().getTenantId()); return userDTO; } ConnectionManagerUtil.rollbackDBTransaction(); @@ -507,4 +508,11 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { return false; } + + @Override + public VppAssociationDTO getUserAssociation(String adamId, String emmUsername) throws ApplicationManagementException { + // Todo: Join the 3 tables and find a matching association + return null; + } + } 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 f689d56828..016fe414fa 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 @@ -196,7 +196,7 @@ public class Constants { public static final String PAID_SUB_METHOD = "PAID"; public static final String TYPE = "type";; public static final String PACKAGE_NAME = "packageName"; - public static final String APPLE_STORE_SYNCED_APP_CATEGORY = "APPLE_STORE_SYNCED_APP"; + public static final String APPLE_STORE_SYNCED_APP_CATEGORY = "AppleStoreSyncedApp"; public static final String RESULTS = "results"; public static final String ARTWORK = "artwork"; 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/DAOUtil.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/DAOUtil.java index f152d27f4f..c5d9f259a6 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/DAOUtil.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/DAOUtil.java @@ -362,9 +362,18 @@ public class DAOUtil { vppUserDTO.setTenantId(rs.getInt("TENANT_ID")); vppUserDTO.setEmail(rs.getString("EMAIL")); vppUserDTO.setInviteCode(rs.getString("INVITE_CODE")); - vppUserDTO.setStatus(rs.getString("STATUS")); - vppUserDTO.setManagedId(rs.getString("MANAGED_ID")); - vppUserDTO.setTmpPassword(rs.getString("TEMP_PASSWORD")); + if (columnExist(rs,"STATUS")) { + vppUserDTO.setStatus(rs.getString("STATUS")); + } + if (columnExist(rs,"MANAGED_ID")) { + vppUserDTO.setManagedId(rs.getString("MANAGED_ID")); + } + if (columnExist(rs,"TEMP_PASSWORD")) { + vppUserDTO.setTmpPassword(rs.getString("TEMP_PASSWORD")); + } + if (columnExist(rs,"DM_USERNAME")) { + vppUserDTO.setDmUsername(rs.getString("DM_USERNAME")); + } if (rs.getLong("CREATED_TIME") != 0) { vppUserDTO.setCreatedTime(new Date(rs.getLong(("CREATED_TIME")) * 1000).toString()); } @@ -376,6 +385,16 @@ public class DAOUtil { return vppUserDTOS; } + private static boolean columnExist(ResultSet rs, String column){ + try{ + rs.findColumn(column); + return true; + } catch (SQLException sqlex){ + } + + return false; + } + public static VppAssetDTO loadAsset(ResultSet rs) throws SQLException, UnexpectedServerErrorException { List vppAssetDTOS = loadAssets(rs); if (vppAssetDTOS.isEmpty()) { diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml index 8913afa2b9..bb1e6144ac 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml @@ -171,6 +171,7 @@ Video Players & Editors Weather GooglePlaySyncedApp + AppleStoreSyncedApp diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 index cbd8c6f0c9..bc4d34b048 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 @@ -202,6 +202,7 @@ Video Players & Editors Weather GooglePlaySyncedApp + AppleStoreSyncedApp {% if application_mgt_conf.app_categories is defined %} {%- for app_category in application_mgt_conf.app_categories -%} {{app_category}} From 0e5478fb5e0235c5282aeedfa852f1a78468ccdc Mon Sep 17 00:00:00 2001 From: osh Date: Wed, 5 Jul 2023 20:49:46 +0530 Subject: [PATCH 09/36] Add association DAO and fix meta issue fixes https://roadmap.entgra.net/issues/10186 --- .../services/VPPApplicationManager.java | 4 + .../mgt/core/config/Extension.java | 3 +- .../mgt/core/dao/VppApplicationDAO.java | 7 + .../vpp/GenericVppApplicationDAOImpl.java | 122 ++++++++++++++ .../core/impl/VppApplicationManagerImpl.java | 156 ++++++++++++++---- .../application/mgt/core/util/APIUtil.java | 25 +++ .../core/util/ApplicationManagementUtil.java | 9 + .../application/mgt/core/util/DAOUtil.java | 31 ++++ 8 files changed, 323 insertions(+), 34 deletions(-) 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/VPPApplicationManager.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/VPPApplicationManager.java index f537764c62..05f3090949 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/VPPApplicationManager.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/VPPApplicationManager.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.application.mgt.common.services; import io.entgra.device.mgt.core.application.mgt.common.dto.ProxyResponse; import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; @@ -44,4 +45,7 @@ public interface VPPApplicationManager { boolean addAssociation(VppAssetDTO asset, List vppUsers) throws ApplicationManagementException; + + VppAssociationDTO getAssociation(int assetId, int userId) throws + ApplicationManagementException; } 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/config/Extension.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java index 553ee67172..9ded8d3608 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java @@ -88,7 +88,8 @@ public class Extension { SubscriptionManager, VisibilityManager, ApplicationStorageManager, - PlatformStorageManager + PlatformStorageManager, + MetadataManagementService } } 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 df84ed1e27..02aec95174 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 @@ -19,6 +19,7 @@ package io.entgra.device.mgt.core.application.mgt.core.dao; import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; @@ -36,4 +37,10 @@ public interface VppApplicationDAO { int addAsset(VppAssetDTO vppAssetDTO, int tenantId) throws ApplicationManagementDAOException; VppAssetDTO updateAsset(VppAssetDTO vppAssetDTO, int tenantId) throws ApplicationManagementDAOException; + + VppAssociationDTO getAssociation(int assetId, int userId, int tenantId) throws ApplicationManagementDAOException; + + int addAssociation(VppAssociationDTO vppAssociationDTO, int tenantId) throws ApplicationManagementDAOException; + + VppAssociationDTO updateAssociation(VppAssociationDTO vppAssociationDTO, 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/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 13c26d75f6..212a6d4baf 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 @@ -19,6 +19,7 @@ package io.entgra.device.mgt.core.application.mgt.core.dao.impl.vpp; import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssetDTO; +import io.entgra.device.mgt.core.application.mgt.common.dto.VppAssociationDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.VppUserDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.core.dao.VppApplicationDAO; @@ -324,4 +325,125 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp throw new ApplicationManagementDAOException(msg, e); } } + + @Override + public VppAssociationDTO getAssociation(int assetId, int userId, int tenantId) + throws ApplicationManagementDAOException { + String sql = "SELECT " + + "ID, " + + "ASSOCIATION_TYPE, " + + "CREATED_TIME, " + + "LAST_UPDATED_TIME, " + + "PRICING_PARAMS " + + "FROM AP_VPP_ASSOCIATION " + + "WHERE ASSET_ID = ? AND USER_ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, assetId); + stmt.setInt(2, userId); + stmt.setInt(3, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + return DAOUtil.loadAssignment(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when retrieving assignment data of user with id "+ userId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to retrieve assignment by asset id and user id."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one assignment for user id: " + userId + " and asset id: " + assetId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public int addAssociation(VppAssociationDTO vppAssociationDTO, int tenantId) + throws ApplicationManagementDAOException { + int associationId = -1; + String sql = "INSERT INTO " + + "AP_VPP_ASSOCIATION(" + + "ASSET_ID, " + + "USER_ID, " + + "TENANT_ID, " + + "ASSOCIATION_TYPE," + + "CREATED_TIME," + + "LAST_UPDATED_TIME," + + "PRICING_PARAMS) " + + "VALUES (?, ?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + long currentTime = System.currentTimeMillis(); + stmt.setInt(1, vppAssociationDTO.getAssetId()); + stmt.setInt(2, vppAssociationDTO.getClientId()); + stmt.setInt(3, tenantId); + stmt.setString(4, vppAssociationDTO.getAssociationType()); + stmt.setLong(5, currentTime); + stmt.setLong(6, currentTime); + stmt.setString(7, vppAssociationDTO.getPricingParam()); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + associationId = rs.getInt(1); + } + } + return associationId; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when adding the asset."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to add the asset."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public VppAssociationDTO updateAssociation(VppAssociationDTO vppAssociationDTO, int tenantId) + throws ApplicationManagementDAOException { + + String sql = "UPDATE " + + "AP_VPP_ASSOCIATION " + + "SET " + + "ASSET_ID = ?," + + "USER_ID = ?, " + + "ASSOCIATION_TYPE = ?, " + + "LAST_UPDATED_TIME = ?, " + + "PRICING_PARAMS = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + long updatedTime = System.currentTimeMillis(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, vppAssociationDTO.getAssetId()); + stmt.setInt(2, vppAssociationDTO.getClientId()); + stmt.setString(3, vppAssociationDTO.getAssociationType()); + stmt.setLong(4, updatedTime); + stmt.setString(5, vppAssociationDTO.getPricingParam()); + stmt.setInt(6, vppAssociationDTO.getId()); + stmt.setLong(7, tenantId); + stmt.executeUpdate(); + if (stmt.executeUpdate() == 1) { + return vppAssociationDTO; + } + return null; + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining database connection when updating the vpp user"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to updating the vpp user."; + 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/impl/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index b86ef9d2a3..d1a0af7cf4 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -50,6 +50,7 @@ import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagement import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.VppHttpUtil; +import io.entgra.device.mgt.core.application.mgt.core.util.APIUtil; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; @@ -71,6 +72,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { private static final String USER_UPDATE = APP_API + "/users/update"; private static final String USER_GET = APP_API + "/users"; private static final String ASSIGNMENTS_POST = APP_API + "/assets/associate"; + private static final String ASSIGNMENTS_GET = APP_API + "/assignments"; private static final String TOKEN = ""; private static final String LOOKUP_API = "https://uclient-api.itunes.apple" + ".com/WebObjects/MZStorePlatform.woa/wa/lookup?version=2&id="; @@ -285,10 +287,10 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { VppAssetDTO vppAssetDTOs = getAssetByAppId(application.getId()); if (vppAssetDTOs == null) { vppAssetDTOs = new VppAssetDTO(); - vppAssetDTOs.setAppId(application.getId()); + vppAssetDTO.setAppId(application.getId()); try { ConnectionManagerUtil.beginDBTransaction(); - if (vppApplicationDAO.addAsset(vppAssetDTOs, tenantId) != -1) { + if (vppApplicationDAO.addAsset(vppAssetDTO, tenantId) != -1) { ConnectionManagerUtil.commitDBTransaction(); } ConnectionManagerUtil.rollbackDBTransaction(); @@ -413,7 +415,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { return null; } - + @Override public VppAssetDTO getAssetByAppId(int appId) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { @@ -433,40 +435,12 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { } @Override - public ProxyResponse callVPPBackend(String url, - String payload, - String accessToken, - String method) throws IOException { - return VppHttpUtil.execute(url, payload, accessToken, method); - } - - public String getVppToken() throws ApplicationManagementException { - String token = ""; - MetadataManagementService meta = DeviceManagementDataHolder - .getInstance().getMetadataManagementService(); - Metadata metadata = null; - try { - metadata = meta.retrieveMetadata("DEP_META_KEY"); - if (metadata != null) { - - Gson g = new Gson(); - DepConfig depConfigs = g.fromJson(metadata.getMetaValue(), DepConfig.class); - token = depConfigs.getAccessToken(); - return token; - } - }catch (MetadataManagementException e) { - String msg = "Error when retrieving metadata of vpp feature"; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } - return token; - } - public boolean addAssociation(VppAssetDTO asset, List vppUsers) throws ApplicationManagementException { List associations = new ArrayList<>(); // To save to UEM DBs List clientUserIds = new ArrayList<>(); // Need this to send to vpp backend. + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); if (asset != null) { for (VppUserDTO vppUserDTO : vppUsers) { VppAssociationDTO associationDTO = VppHttpUtil.getAssociation(vppUserDTO, asset); @@ -494,7 +468,75 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { ProxyResponse proxyResponse = callVPPBackend(ASSIGNMENTS_POST, payload, TOKEN, Constants.VPP.POST); - return true; + if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == + HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { + // Create assignment does not return any useful data. Its needed to call the backend again + ProxyResponse getAssignmentResponse = callVPPBackend(ASSIGNMENTS_GET, null, TOKEN, Constants.VPP.GET); + if ((getAssignmentResponse.getCode() == HttpStatus.SC_OK || getAssignmentResponse.getCode() == + HttpStatus.SC_CREATED) && getAssignmentResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { +// VppAssociateResponseWrapper vppAssociateResponseWrapper = gson.fromJson +// (getAssignmentResponse.getData(), VppAssociateResponseWrapper.class); + for (VppAssociationDTO association : associations) { + + VppAssociationDTO vppAssociation = getAssociation(association.getAssetId(), association.getClientId()); + + if (vppAssociation == null) { + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.addAssociation(association, tenantId) != -1) { + ConnectionManagerUtil.commitDBTransaction(); + return true; + } + ConnectionManagerUtil.rollbackDBTransaction(); + return false; + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while adding the Assignment."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for adding Assignment."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for adding Assignment."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } else { + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.updateAssociation(association, tenantId) == null) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Unable to update the assignment: " +association.getAssetId(); + log.error(msg); + throw new ApplicationManagementException(msg); + } + ConnectionManagerUtil.commitDBTransaction(); + return true; + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while updating the Asset."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for Asset update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for Asset update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + } + } + + } } catch (IOException e) { String msg = "Error while adding associations"; @@ -507,4 +549,52 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { return false; } + + @Override + public VppAssociationDTO getAssociation(int assetId, int userId) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + return vppApplicationDAO.getAssociation(assetId, userId, tenantId); + } catch (DBConnectionException e) { + String msg = "DB Connection error occurs while getting assignment related to user of id " + userId + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while getting assignment data related to user of id " + userId + "."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public ProxyResponse callVPPBackend(String url, + String payload, + String accessToken, + String method) throws IOException { + return VppHttpUtil.execute(url, payload, accessToken, method); + } + + public String getVppToken() throws ApplicationManagementException { + String token = ""; + MetadataManagementService meta = APIUtil.getMetadataManager(); + Metadata metadata = null; + try { + metadata = meta.retrieveMetadata("DEP_META_KEY"); + if (metadata != null) { + + Gson g = new Gson(); + DepConfig depConfigs = g.fromJson(metadata.getMetaValue(), DepConfig.class); + token = depConfigs.getAccessToken(); + return token; + } + }catch (MetadataManagementException e) { + String msg = "Error when retrieving metadata of vpp feature"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + return token; + } } 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 5a76974288..2e8536feb8 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 @@ -26,6 +26,8 @@ import io.entgra.device.mgt.core.application.mgt.core.config.IdentityServiceProv import io.entgra.device.mgt.core.application.mgt.core.serviceprovider.ISServiceProviderApplicationService; import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; +import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -72,6 +74,7 @@ public class APIUtil { private static volatile ReviewManager reviewManager; private static volatile AppmDataHandler appmDataHandler; private static volatile VPPApplicationManager vppApplicationManager; + private static volatile MetadataManagementService metadataManagementService; public static SPApplicationManager getSPApplicationManager() { if (SPApplicationManager == null) { @@ -113,6 +116,28 @@ public class APIUtil { return applicationManager; } + public static MetadataManagementService getMetadataManager() { + try { + if (metadataManagementService == null) { + synchronized (APIUtil.class) { + if (metadataManagementService == null) { + metadataManagementService = ApplicationManagementUtil.getDeviceManagerInstance(); + if (metadataManagementService == null) { + String msg = "MetadataManagement Service service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + } + } + } catch (Exception e) { + String msg = "Error occurred while getting the vpp manager"; + log.error(msg); + throw new IllegalStateException(msg); + } + return metadataManagementService; + } + /** * To get the ApplicationDTO Storage Manager from the osgi context. * @return ApplicationStoreManager instance in the current osgi context. 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 3ae13bae1f..d739f0f68a 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 @@ -49,7 +49,9 @@ import io.entgra.device.mgt.core.application.mgt.core.impl.VppApplicationManager 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.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; @@ -209,6 +211,13 @@ public class ApplicationManagementUtil { return new VppApplicationManagerImpl(); } + public static MetadataManagementService getDeviceManagerInstance() throws InvalidConfigurationException { + ConfigurationManager configurationManager = ConfigurationManager.getInstance(); + Extension extension = configurationManager.getExtension(Extension.Name.MetadataManagementService); + return getInstance(extension, MetadataManagementService.class); + } + + /** * This is useful to delete application artifacts if any error occurred while creating release/application * after uploading the artifacts 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/DAOUtil.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/DAOUtil.java index f152d27f4f..73df7fbe53 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/DAOUtil.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/DAOUtil.java @@ -422,6 +422,37 @@ public class DAOUtil { return vppAssetDTOS; } + public static VppAssociationDTO loadAssignment(ResultSet rs) throws SQLException, UnexpectedServerErrorException { + List vppAssociationDTOS = loadAssignments(rs); + if (vppAssociationDTOS.isEmpty()) { + return null; + } + if (vppAssociationDTOS.size() > 1) { + String msg = "Internal server error. Found more than one asset for given app id."; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return vppAssociationDTOS.get(0); + } + + public static List loadAssignments (ResultSet rs) throws SQLException { + List vppAssociationDTOS = new ArrayList<>(); + while (rs.next()) { + VppAssociationDTO vppAssociationDTO = new VppAssociationDTO(); + vppAssociationDTO.setId(rs.getInt("ID")); + vppAssociationDTO.setAssociationType(rs.getString("ASSOCIATION_TYPE")); + if (rs.getLong("CREATED_TIME") != 0) { + vppAssociationDTO.setCreatedTime(new Date(rs.getLong(("CREATED_TIME")) * 1000).toString()); + } + if (rs.getLong("LAST_UPDATED_TIME") != 0) { + vppAssociationDTO.setLastUpdatedTime(new Date(rs.getLong(("LAST_UPDATED_TIME")) * 1000).toString()); + } + vppAssociationDTO.setPricingParam(rs.getString("PRICING_PARAMS")); + vppAssociationDTOS.add(vppAssociationDTO); + } + return vppAssociationDTOS; + } + /** * Cleans up the statement and resultset after executing the query * From dae8c0976155f4069c3e28824092e0dce409a936 Mon Sep 17 00:00:00 2001 From: osh Date: Wed, 5 Jul 2023 22:38:10 +0530 Subject: [PATCH 10/36] Resolve comments --- .../mgt/core/config/Extension.java | 3 +-- .../vpp/GenericVppApplicationDAOImpl.java | 1 - .../application/mgt/core/util/APIUtil.java | 23 ++++++++----------- .../core/util/ApplicationManagementUtil.java | 8 ------- 4 files changed, 10 insertions(+), 25 deletions(-) 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/config/Extension.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java index 9ded8d3608..553ee67172 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/config/Extension.java @@ -88,8 +88,7 @@ public class Extension { SubscriptionManager, VisibilityManager, ApplicationStorageManager, - PlatformStorageManager, - MetadataManagementService + PlatformStorageManager } } 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 1e935d35de..936e8da7e3 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 @@ -458,7 +458,6 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp stmt.setString(5, vppAssociationDTO.getPricingParam()); stmt.setInt(6, vppAssociationDTO.getId()); stmt.setLong(7, tenantId); - stmt.executeUpdate(); if (stmt.executeUpdate() == 1) { return vppAssociationDTO; } 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 2e8536feb8..d37a85dee6 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 @@ -27,7 +27,6 @@ import io.entgra.device.mgt.core.application.mgt.core.serviceprovider.ISServiceP import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; -import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -117,23 +116,19 @@ public class APIUtil { } public static MetadataManagementService getMetadataManager() { - try { - if (metadataManagementService == null) { - synchronized (APIUtil.class) { + if (metadataManagementService == null) { + synchronized (APIUtil.class) { + if (metadataManagementService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + metadataManagementService = + (MetadataManagementService) ctx.getOSGiService(MetadataManagementService.class, null); if (metadataManagementService == null) { - metadataManagementService = ApplicationManagementUtil.getDeviceManagerInstance(); - if (metadataManagementService == null) { - String msg = "MetadataManagement Service service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } + String msg = "MetadataManagement Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } } } - } catch (Exception e) { - String msg = "Error occurred while getting the vpp manager"; - log.error(msg); - throw new IllegalStateException(msg); } return metadataManagementService; } 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 d739f0f68a..36920d013c 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 @@ -210,14 +210,6 @@ public class ApplicationManagementUtil { // TODO: implement as an extension return new VppApplicationManagerImpl(); } - - public static MetadataManagementService getDeviceManagerInstance() throws InvalidConfigurationException { - ConfigurationManager configurationManager = ConfigurationManager.getInstance(); - Extension extension = configurationManager.getExtension(Extension.Name.MetadataManagementService); - return getInstance(extension, MetadataManagementService.class); - } - - /** * This is useful to delete application artifacts if any error occurred while creating release/application * after uploading the artifacts From 2d3f2b94dad5d4d7f55c90afc191fa9ed415f3d9 Mon Sep 17 00:00:00 2001 From: nishan Date: Fri, 7 Jul 2023 18:53:21 +0530 Subject: [PATCH 11/36] Show device identifier and changeed to delete certificate using Id --- ...CertificateManagementAdminServiceImpl.java | 12 +++---- .../admin/api/util/RequestValidationUtil.java | 8 +++++ .../mgt/core/dao/CertificateDAO.java | 4 +-- .../dao/impl/AbstractCertificateDAOImpl.java | 12 ++++--- .../dao/impl/GenericCertificateDAOImpl.java | 27 +++++++++++++-- .../dao/impl/OracleCertificateDAOImpl.java | 28 +++++++++++++-- .../impl/PostgreSQLCertificateDAOImpl.java | 28 +++++++++++++-- .../dao/impl/SQLServerCertificateDAOImpl.java | 28 +++++++++++++-- .../mgt/core/dto/CertificateResponse.java | 34 +++++++++++++++---- .../mgt/core/impl/CertificateGenerator.java | 2 +- .../service/CertificateManagementService.java | 2 +- .../CertificateManagementServiceImpl.java | 8 ++--- ...CertificateManagementServiceImplTests.java | 2 +- 13 files changed, 161 insertions(+), 34 deletions(-) diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java index 0adb7ee601..c64df487be 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java @@ -151,20 +151,20 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem } @DELETE - public Response removeCertificate(@QueryParam("serialNumber") String serialNumber) { - RequestValidationUtil.validateSerialNumber(serialNumber); + public Response removeCertificate(@QueryParam("certificateId") String certificateId) { + RequestValidationUtil.validateCertificateId(certificateId); CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); try { - boolean status = certificateService.removeCertificate(serialNumber); + boolean status = certificateService.removeCertificate(certificateId); if (!status) { return Response.status(Response.Status.NOT_FOUND).entity( "No certificate is found with the given " + - "serial number '" + serialNumber + "'").build(); + "certificate id '" + certificateId + "'").build(); } else { return Response.status(Response.Status.OK).entity( - "Certificate that carries the serial number '" + - serialNumber + "' has been removed").build(); + "Certificate that carries the certificate id '" + + certificateId + "' has been removed").build(); } } catch (CertificateManagementException e) { String msg = "Error occurred while converting PEM file to X509Certificate"; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java index 43f4d1ab48..6263ac9e46 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java @@ -30,6 +30,14 @@ public class RequestValidationUtil { } } + public static void validateCertificateId(String certificateId) { + if (certificateId == null || certificateId.isEmpty()) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( + "Certificate Id cannot be null or empty").build()); + } + } + public static void validatePaginationInfo(int offset, int limit) { if (offset < 0) { throw new InputValidationException( diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java index 779251761e..a3200621d1 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java @@ -95,10 +95,10 @@ public interface CertificateDAO { /** * Delete a certificate identified by a serial number() * - * @param serialNumber serial number + * @param certificateId number * @return whether the certificate was removed or not. */ - boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException; + boolean removeCertificate(String certificateId) throws CertificateManagementDAOException; List searchCertificate(String serialNumber) throws CertificateManagementDAOException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java index d2b5be4062..8e87ffff38 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java @@ -237,7 +237,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME" + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME" + " FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -247,6 +247,8 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); @@ -263,7 +265,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ } @Override - public boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException { + public boolean removeCertificate(String certificateId) throws CertificateManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; @@ -271,15 +273,15 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ try { conn = this.getConnection(); String query = - "DELETE FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ?" + + "DELETE FROM DM_DEVICE_CERTIFICATE WHERE ID = ?" + " AND TENANT_ID = ? "; stmt = conn.prepareStatement(query); - stmt.setString(1, serialNumber); + stmt.setString(1, certificateId); stmt.setInt(2, tenantId); return stmt.executeUpdate() > 0; } catch (SQLException e) { - String msg = "Unable to get the read the certificate with serial" + serialNumber; + String msg = "Unable to get the read the certificate with certificate id" + certificateId; log.error(msg, e); throw new CertificateManagementDAOException(msg, e); } finally { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index 99bf38c73f..f3cba82857 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -47,6 +47,27 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { private Connection getConnection() throws SQLException { return CertificateManagementDAOFactory.getConnection(); } + private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + int certificateCount = 0; + try { + Connection conn = this.getConnection(); + String sql = + "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } + } + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificates."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } + return certificateCount; + } @Override public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { @@ -58,7 +79,7 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -71,6 +92,8 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); @@ -79,7 +102,7 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(resultCount); + paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java index 2b2e934570..f326f9cf97 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java @@ -53,7 +53,7 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -66,6 +66,8 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); @@ -74,7 +76,7 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(resultCount); + paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -88,4 +90,26 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { private Connection getConnection() throws SQLException { return CertificateManagementDAOFactory.getConnection(); } + + private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + int certificateCount = 0; + try { + Connection conn = this.getConnection(); + String sql = + "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } + } + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificates."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } + return certificateCount; + } } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java index 6e8ea00703..7d187cfa3d 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java @@ -53,7 +53,7 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -66,6 +66,8 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); @@ -74,7 +76,7 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(resultCount); + paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -88,4 +90,26 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { private Connection getConnection() throws SQLException { return CertificateManagementDAOFactory.getConnection(); } + + private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + int certificateCount = 0; + try { + Connection conn = this.getConnection(); + String sql = + "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } + } + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificates."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } + return certificateCount; + } } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java index de8d911c29..6615ab4c12 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java @@ -53,7 +53,7 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -66,6 +66,8 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); @@ -74,7 +76,7 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(resultCount); + paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -88,4 +90,26 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { private Connection getConnection() throws SQLException { return CertificateManagementDAOFactory.getConnection(); } + + private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + int certificateCount = 0; + try { + Connection conn = this.getConnection(); + String sql = + "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } + } + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificates."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } + return certificateCount; + } } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dto/CertificateResponse.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dto/CertificateResponse.java index 44b0df5193..23f37a0efa 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dto/CertificateResponse.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dto/CertificateResponse.java @@ -32,6 +32,12 @@ public class CertificateResponse { @ApiModelProperty(name = "serialNumber", value = "It is the unique ID that is used to identify a certificate", required = true) String serialNumber; + @ApiModelProperty(name = "deviceIdentifier", value = "It is use to identify a certificate list", required = true) + String deviceIdentifier; + + @ApiModelProperty(name = "certificateId", value = "It is the unique ID that is used to identify a certificate", required = true) + String certificateId; + @ApiModelProperty(name = "tenantId", value = "The ID of the tenant who adds the certificate", required = true) int tenantId; @@ -44,8 +50,8 @@ public class CertificateResponse { @ApiModelProperty(name = "notBefore", value = "The date from when the certificate is valid", required = true) long notBefore; - @ApiModelProperty(name = "certificateserial", value = "The serial number of the certificate", required = true) - BigInteger certificateserial; + @ApiModelProperty(name = "certificateSerial", value = "The serial number of the certificate", required = true) + BigInteger certificateSerial; @ApiModelProperty(name = "issuer", value = "The identity of the authority that signs the SSL certificate", required = true) String issuer; @@ -83,12 +89,12 @@ public class CertificateResponse { this.notBefore = notBefore; } - public BigInteger getCertificateserial() { - return certificateserial; + public BigInteger getCertificateSerial() { + return certificateSerial; } - public void setCertificateserial(BigInteger certificateserial) { - this.certificateserial = certificateserial; + public void setCertificateSerial(BigInteger certificateSerial) { + this.certificateSerial = certificateSerial; } public String getIssuer() { @@ -146,4 +152,20 @@ public class CertificateResponse { public void setTenantId(int tenantId) { this.tenantId = tenantId; } + + public String getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(String deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + public String getCertificateId() { + return certificateId; + } + + public void setCertificateId(String certificateId) { + this.certificateId = certificateId; + } } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java index 328c2fcbfb..f90762897d 100755 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java @@ -130,7 +130,7 @@ public class CertificateGenerator { X509Certificate certificate = (X509Certificate) x509Certificate; certificateResponse.setNotAfter(certificate.getNotAfter().getTime()); certificateResponse.setNotBefore(certificate.getNotBefore().getTime()); - certificateResponse.setCertificateserial(certificate.getSerialNumber()); + certificateResponse.setCertificateSerial(certificate.getSerialNumber()); certificateResponse.setIssuer(certificate.getIssuerDN().getName()); certificateResponse.setSubject(certificate.getSubjectDN().getName()); certificateResponse.setCertificateVersion(certificate.getVersion()); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java index 3eb94d21f1..61d333413e 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java @@ -73,7 +73,7 @@ public interface CertificateManagementService { PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException; - boolean removeCertificate(String serialNumber) throws CertificateManagementException; + boolean removeCertificate(String certificateId) throws CertificateManagementException; List getCertificates() throws CertificateManagementException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java index 95ec72a111..bcd696f21e 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -174,20 +174,20 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe } @Override - public boolean removeCertificate(String serialNumber) throws CertificateManagementException { + public boolean removeCertificate(String certificateId) throws CertificateManagementException { try { CertificateManagementDAOFactory.beginTransaction(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); - boolean status = certificateDAO.removeCertificate(serialNumber); + boolean status = certificateDAO.removeCertificate(certificateId); CertificateManagementDAOFactory.commitTransaction(); return status; } catch (TransactionManagementException e) { - String msg = "Error occurred while removing certificate carrying serial number '" + serialNumber + "'"; + String msg = "Error occurred while removing certificate carrying certificate id '" + certificateId + "'"; log.error(msg, e); throw new CertificateManagementException(msg, e); } catch (CertificateManagementDAOException e) { CertificateManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while removing the certificate carrying serial number '" + serialNumber + + String msg = "Error occurred while removing the certificate carrying certificate id '" + certificateId + "' from the certificate repository"; log.error(msg, e); throw new CertificateManagementException(msg, e); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java index 81ff3db86f..ff6ad09e88 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java @@ -210,7 +210,7 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC X509Certificate x509Certificate = managementService.generateX509Certificate(); CertificateResponse certificateResponse = managementService.retrieveCertificate(x509Certificate.getSerialNumber().toString()); Assert.assertNotNull(certificateResponse); - Assert.assertEquals(x509Certificate.getSerialNumber(), certificateResponse.getCertificateserial()); + Assert.assertEquals(x509Certificate.getSerialNumber(), certificateResponse.getCertificateSerial()); } @Test(description = "This test case tests the retrieval of Certificates from keystore in desired pagination") From 81fd5687ef74fedfc9b6b1e88678d82b7ce23283 Mon Sep 17 00:00:00 2001 From: osh Date: Sun, 9 Jul 2023 00:50:57 +0530 Subject: [PATCH 12/36] Update user service and token retrieval --- .../core/impl/VppApplicationManagerImpl.java | 70 ++++++++++--------- .../application/mgt/core/util/DAOUtil.java | 31 ++++++-- 2 files changed, 61 insertions(+), 40 deletions(-) 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index 9ecc31ee46..f250af7a6b 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -114,12 +114,12 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { Gson gson = new Gson(); String userPayload = gson.toJson(wrapper); - ProxyResponse proxyResponse = callVPPBackend(USER_CREATE, userPayload, TOKEN, Constants.VPP.POST); + ProxyResponse proxyResponse = callVPPBackend(USER_CREATE, userPayload, getVppToken(), Constants.VPP.POST); if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { // Create user does not return any useful data. Its needed to call the backend again ProxyResponse getUserResponse = callVPPBackend(USER_GET + Constants.VPP.CLIENT_USER_ID_PARAM + - userDTO.getClientUserId(), userPayload, TOKEN, Constants.VPP.GET); + userDTO.getClientUserId(), userPayload, getVppToken(), Constants.VPP.GET); if ((getUserResponse.getCode() == HttpStatus.SC_OK || getUserResponse.getCode() == HttpStatus.SC_CREATED) && getUserResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { VppItuneUserResponseWrapper vppItuneUserResponseWrapper = gson.fromJson @@ -196,38 +196,40 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { Gson gson = new Gson(); String userPayload = gson.toJson(wrapper); try { - ProxyResponse proxyResponse = callVPPBackend(USER_UPDATE, userPayload, TOKEN, Constants.VPP.POST); + ProxyResponse proxyResponse = callVPPBackend(USER_UPDATE, userPayload, getVppToken(), Constants.VPP.POST); if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { - - log.error("userDTO " + userDTO.toString()); - - try { - ConnectionManagerUtil.beginDBTransaction(); - if (vppApplicationDAO.updateVppUser(userDTO, tenantId) == null) { + VppUserDTO currentUserDTO = getUserByDMUsername(userDTO.getDmUsername()); + if (currentUserDTO != null) { + userDTO.setId(currentUserDTO.getId()); + } + try { + ConnectionManagerUtil.beginDBTransaction(); + if (vppApplicationDAO.updateVppUser(userDTO, tenantId) == null) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Unable to update the Vpp user " +userDTO.getId(); + log.error(msg); + throw new ApplicationManagementException(msg); + } + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Unable to update the Vpp user " +userDTO.getId(); - log.error(msg); - throw new ApplicationManagementException(msg); + String msg = "Error occurred while updating the Vpp User."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while executing database transaction for Vpp User update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection for Vpp User update."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); } - ConnectionManagerUtil.commitDBTransaction(); - } catch (ApplicationManagementDAOException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Error occurred while updating the Vpp User."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (TransactionManagementException e) { - String msg = "Error occurred while executing database transaction for Vpp User update."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (DBConnectionException e) { - String msg = "Error occurred while retrieving the database connection for Vpp User update."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } finally { - ConnectionManagerUtil.closeDBConnection(); } - } + } catch (IOException e) { String msg = "Error while calling VPP backend to update"; log.error(msg, e); @@ -239,7 +241,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { public void syncUsers(String clientId) throws ApplicationManagementException { ProxyResponse proxyResponse = null; try { - proxyResponse = callVPPBackend(USER_GET, null, TOKEN, Constants + proxyResponse = callVPPBackend(USER_GET, null, getVppToken(), Constants .VPP.GET); if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { @@ -266,7 +268,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { if (nextPageIndex > 0) { // Not the first page url += "?pageIndex=" + nextPageIndex; } - proxyResponse = callVPPBackend(url, null, TOKEN, Constants.VPP.GET); + proxyResponse = callVPPBackend(url, null, getVppToken(), Constants.VPP.GET); if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { Gson gson = new Gson(); @@ -360,7 +362,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { private ItuneAppDTO lookupAsset(String packageName) throws ApplicationManagementException { String lookupURL = LOOKUP_API + packageName + LOOKUP_API_PREFIX; try { - ProxyResponse proxyResponse = callVPPBackend(lookupURL, null, TOKEN, Constants.VPP.GET); + ProxyResponse proxyResponse = callVPPBackend(lookupURL, null, getVppToken(), Constants.VPP.GET); if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.GET_APP_DATA_RESPONSE_START)) { String responseData = proxyResponse.getData(); @@ -467,12 +469,12 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { Gson gson = new Gson(); String payload = gson.toJson(vppAssociate); - ProxyResponse proxyResponse = callVPPBackend(ASSIGNMENTS_POST, payload, TOKEN, + ProxyResponse proxyResponse = callVPPBackend(ASSIGNMENTS_POST, payload, getVppToken(), Constants.VPP.POST); if ((proxyResponse.getCode() == HttpStatus.SC_OK || proxyResponse.getCode() == HttpStatus.SC_CREATED) && proxyResponse.getData().contains(Constants.VPP.EVENT_ID)) { // Create assignment does not return any useful data. Its needed to call the backend again - ProxyResponse getAssignmentResponse = callVPPBackend(ASSIGNMENTS_GET, null, TOKEN, Constants.VPP.GET); + ProxyResponse getAssignmentResponse = callVPPBackend(ASSIGNMENTS_GET, null, getVppToken(), Constants.VPP.GET); if ((getAssignmentResponse.getCode() == HttpStatus.SC_OK || getAssignmentResponse.getCode() == HttpStatus.SC_CREATED) && getAssignmentResponse.getData().contains(Constants.VPP.TOTAL_PAGES)) { // VppAssociateResponseWrapper vppAssociateResponseWrapper = gson.fromJson 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/DAOUtil.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/DAOUtil.java index 256a76bb0c..1f497ea5ec 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/DAOUtil.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/DAOUtil.java @@ -33,6 +33,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; +import java.text.SimpleDateFormat; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; @@ -375,10 +376,16 @@ public class DAOUtil { vppUserDTO.setDmUsername(rs.getString("DM_USERNAME")); } if (rs.getLong("CREATED_TIME") != 0) { - vppUserDTO.setCreatedTime(new Date(rs.getLong(("CREATED_TIME")) * 1000).toString()); + Date date = new Date(rs.getLong("CREATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppUserDTO.setCreatedTime(dateString); } if (rs.getLong("LAST_UPDATED_TIME") != 0) { - vppUserDTO.setLastUpdatedTime(new Date(rs.getLong(("LAST_UPDATED_TIME")) * 1000).toString()); + Date date = new Date(rs.getLong("LAST_UPDATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppUserDTO.setLastUpdatedTime(dateString); } vppUserDTOS.add(vppUserDTO); } @@ -416,10 +423,16 @@ public class DAOUtil { vppAssetDTO.setAppId(rs.getInt("APP_ID")); vppAssetDTO.setTenantId(rs.getInt("TENANT_ID")); if (rs.getLong("CREATED_TIME") != 0) { - vppAssetDTO.setCreatedTime(new Date(rs.getLong(("CREATED_TIME")) * 1000).toString()); + Date date = new Date(rs.getLong("CREATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppAssetDTO.setCreatedTime(dateString); } if (rs.getLong("LAST_UPDATED_TIME") != 0) { - vppAssetDTO.setLastUpdatedTime(new Date(rs.getLong(("LAST_UPDATED_TIME")) * 1000).toString()); + Date date = new Date(rs.getLong("LAST_UPDATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppAssetDTO.setLastUpdatedTime(dateString); } vppAssetDTO.setAdamId(rs.getString("ADAM_ID")); vppAssetDTO.setAssignedCount(rs.getString("ASSIGNED_COUNT")); @@ -461,10 +474,16 @@ public class DAOUtil { vppAssociationDTO.setId(rs.getInt("ID")); vppAssociationDTO.setAssociationType(rs.getString("ASSOCIATION_TYPE")); if (rs.getLong("CREATED_TIME") != 0) { - vppAssociationDTO.setCreatedTime(new Date(rs.getLong(("CREATED_TIME")) * 1000).toString()); + Date date = new Date(rs.getLong("CREATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppAssociationDTO.setCreatedTime(dateString); } if (rs.getLong("LAST_UPDATED_TIME") != 0) { - vppAssociationDTO.setLastUpdatedTime(new Date(rs.getLong(("LAST_UPDATED_TIME")) * 1000).toString()); + Date date = new Date(rs.getLong("LAST_UPDATED_TIME")); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateString = dateFormat.format(date); + vppAssociationDTO.setLastUpdatedTime(dateString); } vppAssociationDTO.setPricingParam(rs.getString("PRICING_PARAMS")); vppAssociationDTOS.add(vppAssociationDTO); From eb740773aa32c94c9356e579d249cfb404022b0d Mon Sep 17 00:00:00 2001 From: osh Date: Tue, 11 Jul 2023 15:59:42 +0530 Subject: [PATCH 13/36] Improve update asset DAO fixes https://roadmap.entgra.net/issues/10179 --- .../vpp/GenericVppApplicationDAOImpl.java | 102 ++++++++++++------ .../core/impl/VppApplicationManagerImpl.java | 1 + 2 files changed, 68 insertions(+), 35 deletions(-) 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 936e8da7e3..df29a3f4b7 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 @@ -261,9 +261,9 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp + "PRICING_PARAMS," + "PRODUCT_TYPE," + "RETIRED_COUNT," - + "REVOCABLE) " -// + "SUPPORTED_PLATFORMS) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + "REVOCABLE, " + + "SUPPORTED_PLATFORMS) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -279,9 +279,9 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp stmt.setString(9, vppAssetDTO.getProductType()); stmt.setString(10, vppAssetDTO.getRetiredCount()); stmt.setString(11, vppAssetDTO.getRevocable()); -// List platformList = vppAssetDTO.getSupportedPlatforms(); -// String platformString = String.join(",", platformList); -// stmt.setString(12, platformString); + List platformList = vppAssetDTO.getSupportedPlatforms(); + String platformString = String.join(",", platformList); + stmt.setString(12, platformString); stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { if (rs.next()) { @@ -305,39 +305,71 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp public VppAssetDTO updateAsset(VppAssetDTO vppAssetDTO, int tenantId) throws ApplicationManagementDAOException { - String sql = "UPDATE " - + "AP_ASSETS " - + "SET " - + "APP_ID = ?," - + "LAST_UPDATED_TIME = ?, " - + "ADAM_ID = ?, " - + "ASSIGNED_COUNT = ?, " - + "DEVICE_ASSIGNABLE = ?, " - + "PRICING_PARAMS = ?, " - + "PRODUCT_TYPE = ?, " - + "RETIRED_COUNT = ?, " - + "REVOCABLE = ? " -// + "SUPPORTED_PLATFORMS = ? " - + "WHERE ID = ? AND TENANT_ID = ?"; + String sql = "UPDATE AP_ASSETS SET "; + + if (vppAssetDTO.getAdamId() != null && !vppAssetDTO.getAdamId().isEmpty()) { + sql += "ADAM_ID = ?, "; + } + if (vppAssetDTO.getAssignedCount() != null && !vppAssetDTO.getAssignedCount().isEmpty()) { + sql += "ASSIGNED_COUNT = ?, "; + } + if (vppAssetDTO.getDeviceAssignable() != null && !vppAssetDTO.getDeviceAssignable().isEmpty()) { + sql += "DEVICE_ASSIGNABLE = ?, "; + } + if (vppAssetDTO.getPricingParam() != null && !vppAssetDTO.getPricingParam().isEmpty()) { + sql += "PRICING_PARAMS = ?, "; + } + if (vppAssetDTO.getProductType() != null && !vppAssetDTO.getProductType().isEmpty()) { + sql += "PRODUCT_TYPE = ?, "; + } + if (vppAssetDTO.getRetiredCount() != null && !vppAssetDTO.getRetiredCount().isEmpty()) { + sql += "RETIRED_COUNT = ?, "; + } + if (vppAssetDTO.getRevocable() != null && !vppAssetDTO.getRevocable().isEmpty()) { + sql += "REVOCABLE = ?, "; + } + if (vppAssetDTO.getSupportedPlatforms() != null && !vppAssetDTO.getSupportedPlatforms().isEmpty()) { + sql += "SUPPORTED_PLATFORMS = ?,"; + } + sql += "APP_ID = ?, LAST_UPDATED_TIME = ? WHERE ID = ? AND TENANT_ID = ?"; + try { Connection conn = this.getDBConnection(); long updatedTime = System.currentTimeMillis(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, vppAssetDTO.getAppId()); - stmt.setLong(2, updatedTime); - stmt.setString(3, vppAssetDTO.getAdamId()); - stmt.setString(4, vppAssetDTO.getAssignedCount()); - stmt.setString(5, vppAssetDTO.getDeviceAssignable()); - stmt.setString(6, vppAssetDTO.getPricingParam()); - stmt.setString(7, vppAssetDTO.getProductType()); - stmt.setString(8, vppAssetDTO.getRetiredCount()); - stmt.setString(9, vppAssetDTO.getRevocable()); -// List platformList = vppAssetDTO.getSupportedPlatforms(); -// String platformString = String.join(",", platformList); -// stmt.setString(10, platformString); - stmt.setInt(10, vppAssetDTO.getId()); - stmt.setLong(11, tenantId); - stmt.executeUpdate(); + int x = 0; + + if (vppAssetDTO.getAdamId() != null && !vppAssetDTO.getAdamId().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getAdamId()); + } + if (vppAssetDTO.getAssignedCount() != null && !vppAssetDTO.getAssignedCount().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getAssignedCount()); + } + if (vppAssetDTO.getDeviceAssignable() != null && !vppAssetDTO.getDeviceAssignable().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getDeviceAssignable()); + } + if (vppAssetDTO.getPricingParam() != null && !vppAssetDTO.getPricingParam().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getPricingParam()); + } + if (vppAssetDTO.getProductType() != null && !vppAssetDTO.getProductType().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getProductType()); + } + if (vppAssetDTO.getRetiredCount() != null && !vppAssetDTO.getRetiredCount().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getRetiredCount()); + } + if (vppAssetDTO.getRevocable() != null && !vppAssetDTO.getRevocable().isEmpty()) { + stmt.setString(++x, vppAssetDTO.getRevocable()); + } + if (vppAssetDTO.getSupportedPlatforms() != null && !vppAssetDTO.getSupportedPlatforms().isEmpty()) { + List platformList = vppAssetDTO.getSupportedPlatforms(); + String platformString = String.join(",", platformList); + stmt.setString(++x, platformString); + } + + stmt.setInt(++x, vppAssetDTO.getAppId()); + stmt.setLong(++x, updatedTime); + stmt.setInt(++x, vppAssetDTO.getId()); + stmt.setLong(++x, tenantId); if (stmt.executeUpdate() == 1) { return vppAssetDTO; } 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index f250af7a6b..8ab98ad5a5 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -315,6 +315,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { } } else { vppAssetDTOs.setAppId(application.getId()); + vppAssetDTOs.setSupportedPlatforms(vppAssetDTO.getSupportedPlatforms()); try { ConnectionManagerUtil.beginDBTransaction(); if (vppApplicationDAO.updateAsset(vppAssetDTOs, tenantId) == null) { From 01df3700322964fdb407d992597c49191f10ba6d Mon Sep 17 00:00:00 2001 From: osh Date: Thu, 13 Jul 2023 14:40:15 +0530 Subject: [PATCH 14/36] Add db scripts --- .../dbscripts/cdm/application-mgt/h2.sql | 54 ++++++++++++++++++ .../dbscripts/cdm/application-mgt/mssql.sql | 56 +++++++++++++++++++ .../dbscripts/cdm/application-mgt/mysql.sql | 54 ++++++++++++++++++ .../dbscripts/cdm/application-mgt/oracle.sql | 47 ++++++++++++++++ .../cdm/application-mgt/postgresql.sql | 53 ++++++++++++++++++ 5 files changed, 264 insertions(+) diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql index f9c5861831..e129d6f68e 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql @@ -325,3 +325,57 @@ CREATE TABLE IF NOT EXISTS AP_APP_FAVOURITES( FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); + +-- ----------------------------------------------------- +-- Table AP_VPP_USER +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_VPP_USER ( + ID INT NOT NULL AUTO_INCREMENT, + CLIENT_USER_ID VARCHAR(255) NULL, + DM_USERNAME VARCHAR(255) NOT NULL, + TENANT_ID INT NOT NULL, + EMAIL VARCHAR(255) NULL, + INVITE_CODE VARCHAR(255) NULL, + STATUS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + MANAGED_ID VARCHAR(255) NULL, + TEMP_PASSWORD VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_ASSETS +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_ASSETS ( + ID INT NOT NULL AUTO_INCREMENT, + APP_ID INT NULL, + TENANT_ID INT NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + ADAM_ID VARCHAR(255) NULL, + ASSIGNED_COUNT VARCHAR(255) NULL, + DEVICE_ASSIGNABLE VARCHAR(255) NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRODUCT_TYPE VARCHAR(255) NULL, + RETIRED_COUNT VARCHAR(255) NULL, + REVOCABLE VARCHAR(255) NULL, + SUPPORTED_PLATFORMS VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_VPP_ASSOCIATION +-- ----------------------------------------------------- + +CREATE TABLE IF NOT EXISTS AP_VPP_ASSOCIATION ( + ID INT NOT NULL AUTO_INCREMENT, + ASSET_ID INT, + USER_ID INT, + TENANT_ID INT NOT NULL, + ASSOCIATION_TYPE VARCHAR(255) NOT NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE +); diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql index 9b2e89b3f7..143d2f2103 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql @@ -342,3 +342,59 @@ CREATE TABLE AP_APP_FAVOURITES( FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID) ); + +-- ----------------------------------------------------- +-- Table AP_VPP_USER +-- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'AP_VPP_USER') AND type in (N'U')) +CREATE TABLE AP_VPP_USER ( + ID INT NOT NULL IDENTITY(1,1), + CLIENT_USER_ID VARCHAR(255) NULL, + DM_USERNAME VARCHAR(255) NOT NULL, + TENANT_ID INT NOT NULL, + EMAIL VARCHAR(255) NULL, + INVITE_CODE VARCHAR(255) NULL, + STATUS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + MANAGED_ID VARCHAR(255) NULL, + TEMP_PASSWORD VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_ASSETS +-- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'AP_ASSETS') AND type in (N'U')) +CREATE TABLE AP_ASSETS ( + ID INT NOT NULL IDENTITY(1,1), + APP_ID INT NULL, + TENANT_ID INT NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + ADAM_ID VARCHAR(255) NULL, + ASSIGNED_COUNT VARCHAR(255) NULL, + DEVICE_ASSIGNABLE VARCHAR(255) NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRODUCT_TYPE VARCHAR(255) NULL, + RETIRED_COUNT VARCHAR(255) NULL, + REVOCABLE VARCHAR(255) NULL, + SUPPORTED_PLATFORMS VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_VPP_ASSOCIATION +-- ----------------------------------------------------- +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'AP_VPP_ASSOCIATION') AND type in (N'U')) +CREATE TABLE AP_VPP_ASSOCIATION ( + ID INT NOT NULL IDENTITY(1,1), + ASSET_ID INT, + USER_ID INT, + TENANT_ID INT NOT NULL, + ASSOCIATION_TYPE VARCHAR(255) NOT NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE +); diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql index 54ba58a9fe..d1ae759084 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql @@ -272,4 +272,58 @@ CREATE TABLE IF NOT EXISTS AP_APP_FAVOURITES( TENANT_ID INTEGER NOT NULL, PRIMARY KEY(ID), CONSTRAINT AP_APP_FAVOURITES_AP_APP_ID_fk FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID) +); + +-- ----------------------------------------------------- +-- Table AP_VPP_USER +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_VPP_USER ( + ID INT NOT NULL AUTO_INCREMENT, + CLIENT_USER_ID VARCHAR(255) NULL, + DM_USERNAME VARCHAR(255) NOT NULL, + TENANT_ID INT NOT NULL, + EMAIL VARCHAR(255) NULL, + INVITE_CODE VARCHAR(255) NULL, + STATUS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + MANAGED_ID VARCHAR(255) NULL, + TEMP_PASSWORD VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_ASSETS +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_ASSETS ( + ID INT NOT NULL AUTO_INCREMENT, + APP_ID INT NULL, + TENANT_ID INT NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + ADAM_ID VARCHAR(255) NULL, + ASSIGNED_COUNT VARCHAR(255) NULL, + DEVICE_ASSIGNABLE VARCHAR(255) NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRODUCT_TYPE VARCHAR(255) NULL, + RETIRED_COUNT VARCHAR(255) NULL, + REVOCABLE VARCHAR(255) NULL, + SUPPORTED_PLATFORMS VARCHAR(255) NULL, + PRIMARY KEY (ID) +); + +-- ----------------------------------------------------- +-- Table AP_VPP_ASSOCIATION +-- ----------------------------------------------------- + +CREATE TABLE IF NOT EXISTS AP_VPP_ASSOCIATION ( + ID INT NOT NULL AUTO_INCREMENT, + ASSET_ID INT, + USER_ID INT, + TENANT_ID INT NOT NULL, + ASSOCIATION_TYPE VARCHAR(255) NOT NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE ); \ No newline at end of file diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql index 79c5b1345f..c2f82d7e39 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql @@ -420,3 +420,50 @@ CREATE TABLE IF NOT EXISTS AP_APP_FAVOURITES( REFERENCES AP_APP (ID) ) / + +CREATE TABLE AP_VPP_USER ( + ID number GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL, + CLIENT_USER_ID VARCHAR2(255) NULL, + DM_USERNAME VARCHAR2(255) NOT NULL, + TENANT_ID INT NOT NULL, + EMAIL VARCHAR2(255) NULL, + INVITE_CODE VARCHAR2(255) NULL, + STATUS VARCHAR2(255) NULL, + CREATED_TIME NUMBER(19) NULL, + LAST_UPDATED_TIME NUMBER(19) NULL, + MANAGED_ID VARCHAR2(255) NULL, + TEMP_PASSWORD VARCHAR2(255) NULL, + PRIMARY KEY (ID) +) +/ + +CREATE TABLE AP_ASSETS ( + ID number GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL, + APP_ID INT NULL, + TENANT_ID INT NOT NULL, + CREATED_TIME NUMBER(19) NULL, + LAST_UPDATED_TIME NUMBER(19) NULL, + ADAM_ID VARCHAR2(255) NULL, + ASSIGNED_COUNT VARCHAR2(255) NULL, + DEVICE_ASSIGNABLE VARCHAR2(255) NULL, + PRICING_PARAMS VARCHAR2(255) NULL, + PRODUCT_TYPE VARCHAR2(255) NULL, + RETIRED_COUNT VARCHAR2(255) NULL, + REVOCABLE VARCHAR2(255) NULL, + SUPPORTED_PLATFORMS VARCHAR2(255) NULL, + PRIMARY KEY (ID) +) +/ + +CREATE TABLE AP_VPP_ASSOCIATION ( + ID number GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL, + ASSET_ID INT, + USER_ID INT, + TENANT_ID INT NOT NULL, + ASSOCIATION_TYPE VARCHAR2(255) NOT NULL, + PRICING_PARAMS VARCHAR2(255) NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE +) +/ diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql index e8e1dbb225..f1645de58b 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql @@ -352,3 +352,56 @@ CREATE TABLE IF NOT EXISTS AP_APP_FAVOURITES( FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); + +-- ----------------------------------------------------- +-- Table AP_VPP_USER +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_VPP_USER ( + ID INTEGER NOT NULL DEFAULT NEXTVAL('AP_VPP_USER_seq'), + CLIENT_USER_ID VARCHAR(255) NULL, + DM_USERNAME VARCHAR(255) NOT NULL, + TENANT_ID INTEGER NOT NULL, + EMAIL VARCHAR(255) NULL, + INVITE_CODE VARCHAR(255) NULL, + STATUS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + MANAGED_ID VARCHAR(255) NULL, + TEMP_PASSWORD VARCHAR(255) NULL, + PRIMARY KEY (ID) + ); + +-- ----------------------------------------------------- +-- Table AP_ASSETS +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_ASSETS ( + ID INTEGER NOT NULL DEFAULT NEXTVAL('AP_ASSETS_seq'), + APP_ID INTEGER NULL, + TENANT_ID INTEGER NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, + ADAM_ID VARCHAR(255) NULL, + ASSIGNED_COUNT VARCHAR(255) NULL, + DEVICE_ASSIGNABLE VARCHAR(255) NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRODUCT_TYPE VARCHAR(255) NULL, + RETIRED_COUNT VARCHAR(255) NULL, + REVOCABLE VARCHAR(255) NULL, + SUPPORTED_PLATFORMS VARCHAR(255) NULL, + PRIMARY KEY (ID) + ); + +-- ----------------------------------------------------- +-- Table AP_VPP_ASSOCIATION +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_VPP_ASSOCIATION ( + ID INTEGER NOT NULL DEFAULT NEXTVAL('AP_VPP_ASSOCIATION_seq'), + ASSET_ID INTEGER, + USER_ID INTEGER, + TENANT_ID INTEGER NOT NULL, + ASSOCIATION_TYPE VARCHAR(255) NOT NULL, + PRICING_PARAMS VARCHAR(255) NULL, + PRIMARY KEY (ID), + CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE + ); From dd7910268e685611498eb2def19083383686bfc3 Mon Sep 17 00:00:00 2001 From: osh Date: Mon, 17 Jul 2023 13:36:39 +0530 Subject: [PATCH 15/36] Add vpp token field --- .../mgt/core/application/mgt/common/DepConfig.java | 9 +++++++++ .../core/dao/impl/vpp/GenericVppApplicationDAOImpl.java | 2 +- .../mgt/core/impl/VppApplicationManagerImpl.java | 2 +- 3 files changed, 11 insertions(+), 2 deletions(-) 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/DepConfig.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DepConfig.java index 712ad11df2..244f88fb08 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DepConfig.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/DepConfig.java @@ -26,6 +26,7 @@ public class DepConfig { private String accessToken; private String accessSecret; private String accessTokenExpiry; + private String vppToken; public String getAgentPackageName() { return agentPackageName; @@ -59,6 +60,14 @@ public class DepConfig { this.accessToken = accessToken; } + public String getVppToken() { + return vppToken; + } + + public void setVppToken(String vppToken) { + this.vppToken = vppToken; + } + public String getAccessSecret() { return accessSecret; } 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 df29a3f4b7..38fa090f94 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 @@ -174,7 +174,7 @@ public class GenericVppApplicationDAOImpl extends AbstractDAOImpl implements Vp + "CREATED_TIME, " + "LAST_UPDATED_TIME, " + "MANAGED_ID, " - + "TEMP_PASSWORD " + + "TEMP_PASSWORD, " + "DM_USERNAME " + "FROM AP_VPP_USER " + "WHERE DM_USERNAME = ? AND TENANT_ID = ?"; 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java index 8ab98ad5a5..dc9b34e40d 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/VppApplicationManagerImpl.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/VppApplicationManagerImpl.java @@ -591,7 +591,7 @@ public class VppApplicationManagerImpl implements VPPApplicationManager { Gson g = new Gson(); DepConfig depConfigs = g.fromJson(metadata.getMetaValue(), DepConfig.class); - token = depConfigs.getAccessToken(); + token = depConfigs.getVppToken(); return token; } }catch (MetadataManagementException e) { From 4b9cad1c755543053234cb01e7955982a9c9d0b5 Mon Sep 17 00:00:00 2001 From: osh Date: Mon, 17 Jul 2023 16:13:07 +0530 Subject: [PATCH 16/36] Update db queries --- .../src/main/resources/dbscripts/cdm/application-mgt/h2.sql | 2 ++ .../src/main/resources/dbscripts/cdm/application-mgt/mssql.sql | 2 ++ .../src/main/resources/dbscripts/cdm/application-mgt/mysql.sql | 2 ++ .../src/main/resources/dbscripts/cdm/application-mgt/oracle.sql | 2 ++ .../main/resources/dbscripts/cdm/application-mgt/postgresql.sql | 2 ++ 5 files changed, 10 insertions(+) diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql index e129d6f68e..27c7669289 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql @@ -375,6 +375,8 @@ CREATE TABLE IF NOT EXISTS AP_VPP_ASSOCIATION ( TENANT_ID INT NOT NULL, ASSOCIATION_TYPE VARCHAR(255) NOT NULL, PRICING_PARAMS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, PRIMARY KEY (ID), CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql index 143d2f2103..0c95c74ddd 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql @@ -393,6 +393,8 @@ CREATE TABLE AP_VPP_ASSOCIATION ( USER_ID INT, TENANT_ID INT NOT NULL, ASSOCIATION_TYPE VARCHAR(255) NOT NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, PRICING_PARAMS VARCHAR(255) NULL, PRIMARY KEY (ID), CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql index d1ae759084..448c249b85 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql @@ -323,6 +323,8 @@ CREATE TABLE IF NOT EXISTS AP_VPP_ASSOCIATION ( TENANT_ID INT NOT NULL, ASSOCIATION_TYPE VARCHAR(255) NOT NULL, PRICING_PARAMS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, PRIMARY KEY (ID), CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql index c2f82d7e39..66e518a59e 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql @@ -462,6 +462,8 @@ CREATE TABLE AP_VPP_ASSOCIATION ( TENANT_ID INT NOT NULL, ASSOCIATION_TYPE VARCHAR2(255) NOT NULL, PRICING_PARAMS VARCHAR2(255) NULL, + CREATED_TIME NUMBER(19) NULL, + LAST_UPDATED_TIME NUMBER(19) NULL, PRIMARY KEY (ID), CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE, CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql index f1645de58b..7f51f6e935 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql @@ -401,6 +401,8 @@ CREATE TABLE IF NOT EXISTS AP_VPP_ASSOCIATION ( TENANT_ID INTEGER NOT NULL, ASSOCIATION_TYPE VARCHAR(255) NOT NULL, PRICING_PARAMS VARCHAR(255) NULL, + CREATED_TIME BIGINT NULL, + LAST_UPDATED_TIME BIGINT NULL, PRIMARY KEY (ID), CONSTRAINT AP_VPP_ASSETS_fk FOREIGN KEY (ASSET_ID) REFERENCES AP_ASSETS (ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT AP_VPP_VPP_USER_fk FOREIGN KEY (USER_ID) REFERENCES AP_VPP_USER (ID) ON DELETE CASCADE ON UPDATE CASCADE From e7b0255a957d3542708a876b20ce668ee9c2ab31 Mon Sep 17 00:00:00 2001 From: osh Date: Tue, 18 Jul 2023 19:34:11 +0530 Subject: [PATCH 17/36] Add get device apps by id service --- .../common/services/ApplicationManager.java | 11 +++ .../mgt/core/dao/ApplicationDAO.java | 10 +++ .../GenericApplicationDAOImpl.java | 70 +++++++++++++++++++ .../mgt/core/impl/ApplicationManagerImpl.java | 29 ++++++++ .../application/mgt/core/util/DAOUtil.java | 20 ++++++ 5 files changed, 140 insertions(+) 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 0c75b3b284..7451b8469f 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 @@ -273,6 +273,17 @@ public interface ApplicationManager { */ ApplicationDTO getApplication(int applicationId) throws ApplicationManagementException; + /** + * This method is responsible to provide application data for given deviceId. + * + * @param deviceId id of the device + * @return {@link ApplicationDTO} + * @throws ApplicationManagementException + * if an error occurred while getting subscribed app details for relevant device id, + */ + ApplicationList getSubscribedAppsOfDevice(int deviceId) + throws ApplicationManagementException; + /** * To get the Application for given Id. * 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 6886e824f2..d46ed6336b 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 @@ -150,6 +150,16 @@ public interface ApplicationDAO { */ ApplicationDTO getApplication(int applicationId, int tenantId) throws ApplicationManagementDAOException; + /** + * To get the application with the given id + * + * @param deviceId ID of the device which the apps are installed on. + * @param tenantId ID of the tenant. + * @return the application + * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception. + */ + List getSubscribedAppsOfDevice(int deviceId, int tenantId) throws ApplicationManagementDAOException; + /** * To get the application with the given uuid * 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 a6abaef4cb..361746f623 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 @@ -656,6 +656,76 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic } } + @Override + public List getSubscribedAppsOfDevice(int deviceId, int tenantId) throws + ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Getting all installed apps of device " + deviceId + + " from the database"); + } + List appList = null; + + String sql = "SELECT " + + "AP_APP.ID AS APP_ID, " + + "AP_APP.NAME AS APP_NAME, " + + "AP_APP.DESCRIPTION AS APP_DESCRIPTION, " + + "AP_APP.TYPE AS APP_TYPE, " + + "AP_APP.STATUS AS APP_STATUS, " + + "AP_APP.SUB_TYPE AS APP_SUB_TYPE, " + + "AP_APP.CURRENCY AS APP_CURRENCY, " + + "AP_APP.RATING AS APP_RATING, " + + "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, " + + "AP_APP_RELEASE.ID AS RELEASE_ID, " + + "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, " + + "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, " + + "AP_APP_RELEASE.UUID AS RELEASE_UUID, " + + "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, " + + "AP_APP_RELEASE.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, " + + "AP_APP_RELEASE.ICON_LOCATION AS AP_RELEASE_ICON_LOC, " + + "AP_APP_RELEASE.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, " + + "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, " + + "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, " + + "AP_APP_RELEASE.SC_3_LOCATION AS AP_RELEASE_SC3, " + + "AP_APP_RELEASE.APP_HASH_VALUE AS RELEASE_HASH_VALUE, " + + "AP_APP_RELEASE.APP_PRICE AS RELEASE_PRICE, " + + "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, " + + "AP_APP_RELEASE.PACKAGE_NAME AS PACKAGE_NAME, " + + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + + "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + + "FROM AP_APP " + + "JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " + + "JOIN AP_DEVICE_SUBSCRIPTION ON AP_APP_RELEASE.ID = AP_DEVICE_SUBSCRIPTION.AP_APP_RELEASE_ID " + + "WHERE AP_DEVICE_SUBSCRIPTION.DM_DEVICE_ID = ? AND AP_DEVICE_SUBSCRIPTION.TENANT_ID= ? " + +"AND AP_DEVICE_SUBSCRIPTION.STATUS= 'COMPLETED'"; + + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, deviceId); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + appList = new ArrayList<>(); + while (rs.next()) { + ApplicationDTO app = DAOUtil.loadDeviceApp(rs); + appList.add(app); + } + return appList; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection for getting all apps installed on the device of " + + "device Id: " + deviceId + "."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while while running SQL to get all installed apps of device with device Id: " + deviceId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public boolean updateApplication(ApplicationDTO applicationDTO, 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/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 3bb8ba8260..257994d0a9 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 @@ -1444,6 +1444,35 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + @Override + public ApplicationList getSubscribedAppsOfDevice(int deviceId) throws ApplicationManagementException { + ApplicationList applicationList = new ApplicationList(); + List applications = new ArrayList<>(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + List applicationDTOS = this.applicationDAO.getSubscribedAppsOfDevice(deviceId, tenantId); + for (ApplicationDTO applicationDTO: applicationDTOS) { + applicationDTO.setTags(this.applicationDAO.getAppTags(applicationDTO.getId(), tenantId)); + applicationDTO.setAppCategories(this.applicationDAO.getAppCategories(applicationDTO.getId(), tenantId)); + applications.add(APIUtil.appDtoToAppResponse(applicationDTO)); + } + applicationList.setApplications(applications); + return applicationList; + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred when getting installed apps of device with device id: " + + deviceId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "DB Connection error occurred while getting installed apps of device with device id: " + deviceId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + /** * Check whether given OS range is valid or invalid * 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/DAOUtil.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/DAOUtil.java index 1960230759..5538cbfa05 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/DAOUtil.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/DAOUtil.java @@ -241,6 +241,26 @@ public class DAOUtil { return applicationDTOs.get(0); } + public static ApplicationDTO loadDeviceApp(ResultSet rs) throws SQLException { + ApplicationDTO application = new ApplicationDTO(); + application.setId( rs.getInt("APP_ID")); + application.setName(rs.getString("APP_NAME")); + application.setDescription(rs.getString("APP_DESCRIPTION")); + application.setType(rs.getString("APP_TYPE")); + application.setSubType(rs.getString("APP_SUB_TYPE")); + application.setPaymentCurrency(rs.getString("APP_CURRENCY")); + application.setStatus(rs.getString("APP_STATUS")); + application.setAppRating(rs.getDouble("APP_RATING")); + application.setDeviceTypeId(rs.getInt("APP_DEVICE_TYPE_ID")); + ApplicationReleaseDTO releaseDTO = constructAppReleaseDTO(rs); + List releaseDtoList = new ArrayList<>(); + if (releaseDTO != null) { + releaseDtoList.add(constructAppReleaseDTO(rs)); + application.setApplicationReleaseDTOs(releaseDtoList); + } + return application; + } + /** * Populates {@link ApplicationReleaseDTO} object with the result obtained from the database. * From 77b68af5d0a80d194fdd4a4f5061efe734f21b44 Mon Sep 17 00:00:00 2001 From: osh Date: Tue, 18 Jul 2023 23:10:23 +0530 Subject: [PATCH 18/36] Add pagination --- .../mgt/common/services/ApplicationManager.java | 3 ++- .../application/mgt/core/dao/ApplicationDAO.java | 3 ++- .../impl/application/GenericApplicationDAOImpl.java | 11 ++++++++++- .../mgt/core/impl/ApplicationManagerImpl.java | 13 +++++++++++-- 4 files changed, 25 insertions(+), 5 deletions(-) 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 7451b8469f..57890f53eb 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 @@ -27,6 +27,7 @@ import io.entgra.device.mgt.core.application.mgt.common.response.Category; import io.entgra.device.mgt.core.application.mgt.common.response.Tag; import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import io.entgra.device.mgt.core.application.mgt.common.ApplicationArtifact; @@ -281,7 +282,7 @@ public interface ApplicationManager { * @throws ApplicationManagementException * if an error occurred while getting subscribed app details for relevant device id, */ - ApplicationList getSubscribedAppsOfDevice(int deviceId) + ApplicationList getSubscribedAppsOfDevice(int deviceId, PaginationRequest request) throws ApplicationManagementException; /** 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 d46ed6336b..ffa85b260d 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 @@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.CategoryDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.TagDTO; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import java.util.List; @@ -158,7 +159,7 @@ public interface ApplicationDAO { * @return the application * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception. */ - List getSubscribedAppsOfDevice(int deviceId, int tenantId) throws ApplicationManagementDAOException; + List getSubscribedAppsOfDevice(int deviceId, int tenantId, PaginationRequest request) throws ApplicationManagementDAOException; /** * To get the application with the given uuid 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 361746f623..1e403e5848 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 @@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.device.mgt.core.application.mgt.core.util.Constants; import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -657,7 +658,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic } @Override - public List getSubscribedAppsOfDevice(int deviceId, int tenantId) throws + public List getSubscribedAppsOfDevice(int deviceId, int tenantId, PaginationRequest request) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { log.debug("Getting all installed apps of device " + deviceId @@ -700,11 +701,19 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic + "WHERE AP_DEVICE_SUBSCRIPTION.DM_DEVICE_ID = ? AND AP_DEVICE_SUBSCRIPTION.TENANT_ID= ? " +"AND AP_DEVICE_SUBSCRIPTION.STATUS= 'COMPLETED'"; + if (request != null) { + sql = sql + " LIMIT ?,?"; + } + try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, deviceId); stmt.setInt(2, tenantId); + if (request != null) { + stmt.setInt(3, request.getStartIndex()); + stmt.setInt(4, request.getRowCount()); + } try (ResultSet rs = stmt.executeQuery()) { appList = new ArrayList<>(); while (rs.next()) { 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 257994d0a9..22f5688b07 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 @@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestExcept 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.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import org.apache.commons.codec.digest.DigestUtils; @@ -1445,19 +1446,27 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public ApplicationList getSubscribedAppsOfDevice(int deviceId) throws ApplicationManagementException { + public ApplicationList getSubscribedAppsOfDevice(int deviceId, PaginationRequest request) throws ApplicationManagementException { ApplicationList applicationList = new ApplicationList(); List applications = new ArrayList<>(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { ConnectionManagerUtil.openDBConnection(); - List applicationDTOS = this.applicationDAO.getSubscribedAppsOfDevice(deviceId, tenantId); + List applicationDTOS = this.applicationDAO.getSubscribedAppsOfDevice(deviceId, tenantId, request); for (ApplicationDTO applicationDTO: applicationDTOS) { applicationDTO.setTags(this.applicationDAO.getAppTags(applicationDTO.getId(), tenantId)); applicationDTO.setAppCategories(this.applicationDAO.getAppCategories(applicationDTO.getId(), tenantId)); applications.add(APIUtil.appDtoToAppResponse(applicationDTO)); } + + List totalApplications = this.applicationDAO.getSubscribedAppsOfDevice(deviceId, tenantId, null); + Pagination pagination = new Pagination(); + pagination.setCount(totalApplications.size()); + pagination.setSize(applications.size()); + pagination.setOffset(request.getStartIndex()); + pagination.setLimit(request.getRowCount()); applicationList.setApplications(applications); + applicationList.setPagination(pagination); return applicationList; } catch (ApplicationManagementDAOException e) { String msg = "Error occurred when getting installed apps of device with device id: " From 453034c0e2980ff6b37e8bc9356e8cd02e876ef8 Mon Sep 17 00:00:00 2001 From: navodzoysa Date: Fri, 4 Aug 2023 00:32:56 +0530 Subject: [PATCH 19/36] Revert Windows permission temp fix --- .../framework/authorizer/PermissionAuthorizer.java | 5 ----- 1 file changed, 5 deletions(-) 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 3cddf49e29..0d509200e4 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 @@ -79,11 +79,6 @@ public class PermissionAuthorizer { matchingResources.add(new MatchingResource(permission.getUrlPattern().replace(context, ""), permission.getPath())); } } - //TODO :: Temporary fix for windows bst api url mismatch error - else if ("/api/device-mgt/windows/v1.0/bst/authentication".equals(permission.getUrl())) { - requiredPermission = "/permission/admin/device-mgt/devices/enroll/windows"; - break; - } } if (requiredPermission == null) { From 607b11a224e7bba8f84bc3b8778c34e68fc7bccf Mon Sep 17 00:00:00 2001 From: navodzoysa Date: Tue, 8 Aug 2023 23:41:06 +0530 Subject: [PATCH 20/36] Add missing Windows enroll scope --- .../src/main/resources/conf/mdm-ui-config.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 b16935562d..4e7b97fc6e 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 @@ -215,6 +215,7 @@ perm:android:google-account perm:android:info perm:windows:lock-devices + perm:windows:enroll perm:windows:disenroll perm:windows:wipe perm:windows:ring @@ -227,7 +228,7 @@ perm:android:clear-application perm:android:suspend-package perm:android:alternate-install - perm:ios:lock + perm:ios:lock perm:ios:location perm:ios:ring perm:ios:clear-passcode From e6ee539239ed9d625120d3fe8af358b72896758b Mon Sep 17 00:00:00 2001 From: osh Date: Wed, 9 Aug 2023 00:27:33 +0530 Subject: [PATCH 21/36] Add api changes for getting app details of operation --- .../common/services/SubscriptionManager.java | 10 ++++ .../mgt/core/dao/SubscriptionDAO.java | 12 +++++ .../GenericSubscriptionDAOImpl.java | 46 +++++++++++++++++++ .../core/impl/SubscriptionManagerImpl.java | 26 +++++++++++ .../api/ActivityInfoProviderService.java | 12 ++++- .../impl/ActivityProviderServiceImpl.java | 29 ++++++++++-- .../impl/ActivityProviderServiceImplTest.java | 2 +- .../mgt/common/operation/mgt/Activity.java | 46 +++++++++++++++++++ 8 files changed, 178 insertions(+), 5 deletions(-) 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/SubscriptionManager.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/SubscriptionManager.java index f2bd759fd7..e06a17cb9b 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/SubscriptionManager.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/SubscriptionManager.java @@ -27,6 +27,7 @@ import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import java.util.List; import java.util.Properties; @@ -207,4 +208,13 @@ public interface SubscriptionManager { */ PaginationResult getAppInstalledSubscribeDevices(PaginationRequest request, String appUUID, String subType, String subTypeName) throws ApplicationManagementException; + + + /*** + * This method is responsible for retrieving application details of the passed operation id. + * @param id ID of the related operation + * @return {@link Activity} Activity result of the app information. + * @throws {@link SubscriptionManagementException} Exception of the subscription management + */ + Activity getOperationAppDetails(String id) throws SubscriptionManagementException; } 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 8b5caec6ac..804a4a29e2 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 @@ -23,6 +23,7 @@ import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDT import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO; import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import java.util.List; import java.util.Map; @@ -252,4 +253,15 @@ public interface SubscriptionDAO { * @throws {@link ApplicationManagementDAOException} if connections establishment fails. */ Map getCurrentInstalledAppVersion(int appId, List deviceIdList, String installedVersion) throws ApplicationManagementDAOException; + + + /** + * Retrieves app details by operation id. + * + * @param operationId ID of the operation which app details needs to be retrieved + * @param tenantId ID of tenant + * @return {@link Activity} + * @throws ApplicationManagementDAOException if error occurred while retrieving the app details + */ + Activity getOperationAppDetails(int operationId, 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/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 353340e3d3..373ade8595 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 @@ -21,6 +21,7 @@ import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus; @@ -1435,4 +1436,49 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc throw new ApplicationManagementDAOException(msg, e); } } + + public Activity getOperationAppDetails(int operationId, int tenantId) throws ApplicationManagementDAOException { + Activity activity = null; + try { + String sql = "SELECT " + + "AP.NAME, " + + "AR.PACKAGE_NAME, " + + "DS.SUBSCRIBED_BY, " + + "DS.STATUS " + + "FROM AP_APP_SUB_OP_MAPPING SOP " + + "JOIN AP_DEVICE_SUBSCRIPTION DS ON SOP.AP_DEVICE_SUBSCRIPTION_ID = DS.ID " + + "JOIN AP_APP_RELEASE AR ON DS.AP_APP_RELEASE_ID = AR.ID " + + "JOIN AP_APP AP ON AP.ID = AR.AP_APP_ID " + + " WHERE SOP.OPERATION_ID = ? AND SOP.TENANT_ID = ?"; + + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, operationId); + stmt.setInt(2,tenantId); + try (ResultSet rs = stmt.executeQuery()) { + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved app details for operation " + + operationId); + } + while (rs.next()) { + activity = new Activity(); + activity.setAppName(rs.getString("NAME")); + activity.setUsername(rs.getString("SUBSCRIBED_BY")); + activity.setPackageName(rs.getString("PACKAGE_NAME")); + activity.setStatus(rs.getString("STATUS")); + } + return activity; + } + } + } catch (DBConnectionException e) { + String msg = + "Error occurred while getting the app details from the database related to operation " + operationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when processing SQL to retrieve app details of operation" + operationId; + 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/impl/SubscriptionManagerImpl.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/SubscriptionManagerImpl.java index d89039dee5..0829906682 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/SubscriptionManagerImpl.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/SubscriptionManagerImpl.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.application.mgt.core.impl; import com.google.gson.Gson; import io.entgra.device.mgt.core.application.mgt.core.exception.BadRequestException; +import io.entgra.device.mgt.core.device.mgt.core.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; import io.entgra.device.mgt.core.notification.logger.AppInstallLogContext; import io.entgra.device.mgt.core.notification.logger.impl.EntgraAppInstallLoggerImpl; @@ -1568,4 +1569,29 @@ public class SubscriptionManagerImpl implements SubscriptionManager { ConnectionManagerUtil.closeDBConnection(); } } + + @Override + public Activity getOperationAppDetails(String id) throws SubscriptionManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + int operationId = Integer.parseInt( + id.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); + if (operationId == 0) { + throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); + } + try { + ConnectionManagerUtil.openDBConnection(); + return subscriptionDAO.getOperationAppDetails(operationId, tenantId); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while retrieving app details of operation: " + operationId; + log.error(msg, e); + throw new SubscriptionManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while retrieving the database connection"; + log.error(msg, e); + throw new SubscriptionManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + } 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 99b56d9fbe..23076328e4 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 @@ -308,7 +308,17 @@ public interface ActivityInfoProviderService { "Provide the value in the Java Date Format: EEE, d MMM yyyy HH:mm:ss Z\n." + "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince); + @HeaderParam("If-Modified-Since") String ifModifiedSince, + @ApiParam( + name = "response", + value = "The starting pagination index for the complete list of qualified items.", + required = false) + @QueryParam("response") Boolean response, + @ApiParam( + name = "appInstall", + value = "The starting pagination index for the complete list of qualified items.", + required = false) + @QueryParam("appInstall") Boolean appInstall); @GET @Path("/type/{operationCode}") 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 db2a8eab31..d4860d3dc3 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 @@ -18,6 +18,8 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import com.google.gson.Gson; +import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; +import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.ActivityPaginationRequest; @@ -146,8 +148,11 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService @Size(max = 45) String devicetype, @PathParam("deviceid") @Size(max = 45) String deviceid, - @HeaderParam("If-Modified-Since") String ifModifiedSince) { - Activity activity; + @HeaderParam("If-Modified-Since") String ifModifiedSince, + @QueryParam("response") Boolean response, + @QueryParam("appInstall") Boolean appInstall) { + Activity activity = new Activity(); + Activity appActivity = null; DeviceManagementProviderService dmService; try { RequestValidationUtil.validateActivityId(id); @@ -157,7 +162,20 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService deviceIdentifier.setType(devicetype); dmService = DeviceMgtAPIUtils.getDeviceManagementService(); - activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier); + + if (appInstall != null && appInstall) { + if (response != null && response) { + activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier); + } + SubscriptionManager subscriptionManager = DeviceMgtAPIUtils.getSubscriptionManager(); + appActivity = subscriptionManager.getOperationAppDetails(id); + activity.setUsername(appActivity.getUsername()); + activity.setPackageName(appActivity.getPackageName()); + activity.setAppName(appActivity.getAppName()); + activity.setStatus(appActivity.getStatus()); + } else { + activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier); + } if (activity == null) { String msg = "No activity can be " + "found upon the provided activity id '" + id + "'"; @@ -169,6 +187,11 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (SubscriptionManagementException e) { + String msg = "ErrorResponse occurred while fetching the app details for the supplied id."; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/test/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/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 f56c673495..0e3d23d705 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 @@ -206,7 +206,7 @@ public class ActivityProviderServiceImplTest { Mockito.when(this.deviceManagementProviderService .getOperationByActivityIdAndDevice(TEST_ACTIVITY_ID, deviceIdentifier)).thenReturn(activity); Response response = this.activityInfoProviderService.getActivityByDevice(TEST_ACTIVITY_ID, - DEVICE_TYPE, DEVICE_ID, IF_MODIFIED_SINCE); + DEVICE_TYPE, DEVICE_ID, IF_MODIFIED_SINCE, false, false); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Mockito.reset(this.deviceManagementProviderService); 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/operation/mgt/Activity.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java index 5a04185e0a..e9874778d9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java @@ -80,6 +80,20 @@ public class Activity { @JsonProperty("initiatedBy") private String initiatedBy; + @ApiModelProperty(name = "appName", value = "App Name.") + private String appName; + + @ApiModelProperty(name = "packageName", + value = "package name of the application") + private String packageName; + @ApiModelProperty(name = "username", + value = "username of subscribed person") + private String username; + @ApiModelProperty(name = "status", + value = "Status of app install") + private String status; + + public String getActivityId() { return activityId; } @@ -127,5 +141,37 @@ public class Activity { public void setInitiatedBy(String initiatedBy) { this.initiatedBy = initiatedBy; } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } } From e2a467bc455c7b960a7f244bdffc0529b9628d1d Mon Sep 17 00:00:00 2001 From: osh Date: Wed, 9 Aug 2023 15:03:29 +0530 Subject: [PATCH 22/36] Update activity loading --- .../GenericSubscriptionDAOImpl.java | 18 ++++--------- .../application/mgt/core/util/DAOUtil.java | 27 +++++++++++++++++++ .../impl/ActivityProviderServiceImpl.java | 14 +++++++--- 3 files changed, 42 insertions(+), 17 deletions(-) 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 373ade8595..429ecc1e35 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 @@ -1438,7 +1438,6 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc } public Activity getOperationAppDetails(int operationId, int tenantId) throws ApplicationManagementDAOException { - Activity activity = null; try { String sql = "SELECT " + "AP.NAME, " @@ -1456,18 +1455,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc stmt.setInt(1, operationId); stmt.setInt(2,tenantId); try (ResultSet rs = stmt.executeQuery()) { - if (log.isDebugEnabled()) { - log.debug("Successfully retrieved app details for operation " - + operationId); - } - while (rs.next()) { - activity = new Activity(); - activity.setAppName(rs.getString("NAME")); - activity.setUsername(rs.getString("SUBSCRIBED_BY")); - activity.setPackageName(rs.getString("PACKAGE_NAME")); - activity.setStatus(rs.getString("STATUS")); - } - return activity; + return DAOUtil.loadOperationActivity(rs); } } } catch (DBConnectionException e) { @@ -1479,6 +1467,10 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc String msg = "Error occurred when processing SQL to retrieve app details of operation" + operationId; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "More than one app for operation " + operationId; + 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/util/DAOUtil.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/DAOUtil.java index 08ebe3b60d..ede8d7ff6d 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/DAOUtil.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/DAOUtil.java @@ -21,6 +21,7 @@ import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import io.entgra.device.mgt.core.application.mgt.common.dto.*; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; @@ -361,6 +362,32 @@ public class DAOUtil { return subscriptionDTOS; } + public static Activity loadOperationActivity(ResultSet rs) throws SQLException, UnexpectedServerErrorException { + List activity = loadOperationActivities(rs); + if (activity.isEmpty()) { + return null; + } + if (activity.size() > 1) { + String msg = "Internal server error. Found more than one app for operation"; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return activity.get(0); + } + + public static List loadOperationActivities (ResultSet rs) throws SQLException { + List activities = new ArrayList<>(); + while (rs.next()) { + Activity activity = new Activity(); + activity.setAppName(rs.getString("NAME")); + activity.setUsername(rs.getString("SUBSCRIBED_BY")); + activity.setPackageName(rs.getString("PACKAGE_NAME")); + activity.setStatus(rs.getString("STATUS")); + activities.add(activity); + } + return activities; + } + public static VppUserDTO loadVppUser(ResultSet rs) throws SQLException, UnexpectedServerErrorException { List vppUserDTOS = loadVppUsers(rs); if (vppUserDTOS.isEmpty()) { 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 d4860d3dc3..60272d589f 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 @@ -169,10 +169,16 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService } SubscriptionManager subscriptionManager = DeviceMgtAPIUtils.getSubscriptionManager(); appActivity = subscriptionManager.getOperationAppDetails(id); - activity.setUsername(appActivity.getUsername()); - activity.setPackageName(appActivity.getPackageName()); - activity.setAppName(appActivity.getAppName()); - activity.setStatus(appActivity.getStatus()); + if (appActivity != null) { + activity.setUsername(appActivity.getUsername()); + activity.setPackageName(appActivity.getPackageName()); + activity.setAppName(appActivity.getAppName()); + activity.setStatus(appActivity.getStatus()); + } else { + String msg = "Cannot find the app details related to the operation "; + log.error(msg); + Response.status(404).entity(msg).build(); + } } else { activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier); } From 81e57ce78fd26d3fc83ec755c1850cb176353cd4 Mon Sep 17 00:00:00 2001 From: osh Date: Thu, 10 Aug 2023 13:01:41 +0530 Subject: [PATCH 23/36] Retrieve extra details --- .../GenericSubscriptionDAOImpl.java | 5 ++- .../application/mgt/core/util/DAOUtil.java | 3 ++ .../impl/ActivityProviderServiceImpl.java | 3 ++ .../mgt/common/operation/mgt/Activity.java | 36 +++++++++++++++++++ 4 files changed, 46 insertions(+), 1 deletion(-) 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 429ecc1e35..457de13bee 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 @@ -1441,9 +1441,12 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc try { String sql = "SELECT " + "AP.NAME, " + + "AP.TYPE, " + "AR.PACKAGE_NAME, " + + "AR.VERSION, " + "DS.SUBSCRIBED_BY, " - + "DS.STATUS " + + "DS.STATUS, " + + "DS.ACTION_TRIGGERED_FROM " + "FROM AP_APP_SUB_OP_MAPPING SOP " + "JOIN AP_DEVICE_SUBSCRIPTION DS ON SOP.AP_DEVICE_SUBSCRIPTION_ID = DS.ID " + "JOIN AP_APP_RELEASE AR ON DS.AP_APP_RELEASE_ID = AR.ID " 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/DAOUtil.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/DAOUtil.java index ede8d7ff6d..a41f48e1e9 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/DAOUtil.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/DAOUtil.java @@ -380,9 +380,12 @@ public class DAOUtil { while (rs.next()) { Activity activity = new Activity(); activity.setAppName(rs.getString("NAME")); + activity.setAppType(rs.getString("TYPE")); activity.setUsername(rs.getString("SUBSCRIBED_BY")); activity.setPackageName(rs.getString("PACKAGE_NAME")); activity.setStatus(rs.getString("STATUS")); + activity.setVersion(rs.getString("VERSION")); + activity.setTriggeredBy(rs.getString("ACTION_TRIGGERED_FROM")); activities.add(activity); } return activities; 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 60272d589f..d9fec4b91b 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 @@ -174,6 +174,9 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService activity.setPackageName(appActivity.getPackageName()); activity.setAppName(appActivity.getAppName()); activity.setStatus(appActivity.getStatus()); + activity.setAppType(appActivity.getAppType()); + activity.setVersion(appActivity.getVersion()); + activity.setTriggeredBy(appActivity.getTriggeredBy()); } else { String msg = "Cannot find the app details related to the operation "; log.error(msg); 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/operation/mgt/Activity.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java index e9874778d9..e001d72929 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/operation/mgt/Activity.java @@ -93,6 +93,18 @@ public class Activity { value = "Status of app install") private String status; + @ApiModelProperty(name = "version", + value = "Version of app") + private String version; + + @ApiModelProperty(name = "triggeredBy", + value = "Operation triggered by what") + private String triggeredBy; + + @ApiModelProperty(name = "appType", + value = "Type of application") + private String appType; + public String getActivityId() { return activityId; @@ -173,5 +185,29 @@ public class Activity { public void setStatus(String status) { this.status = status; } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getTriggeredBy() { + return triggeredBy; + } + + public void setTriggeredBy(String triggeredBy) { + this.triggeredBy = triggeredBy; + } + + public String getAppType() { + return appType; + } + + public void setAppType(String appType) { + this.appType = appType; + } } From 74d4e2dded9aee97ef5179a3320f30a26cd57d0b Mon Sep 17 00:00:00 2001 From: osh Date: Thu, 10 Aug 2023 13:12:19 +0530 Subject: [PATCH 24/36] Add vpp scopes --- .../src/main/resources/conf/mdm-ui-config.xml | 4 ++++ 1 file changed, 4 insertions(+) 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 4e7b97fc6e..30c9e55f57 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 @@ -241,6 +241,10 @@ perm:ios:app-configurations perm:mac-os:restart perm:mac-os:shut-down + perm:app:vpp:user:modify + perm:app:vpp:user:view + perm:app:vpp:asset:modify + perm:app:vpp:asset:view device-mgt From 67864cb76212aca213ee7e22a721395175a25b7f Mon Sep 17 00:00:00 2001 From: shamalka Date: Tue, 15 Aug 2023 12:48:58 +0530 Subject: [PATCH 25/36] Add deviceinfo config beans --- .../config/ui/DeviceInfoConfigurations.java | 36 ++++++++++ .../mgt/core/config/ui/DeviceInfoItem.java | 56 +++++++++++++++ .../mgt/core/config/ui/UIConfiguration.java | 11 +++ .../src/main/resources/conf/mdm-ui-config.xml | 70 +++++++++++++++++++ 4 files changed, 173 insertions(+) create mode 100644 components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoConfigurations.java create mode 100644 components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoItem.java 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/config/ui/DeviceInfoConfigurations.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoConfigurations.java new file mode 100644 index 0000000000..0e37753018 --- /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/config/ui/DeviceInfoConfigurations.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.device.mgt.core.device.mgt.core.config.ui; + +import javax.xml.bind.annotation.XmlElement; +import java.util.List; + +class DeviceInfoConfigurations { + + private List deviceInfoItems; + + @XmlElement(name = "DeviceInfoItem") + public List getDeviceInfoItems() { + return deviceInfoItems; + } + + public void setDeviceInfoItems(List deviceInfoItems) { + this.deviceInfoItems = deviceInfoItems; + } +} 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/config/ui/DeviceInfoItem.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/DeviceInfoItem.java new file mode 100644 index 0000000000..0f02669a49 --- /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/config/ui/DeviceInfoItem.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.device.mgt.core.device.mgt.core.config.ui; + +import javax.xml.bind.annotation.XmlElement; + +class DeviceInfoItem { + + private String definedValue; + private String displayValue; + + private String type; + + @XmlElement(name = "DefinedValue") + public String getDefinedValue() { + return definedValue; + } + + public void setDefinedValue(String definedValue) { + this.definedValue = definedValue; + } + + @XmlElement(name = "DisplayValue") + public String getDisplayValue() { + return displayValue; + } + + public void setDisplayValue(String displayValue) { + this.displayValue = displayValue; + } + + @XmlElement(name = "Type") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} 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/config/ui/UIConfiguration.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java index 844c4039d2..6e71d17072 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java @@ -36,6 +36,8 @@ public class UIConfiguration { private Billing billing; private HubspotChat hubspotChat; + private DeviceInfoConfigurations deviceInfoConfigurations; + @XmlElement(name = "AppRegistration", required=true) public AppRegistration getAppRegistration() { return appRegistration; @@ -98,4 +100,13 @@ public class UIConfiguration { public void setLoginCacheCapacity(int loginCacheCapacity) { this.loginCacheCapacity = loginCacheCapacity; } + + @XmlElement(name = "DeviceInfoConfigurations", required = true) + public DeviceInfoConfigurations getDeviceInfoConfigurations() { + return deviceInfoConfigurations; + } + + public void setDeviceInfoConfigurations(DeviceInfoConfigurations deviceInfoConfigurations) { + this.deviceInfoConfigurations = deviceInfoConfigurations; + } } 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 30c9e55f57..d289c60da6 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 @@ -40,6 +40,76 @@ false true + + + FIRMWARE_VERSION + Firmware version + + + FIRMWARE_APP_VERSION + App version + + + name + Device + default + + + type + Type + default + + + owner + Owner + default + + + serial + Serial Number + default + + + ownership + Ownership + default + + + status + Status + default + + + dateOfLastUpdate + Last Updated + default + + + actions + Actions + default + + + batteryLevel + Battery Level + deviceInfo + + + deviceModel + Device Model + deviceInfo + + + osVersion + OS Version + deviceInfo + + + vendor + Vendor + deviceInfo + + analytics_management From d8691596257f3fd9cfb8ba50eeb28761d1a03406 Mon Sep 17 00:00:00 2001 From: shamalka Date: Tue, 15 Aug 2023 15:17:27 +0530 Subject: [PATCH 26/36] Add missing type params to device info xml --- .../src/main/resources/conf/mdm-ui-config.xml | 2 ++ 1 file changed, 2 insertions(+) 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 d289c60da6..4407fbd5e4 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 @@ -44,10 +44,12 @@ FIRMWARE_VERSION Firmware version + deviceInfo FIRMWARE_APP_VERSION App version + deviceInfo name From f9ae594326b165ade7c45cf69014d2290665200e Mon Sep 17 00:00:00 2001 From: tcdlpds Date: Wed, 16 Aug 2023 08:34:28 +0530 Subject: [PATCH 27/36] Fix APPs getting issue in APPM DAO --- .../mgt/core/device/mgt/core/dao/impl/ApplicationDAOImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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/ApplicationDAOImpl.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/ApplicationDAOImpl.java index 8aa49c92e0..4f46d5b4f6 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/ApplicationDAOImpl.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/ApplicationDAOImpl.java @@ -293,11 +293,11 @@ public class ApplicationDAOImpl implements ApplicationDAO { "WHERE A.NAME = DM_APPLICATION.NAME " + "AND A.ID < DM_APPLICATION.ID) " + "AND PLATFORM = ? " + - "AND TENANT_ID = ?"; + "AND TENANT_ID = ? "; try { String filter = request.getFilter(); if (filter != null) { - sql = sql + "AND NAME LIKE ?"; + sql = sql + "AND NAME LIKE ? "; } sql = sql + "LIMIT ? OFFSET ?"; Connection conn = this.getConnection(); From 4ab0c77e8e484647af8aa0c893261720c35a44b9 Mon Sep 17 00:00:00 2001 From: shamalka Date: Thu, 17 Aug 2023 01:20:40 +0530 Subject: [PATCH 28/36] Add i8n support --- .../src/main/resources/conf/mdm-ui-config.xml | 88 ++++++++++++++++--- 1 file changed, 74 insertions(+), 14 deletions(-) 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 4407fbd5e4..f60b9cca6a 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 @@ -43,72 +43,132 @@ FIRMWARE_VERSION - Firmware version + label_firmware_version deviceInfo FIRMWARE_APP_VERSION - App version + label_app_version deviceInfo name - Device + label_device default type - Type + label_type default owner - Owner + label_owner default serial - Serial Number + label_serialNumber default ownership - Ownership + label_ownership default status - Status + label_status default dateOfLastUpdate - Last Updated + label_last_updated default actions - Actions + label_actions default batteryLevel - Battery Level + label_battery_leve deviceInfo deviceModel - Device Model + label_deviceModel deviceInfo osVersion - OS Version + label_os_version deviceInfo vendor - Vendor + label_vendor + deviceInfo + + + availableRAMMemory + label_available_ram_memory + deviceInfo + + + connectionType + label_connection_type + deviceInfo + + + cpuUsage + label_cpu_usage + deviceInfo + + + externalAvailableMemory + label_external_available_memory + deviceInfo + + + externalTotalMemory + label_external_tot_memory + deviceInfo + + + internalAvailableMemory + label_internal_available_memory + deviceInfo + + + internalTotalMemory + label_internal_tot_memory + deviceInfo + + + osBuildDate + label_os_build_date + deviceInfo + + + pluggedIn + label_plugged_in + deviceInfo + + + ssid + label_ssid + deviceInfo + + + totalRAMMemory + label_tot_ram_memory + deviceInfo + + + updatedTime + label_updated_time deviceInfo From 6d6d3f4f406397b8f2bc89156b72348dae48507d Mon Sep 17 00:00:00 2001 From: shamalka Date: Fri, 18 Aug 2023 10:28:04 +0530 Subject: [PATCH 29/36] Add firmware system version column --- .../src/main/resources/conf/mdm-ui-config.xml | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) 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 f60b9cca6a..a5dad642b7 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 @@ -41,16 +41,6 @@ true - - FIRMWARE_VERSION - label_firmware_version - deviceInfo - - - FIRMWARE_APP_VERSION - label_app_version - deviceInfo - name label_device @@ -91,6 +81,21 @@ label_actions default + + FIRMWARE_VERSION + label_firmware_version + deviceDetailsMap + + + FIRMWARE_APP_VERSION + label_app_version + deviceDetailsMap + + + FIRMWARE_SYSTEM_VERSION + label_firmware_system_version + deviceDetailsMap + batteryLevel label_battery_leve From 388f34e3b8afd2945245eddbff5c3f78a97bc57a Mon Sep 17 00:00:00 2001 From: pramilaniroshan Date: Mon, 21 Aug 2023 12:44:42 +0530 Subject: [PATCH 30/36] Fix try-it meta-info getting issue --- .../mgt/core/otp/mgt/service/OTPManagementServiceImpl.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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/otp/mgt/service/OTPManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java index d8872be921..bc9204eecb 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java @@ -276,9 +276,7 @@ public class OTPManagementServiceImpl implements OTPManagementService { public OneTimePinDTO generateOneTimePin(OneTimePinDTO oneTimePinDTO, boolean persistPin) throws OTPManagementException { String otpValue = UUID.randomUUID().toString(); - - Gson gson = new Gson(); - String metaInfo = gson.toJson(oneTimePinDTO.getMetaInfo()); + String metaInfo = oneTimePinDTO.getMetaInfo(); oneTimePinDTO.setMetaInfo(metaInfo); oneTimePinDTO.setOtpToken(otpValue); From 1fed47e8fd694445a505cc7abfccc026aa71cd4c Mon Sep 17 00:00:00 2001 From: osh Date: Mon, 21 Aug 2023 23:27:58 +0530 Subject: [PATCH 31/36] Add app details for UNMANAGED_APP_UNINSTALL --- .../beans/ApplicationUninstallation.java | 49 +++++++++++++++++++ .../service/api/DeviceManagementService.java | 26 +++++++++- .../impl/DeviceManagementServiceImpl.java | 8 ++- .../mgt/dao/impl/GenericOperationDAOImpl.java | 34 +++++++++++++ 4 files changed, 114 insertions(+), 3 deletions(-) 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/ApplicationUninstallation.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/ApplicationUninstallation.java index a38ae2982d..f78d15966e 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/ApplicationUninstallation.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/ApplicationUninstallation.java @@ -41,6 +41,14 @@ public class ApplicationUninstallation { @Pattern(regexp = "^[A-Za-z]*$") String type; + String name; + + String platform; + + String version; + + String user; + public ApplicationUninstallation() { } @@ -49,6 +57,47 @@ public class ApplicationUninstallation { this.type = type; } + public ApplicationUninstallation(String appIdentifier, String type, String name, String platform, String version, String user) { + this.appIdentifier = appIdentifier; + this.type = type; + this.name = name; + this.platform = platform; + this.version = version; + this.user = user; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPlatform() { + return platform; + } + + public void setPlatform(String platform) { + this.platform = platform; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + public String getAppIdentifier() { return appIdentifier; } 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/DeviceManagementService.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/DeviceManagementService.java index 53f7fd9360..bb5349da68 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/DeviceManagementService.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/DeviceManagementService.java @@ -1657,7 +1657,31 @@ public interface DeviceManagementService { value = "The package name of the app user want to uninstall", required = true) @QueryParam("packageName") - String packageName); + String packageName, + @ApiParam( + name = "platform", + value = "The platform of the app user want to uninstall", + required = false) + @QueryParam("platform") + String platform, + @ApiParam( + name = "name", + value = "The name of the app user want to uninstall", + required = false) + @QueryParam("name") + String name, + @ApiParam( + name = "version", + value = "The version of the app user want to uninstall", + required = false) + @QueryParam("version") + String version, + @ApiParam( + name = "user", + value = "The user who triggered the app uninstall", + required = false) + @QueryParam("user") + String user); @GET @Produces(MediaType.APPLICATION_JSON) 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 b5851dff0c..2eaa0a5595 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 @@ -981,7 +981,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { public Response uninstallation( @PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id, - @QueryParam("packageName") String packageName) { + @QueryParam("packageName") String packageName, + @QueryParam("platform") String platform, + @QueryParam("name") String name, + @QueryParam("version") String version, + @QueryParam("user") String user) { List deviceIdentifiers = new ArrayList<>(); Operation operation = new Operation(); try { @@ -1004,7 +1008,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { //if the applications not installed via entgra store } else { if (Constants.ANDROID.equals(type)) { - ApplicationUninstallation applicationUninstallation = new ApplicationUninstallation(packageName, "PUBLIC"); + ApplicationUninstallation applicationUninstallation = new ApplicationUninstallation(packageName, "PUBLIC", name, platform, version, user); Gson gson = new Gson(); operation.setCode(MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL); operation.setType(Operation.Type.PROFILE); 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 046556459a..7411f93c5a 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 @@ -17,6 +17,8 @@ */ package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; +import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ProfileOperation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -41,6 +43,8 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util.Operatio import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; +import java.io.ObjectInputStream; +import java.io.ByteArrayInputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -1353,6 +1357,9 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList<>(); String createdTo = null; String createdFrom = null; + ByteArrayInputStream bais; + ObjectInputStream ois; + ProfileOperation profileOperation = null; DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); boolean isCreatedDayProvided = false; boolean isUpdatedDayProvided = false; //updated day = received day @@ -1375,6 +1382,7 @@ public class GenericOperationDAOImpl implements OperationDAO { "o.RECEIVED_TIMESTAMP, " + "o.OPERATION_CODE, " + "o.INITIATED_BY, " + + "o.OPERATION_DETAILS, " + "om.STATUS, " + "om.ID AS OM_MAPPING_ID, " + "om.UPDATED_TIMESTAMP " + @@ -1473,10 +1481,21 @@ public class GenericOperationDAOImpl implements OperationDAO { } 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"); + bais = new ByteArrayInputStream(operationDetails); + ois = new ObjectInputStream(bais); + profileOperation = (ProfileOperation) ois.readObject(); + operation.setPayLoad(profileOperation.getPayLoad()); + } operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); operations.add(operation); } + } catch (IOException e) { + throw new OperationManagementDAOException("IO Error occurred while retrieving app data of operation ", e); + } catch (ClassNotFoundException e) { + throw new OperationManagementDAOException("Class not found error occurred while retrieving app data of operation ", e); } } } catch (SQLException e) { @@ -1493,6 +1512,9 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList<>(); String createdTo = null; String createdFrom = null; + ByteArrayInputStream bais; + ObjectInputStream ois; + ProfileOperation profileOperation = null; DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); boolean isCreatedDayProvided = false; boolean isUpdatedDayProvided = false; //updated day = received day @@ -1515,6 +1537,7 @@ public class GenericOperationDAOImpl implements OperationDAO { "o.RECEIVED_TIMESTAMP, " + "o.OPERATION_CODE, " + "o.INITIATED_BY, " + + "o.OPERATION_DETAILS, " + "om.STATUS, " + "om.ID AS OM_MAPPING_ID, " + "om.UPDATED_TIMESTAMP " + @@ -1613,10 +1636,21 @@ public class GenericOperationDAOImpl implements OperationDAO { } 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"); + bais = new ByteArrayInputStream(operationDetails); + ois = new ObjectInputStream(bais); + profileOperation = (ProfileOperation) ois.readObject(); + operation.setPayLoad(profileOperation.getPayLoad()); + } operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); OperationDAOUtil.setActivityId(operation, rs.getInt("ID")); operations.add(operation); } + } catch (IOException e) { + throw new OperationManagementDAOException("IO Error occurred while retrieving app data of operation " , e); + } catch (ClassNotFoundException e) { + throw new OperationManagementDAOException("Class not found error occurred while retrieving app data of operation ", e); } } } catch (SQLException e) { From 127b554ef7456aad526647eec8f2cc1a83e8153b Mon Sep 17 00:00:00 2001 From: rajitha Date: Tue, 22 Aug 2023 08:20:59 +0530 Subject: [PATCH 32/36] Remove not null constraints from metainfo field --- .../src/main/resources/dbscripts/cdm/h2.sql | 2 +- .../src/main/resources/dbscripts/cdm/mssql.sql | 2 +- .../src/main/resources/dbscripts/cdm/mysql.sql | 2 +- .../src/main/resources/dbscripts/cdm/oracle.sql | 2 +- .../src/main/resources/dbscripts/cdm/postgresql.sql | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) 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 b3bc1c36ea..a0be9fd704 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 @@ -608,7 +608,7 @@ CREATE TABLE IF NOT EXISTS DM_OTP_DATA ( USERNAME VARCHAR(500) DEFAULT NOT NULL, EMAIL VARCHAR(100) NOT NULL, EMAIL_TYPE VARCHAR(20) NOT NULL, - META_INFO VARCHAR(20000) NOT NULL, + META_INFO VARCHAR(20000) NULL, CREATED_AT TIMESTAMP NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, IS_EXPIRED BOOLEAN DEFAULT false, 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 34ff7ef1a7..16af46d997 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 @@ -669,7 +669,7 @@ CREATE TABLE DM_OTP_DATA ( USERNAME VARCHAR(500) NOT NULL, EMAIL VARCHAR(100) NOT NULL, EMAIL_TYPE VARCHAR(20) NOT NULL, - META_INFO VARCHAR(8000) NOT NULL, + META_INFO VARCHAR(8000) NULL, CREATED_AT DATETIME2(0) NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, IS_EXPIRED BIT DEFAULT 0, 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 e55274e49f..d184237d44 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 @@ -665,7 +665,7 @@ CREATE TABLE IF NOT EXISTS DM_OTP_DATA ( USERNAME VARCHAR(500) NOT NULL, EMAIL VARCHAR(100) NOT NULL, EMAIL_TYPE VARCHAR(20) NOT NULL, - META_INFO VARCHAR(20000) NOT NULL, + META_INFO VARCHAR(20000) NULL, CREATED_AT TIMESTAMP NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, IS_EXPIRED BOOLEAN DEFAULT false, 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 708f135b78..60c7aaf89e 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 @@ -1026,7 +1026,7 @@ CREATE TABLE DM_OTP_DATA ( USERNAME VARCHAR(500) NOT NULL, EMAIL VARCHAR2(100) NOT NULL, EMAIL_TYPE VARCHAR2(20) NOT NULL, - META_INFO VARCHAR2(20000) NOT NULL, + META_INFO VARCHAR2(20000) NULL, CREATED_AT TIMESTAMP(0) NOT NULL, EXPIRY_TIME NUMBER(10) DEFAULT 3600 NOT NULL, IS_EXPIRED CHAR(1) DEFAULT false, 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 3ff77c0242..f9f6879338 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 @@ -672,7 +672,7 @@ CREATE TABLE IF NOT EXISTS DM_OTP_DATA ( USERNAME VARCHAR(500) NOT NULL, EMAIL VARCHAR(100) NOT NULL, EMAIL_TYPE VARCHAR(20) NOT NULL, - META_INFO VARCHAR(20000) NOT NULL, + META_INFO VARCHAR(20000) NULL, CREATED_AT TIMESTAMP(0) NOT NULL, EXPIRY_TIME INT NOT NULL DEFAULT 3600, IS_EXPIRED BOOLEAN DEFAULT false, From 195bb64beafe347c6280d8715f074b4f29291949 Mon Sep 17 00:00:00 2001 From: osh Date: Wed, 23 Aug 2023 12:42:57 +0530 Subject: [PATCH 33/36] Resolve comments --- .../mgt/dao/impl/GenericOperationDAOImpl.java | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) 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 7411f93c5a..164e50a8ec 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 @@ -1357,8 +1357,6 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList<>(); String createdTo = null; String createdFrom = null; - ByteArrayInputStream bais; - ObjectInputStream ois; ProfileOperation profileOperation = null; DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); boolean isCreatedDayProvided = false; @@ -1483,19 +1481,24 @@ public class GenericOperationDAOImpl implements OperationDAO { operation.setInitiatedBy(rs.getString("INITIATED_BY")); if (MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL.equals(operation.getCode())) { byte[] operationDetails = rs.getBytes("OPERATION_DETAILS"); - bais = new ByteArrayInputStream(operationDetails); - ois = new ObjectInputStream(bais); - profileOperation = (ProfileOperation) ois.readObject(); - operation.setPayLoad(profileOperation.getPayLoad()); + 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); } - } catch (IOException e) { - throw new OperationManagementDAOException("IO Error occurred while retrieving app data of operation ", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Class not found error occurred while retrieving app data of operation ", e); } } } catch (SQLException e) { @@ -1512,8 +1515,6 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList<>(); String createdTo = null; String createdFrom = null; - ByteArrayInputStream bais; - ObjectInputStream ois; ProfileOperation profileOperation = null; DateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); boolean isCreatedDayProvided = false; @@ -1638,19 +1639,24 @@ public class GenericOperationDAOImpl implements OperationDAO { operation.setInitiatedBy(rs.getString("INITIATED_BY")); if (MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL.equals(operation.getCode())) { byte[] operationDetails = rs.getBytes("OPERATION_DETAILS"); - bais = new ByteArrayInputStream(operationDetails); - ois = new ObjectInputStream(bais); - profileOperation = (ProfileOperation) ois.readObject(); - operation.setPayLoad(profileOperation.getPayLoad()); + 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); } - } catch (IOException e) { - throw new OperationManagementDAOException("IO Error occurred while retrieving app data of operation " , e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Class not found error occurred while retrieving app data of operation ", e); } } } catch (SQLException e) { From 70c27b647b2940dff5dac6a98ac529c320d73f92 Mon Sep 17 00:00:00 2001 From: Thameera Date: Wed, 23 Aug 2023 13:47:30 +0530 Subject: [PATCH 34/36] Operation Template releated changes --- .../io.entgra.device.mgt.core.operation.template/pom.xml | 5 ++++- .../internal/OperationTemplateMgtServiceComponent.java | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) 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 9edcd52f95..78e8220884 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 @@ -79,7 +79,8 @@ io.entgra.device.mgt.core.device.mgt.extensions.license.mgt.registry, javax.net.ssl, org.wso2.carbon.core.util, - okhttp3 + okhttp3, + com.google.common.cache.* !io.entgra.device.mgt.core.operation.template.internal, @@ -300,6 +301,8 @@ com.google.guava guava + ${guava.version} + provided io.github.openfeign diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtServiceComponent.java b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtServiceComponent.java index 1bff30c260..0eae3ad301 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtServiceComponent.java +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/main/java/io/entgra/device/mgt/core/operation/template/internal/OperationTemplateMgtServiceComponent.java @@ -31,7 +31,7 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.ndatasource.core.DataSourceService; /** - * @scr.component name="io.entgra.device.mgt.operation.template.internal.OperationTemplateMgtServiceComponent" immediate="true" + * @scr.component name="io.entgra.device.mgt.core.operation.template.internal.OperationTemplateMgtServiceComponent" immediate="true" * immediate="true" * @scr.reference name="org.wso2.carbon.ndatasource" * interface="org.wso2.carbon.ndatasource.core.DataSourceService" From 017c70fa084676003dd086ea2f7c75430528b3eb Mon Sep 17 00:00:00 2001 From: nishan Date: Fri, 14 Jul 2023 00:08:27 +0530 Subject: [PATCH 35/36] Fix Certificate test case and delete and search option --- .../CertificateManagementAdminService.java | 41 ++++-- ...CertificateManagementAdminServiceImpl.java | 64 ++++++--- .../admin/api/util/RequestValidationUtil.java | 8 -- .../pom.xml | 7 +- .../mgt/core/dao/CertificateDAO.java | 11 +- .../dao/impl/AbstractCertificateDAOImpl.java | 12 +- .../dao/impl/GenericCertificateDAOImpl.java | 122 ++++++++++++++---- .../dao/impl/OracleCertificateDAOImpl.java | 117 +++++++++++++---- .../impl/PostgreSQLCertificateDAOImpl.java | 118 +++++++++++++---- .../dao/impl/SQLServerCertificateDAOImpl.java | 118 +++++++++++++---- .../service/CertificateManagementService.java | 7 +- .../CertificateManagementServiceImpl.java | 54 ++++++-- .../util/CertificateManagementConstants.java | 6 + .../mgt/core/util/CertificateManagerUtil.java | 25 ++++ ...ateManagementServiceImplNegativeTests.java | 7 +- ...CertificateManagementServiceImplTests.java | 4 +- .../src/test/resources/sql/h2.sql | 1 + .../common/CertificatePaginationRequest.java | 77 +++++++++++ 18 files changed, 643 insertions(+), 156 deletions(-) create mode 100644 components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/CertificatePaginationRequest.java diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java index 18207be106..cd2be07ac9 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java @@ -247,14 +247,15 @@ public interface CertificateManagementAdminService { * * @return paginated result of certificate. */ + @GET @ApiOperation( consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, httpMethod = "GET", - value = "Getting Details of Certificates", - notes = "Get all the details of the certificates you have used for mutual SSL. In a situation where you wish to " - + "view all the certificate details, it is not feasible to show all the details on one " + value = "Getting Details of search Certificates", + notes = "Get all the details of the search certificates you have used for mutual SSL. In a situation where you wish to " + + "view all the search certificate details, it is not feasible to show all the details on one " + "page. Therefore, the details are paginated.", tags = "Certificate Management", extensions = { @@ -308,24 +309,42 @@ public interface CertificateManagementAdminService { }) Response getAllCertificates( @ApiParam( - name = "offset", - value = "The starting pagination index for the complete list of qualified items.", + name = "serialNumber", + value = "The serial number of the certificates", required = false, defaultValue = "0") - @QueryParam("offset") int offset, + @QueryParam("serialNumber") String serialNumber, @ApiParam( - name = "limit", - value = "Provide how many certificate details you require from the starting pagination index/offset.", + name = "deviceIdentifier", + value = "The device identifier of the certificates", required = false, - defaultValue = "5") - @QueryParam("limit") int limit, + defaultValue = "0") + @QueryParam("deviceIdentifier") String deviceIdentifier, + @ApiParam( + name = "username", + value = "User name of the certificate added user" , + required = false, + defaultValue = "0") + @QueryParam("username") String username, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time. \n" + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince); + @HeaderParam("If-Modified-Since") String ifModifiedSince, + @ApiParam( + name = "offset", + value = "The starting pagination index for the complete list of qualified items.", + required = false, + defaultValue = "0") + @QueryParam("offset") int offset, + @ApiParam( + name = "limit", + value = "Provide how many certificate details you require from the starting pagination index/offset.", + required = false, + defaultValue = "5") + @QueryParam("limit") int limit); @DELETE @ApiOperation( diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java index c64df487be..3f124a8946 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.impl; -import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; @@ -26,7 +25,8 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; + +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.CertificateManagementAdminService; @@ -84,6 +84,13 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); certificate.setSerial(enrollmentCertificate.getSerial()); certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem())); + CertificateResponse existingCertificate = certificateService.getCertificateBySerial(enrollmentCertificate.getSerial()); + if (existingCertificate != null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity("Certificate with serial number " + enrollmentCertificate.getSerial() + " already exists.") + .build(); + } + certificates.add(certificate); } certificateService.saveCertificate(certificates); @@ -131,13 +138,24 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem */ @GET public Response getAllCertificates( - @QueryParam("offset") int offset, - @QueryParam("limit") int limit, - @HeaderParam("If-Modified-Since") String ifModifiedSince) { + @QueryParam("serialNumber") String serialNumber, @QueryParam("deviceIdentifier") String deviceIdentifier, + @QueryParam("username") String username, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, + @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationInfo(offset, limit); CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); + CertificatePaginationRequest request = new CertificatePaginationRequest(offset, limit); + + if (serialNumber != null && !serialNumber.isEmpty()) { + request.setSerialNumber(serialNumber); + } + if (deviceIdentifier != null){ + request.setDeviceIdentifier(deviceIdentifier); + } + if (username != null){ + request.setUsername(username); + } try { - PaginationResult result = certificateService.getAllCertificates(offset, limit); + PaginationResult result = certificateService.getAllCertificates(request); CertificateList certificates = new CertificateList(); certificates.setCount(result.getRecordsTotal()); certificates.setList((List) result.getData()); @@ -151,20 +169,34 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem } @DELETE - public Response removeCertificate(@QueryParam("certificateId") String certificateId) { - RequestValidationUtil.validateCertificateId(certificateId); + public Response removeCertificate(@QueryParam("serialNumber") String serialNumber) { + RequestValidationUtil.validateSerialNumber(serialNumber); CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); try { - boolean status = certificateService.removeCertificate(certificateId); - if (!status) { - return Response.status(Response.Status.NOT_FOUND).entity( - "No certificate is found with the given " + - "certificate id '" + certificateId + "'").build(); + boolean decision = certificateService.getValidateMetaValue(); + if (decision) { + try { + boolean status = certificateService.removeCertificate(serialNumber); + if (!status) { + return Response.status(Response.Status.NOT_FOUND).entity( + "No certificate is found with the given " + + "serial number '" + serialNumber + "'").build(); + } else { + return Response.status(Response.Status.OK).entity( + "Certificate that carries the serial number '" + + serialNumber + "' has been removed").build(); + } + } catch (CertificateManagementException e) { + String msg = "Error occurred while converting PEM file to X509Certificate"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } } else { - return Response.status(Response.Status.OK).entity( - "Certificate that carries the certificate id '" + - certificateId + "' has been removed").build(); + return Response.status(Response.Status.NOT_FOUND).entity( + "User not have to access delete certificate " + + "serial number '" + serialNumber + "'").build(); } } catch (CertificateManagementException e) { String msg = "Error occurred while converting PEM file to X509Certificate"; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java index 6263ac9e46..43f4d1ab48 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/util/RequestValidationUtil.java @@ -30,14 +30,6 @@ public class RequestValidationUtil { } } - public static void validateCertificateId(String certificateId) { - if (certificateId == null || certificateId.isEmpty()) { - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( - "Certificate Id cannot be null or empty").build()); - } - } - public static void validatePaginationInfo(int offset, int limit) { if (offset < 0) { throw new InputValidationException( 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 84d4790af8..cb44ff8045 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 @@ -95,7 +95,8 @@ io.entgra.device.mgt.core.device.mgt.core.*, org.wso2.carbon.registry.indexing.*, javax.cache.*, - javax.naming.ldap + javax.naming.ldap, + com.google.gson.* @@ -253,6 +254,10 @@ slf4j-simple test + + com.googlecode.json-simple.wso2 + json-simple + diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java index a3200621d1..068766f3b9 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/CertificateDAO.java @@ -18,8 +18,10 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; +import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import java.util.List; @@ -75,13 +77,12 @@ public interface CertificateDAO { /** * Get all the certificates in a paginated manner. * - * @param rowNum Stating index of the paginated result. - * @param limit Number of records to return. + * @param request index of the paginated result. * @return Pagination result with data and the count of results. * @throws CertificateManagementDAOException * */ - PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException; + PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException; /** * Get all the certificates. @@ -95,10 +96,10 @@ public interface CertificateDAO { /** * Delete a certificate identified by a serial number() * - * @param certificateId number + * @param serialNumber number * @return whether the certificate was removed or not. */ - boolean removeCertificate(String certificateId) throws CertificateManagementDAOException; + boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException; List searchCertificate(String serialNumber) throws CertificateManagementDAOException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java index 8e87ffff38..78ea14c99f 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java @@ -237,7 +237,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME" + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME" + " FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -247,8 +247,6 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); @@ -265,7 +263,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ } @Override - public boolean removeCertificate(String certificateId) throws CertificateManagementDAOException { + public boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet resultSet = null; @@ -273,15 +271,15 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ try { conn = this.getConnection(); String query = - "DELETE FROM DM_DEVICE_CERTIFICATE WHERE ID = ?" + + "DELETE FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ?" + " AND TENANT_ID = ? "; stmt = conn.prepareStatement(query); - stmt.setString(1, certificateId); + stmt.setString(1, serialNumber); stmt.setInt(2, tenantId); return stmt.executeUpdate() > 0; } catch (SQLException e) { - String msg = "Unable to get the read the certificate with certificate id" + certificateId; + String msg = "Unable to get the read the certificate with serialNumber" + serialNumber; log.error(msg, e); throw new CertificateManagementDAOException(msg, e); } finally { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index f3cba82857..b24cc7625e 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import org.apache.commons.logging.Log; @@ -47,47 +48,120 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { private Connection getConnection() throws SQLException { return CertificateManagementDAOFactory.getConnection(); } - private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { int certificateCount = 0; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + PreparedStatement stmt = null; + ResultSet rs = null; + try { Connection conn = this.getConnection(); - String sql = - "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, tenantId); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); - } - } + StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + + if (serialNumber != null && !serialNumber.isEmpty()) { + queryBuilder.append(" AND SERIAL_NUMBER = ?"); + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + } + + if (username != null && !username.isEmpty()) { + queryBuilder.append(" AND USERNAME LIKE ?"); + } + + String sql = queryBuilder.toString(); + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (serialNumber != null && !serialNumber.isEmpty()) { + stmt.setString(paramIdx++, serialNumber); + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (username != null && !username.isEmpty()) { + stmt.setString(paramIdx, "%" + username + "%"); + } + + rs = stmt.executeQuery(); + + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); } } catch (SQLException e) { - String errorMsg = "SQL error occurred while retrieving the certificates."; + String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, rs); } + return certificateCount; } + + @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); PreparedStatement stmt = null; ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + boolean isCertificateSerialNumberProvided = false; + boolean isCertificateDeviceIdentifierProvided = false; + boolean isCertificateUsernameProvided = false; + try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, rowNum); - stmt.setInt(3, limit); - resultSet = stmt.executeQuery(); + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (serialNumber != null && !serialNumber.isEmpty()) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + query += "AND DEVICE_IDENTIFIER = ? "; + isCertificateDeviceIdentifierProvided = true; + } + + if (username != null && !username.isEmpty()) { + query += "AND USERNAME LIKE ? "; + isCertificateUsernameProvided = true; + } + + query += "ORDER BY ID LIMIT ?,?"; - int resultCount = 0; + stmt = conn.prepareStatement(query); + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + resultSet = stmt.executeQuery(); while (resultSet.next()) { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); @@ -98,11 +172,11 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); - resultCount++; } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -112,4 +186,4 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { } return paginationResult; } -} +} \ No newline at end of file diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java index f326f9cf97..7941cb60b7 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import org.apache.commons.logging.Log; @@ -44,24 +45,57 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(OracleCertificateDAOImpl.class); @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); PreparedStatement stmt = null; ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + boolean isCertificateSerialNumberProvided = false; + boolean isCertificateDeviceIdentifierProvided = false; + boolean isCertificateUsernameProvided = false; + try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, rowNum); - stmt.setInt(3, limit); - resultSet = stmt.executeQuery(); + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (serialNumber != null && !serialNumber.isEmpty()) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + query += "AND DEVICE_IDENTIFIER = ? "; + isCertificateDeviceIdentifierProvided = true; + } + + if (username != null && !username.isEmpty()) { + query += "AND USERNAME LIKE ? "; + isCertificateUsernameProvided = true; + } - int resultCount = 0; + query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(query); + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + resultSet = stmt.executeQuery(); while (resultSet.next()) { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); @@ -72,11 +106,10 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); - resultCount++; } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -91,25 +124,63 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { return CertificateManagementDAOFactory.getConnection(); } - private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { int certificateCount = 0; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + PreparedStatement stmt = null; + ResultSet rs = null; + try { Connection conn = this.getConnection(); - String sql = - "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, tenantId); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); - } - } + StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + + if (serialNumber != null && !serialNumber.isEmpty()) { + queryBuilder.append(" AND SERIAL_NUMBER = ?"); + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + } + + if (username != null && !username.isEmpty()) { + queryBuilder.append(" AND USERNAME LIKE ?"); + } + + String sql = queryBuilder.toString(); + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (serialNumber != null && !serialNumber.isEmpty()) { + stmt.setString(paramIdx++, serialNumber); + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (username != null && !username.isEmpty()) { + stmt.setString(paramIdx, "%" + username + "%"); + } + + rs = stmt.executeQuery(); + + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); } } catch (SQLException e) { - String errorMsg = "SQL error occurred while retrieving the certificates."; + String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, rs); } + return certificateCount; } + } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java index 7d187cfa3d..1c84fccbe0 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import org.apache.commons.logging.Log; @@ -44,24 +45,57 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(PostgreSQLCertificateDAOImpl.class); @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); PreparedStatement stmt = null; ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + boolean isCertificateSerialNumberProvided = false; + boolean isCertificateDeviceIdentifierProvided = false; + boolean isCertificateUsernameProvided = false; + try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ? OFFSET ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, limit); - stmt.setInt(3, rowNum); - resultSet = stmt.executeQuery(); + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (serialNumber != null && !serialNumber.isEmpty()) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + query += "AND DEVICE_IDENTIFIER = ? "; + isCertificateDeviceIdentifierProvided = true; + } + + if (username != null && !username.isEmpty()) { + query += "AND USERNAME LIKE ? "; + isCertificateUsernameProvided = true; + } - int resultCount = 0; + query += "ORDER BY ID LIMIT ? OFFSET ?"; + + stmt = conn.prepareStatement(query); + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + resultSet = stmt.executeQuery(); while (resultSet.next()) { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); @@ -72,11 +106,11 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); - resultCount++; } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -91,25 +125,63 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { return CertificateManagementDAOFactory.getConnection(); } - private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { int certificateCount = 0; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + PreparedStatement stmt = null; + ResultSet rs = null; + try { Connection conn = this.getConnection(); - String sql = - "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, tenantId); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); - } - } + StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + + if (serialNumber != null && !serialNumber.isEmpty()) { + queryBuilder.append(" AND SERIAL_NUMBER = ?"); + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + } + + if (username != null && !username.isEmpty()) { + queryBuilder.append(" AND USERNAME ILIKE ?"); + } + + String sql = queryBuilder.toString(); + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (serialNumber != null && !serialNumber.isEmpty()) { + stmt.setString(paramIdx++, serialNumber); + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (username != null && !username.isEmpty()) { + stmt.setString(paramIdx, "%" + username + "%"); + } + + rs = stmt.executeQuery(); + + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); } } catch (SQLException e) { - String errorMsg = "SQL error occurred while retrieving the certificates."; + String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, rs); } + return certificateCount; } + } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java index 6615ab4c12..9fe8733264 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import org.apache.commons.logging.Log; @@ -44,24 +45,57 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(SQLServerCertificateDAOImpl.class); @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); PreparedStatement stmt = null; ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + boolean isCertificateSerialNumberProvided = false; + boolean isCertificateDeviceIdentifierProvided = false; + boolean isCertificateUsernameProvided = false; + try { Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, ID, DEVICE_IDENTIFIER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, rowNum); - stmt.setInt(3, limit); - resultSet = stmt.executeQuery(); + String query = "SELECT * " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ? "; + if (serialNumber != null && !serialNumber.isEmpty()) { + query += "AND SERIAL_NUMBER = ? "; + isCertificateSerialNumberProvided = true; + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + query += "AND DEVICE_IDENTIFIER = ? "; + isCertificateDeviceIdentifierProvided = true; + } + + if (username != null && !username.isEmpty()) { + query += "AND USERNAME LIKE ? "; + isCertificateUsernameProvided = true; + } - int resultCount = 0; + query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(query); + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + resultSet = stmt.executeQuery(); while (resultSet.next()) { certificateResponse = new CertificateResponse(); byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); @@ -72,11 +106,11 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { certificateResponse.setUsername(resultSet.getString("USERNAME")); CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); certificates.add(certificateResponse); - resultCount++; } paginationResult = new PaginationResult(); paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(tenantId)); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); @@ -91,25 +125,63 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { return CertificateManagementDAOFactory.getConnection(); } - private int getCertificateCount(int tenantId) throws CertificateManagementDAOException, SQLException { + private int getCertificateCount(CertificatePaginationRequest request) throws CertificateManagementDAOException { int certificateCount = 0; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String serialNumber = request.getSerialNumber(); + String deviceIdentifier = request.getDeviceIdentifier(); + String username = request.getUsername(); + PreparedStatement stmt = null; + ResultSet rs = null; + try { Connection conn = this.getConnection(); - String sql = - "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"; - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, tenantId); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); - } - } + StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + + if (serialNumber != null && !serialNumber.isEmpty()) { + queryBuilder.append(" AND SERIAL_NUMBER = ?"); + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + } + + if (username != null && !username.isEmpty()) { + queryBuilder.append(" AND USERNAME LIKE ?"); + } + + String sql = queryBuilder.toString(); + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (serialNumber != null && !serialNumber.isEmpty()) { + stmt.setString(paramIdx++, serialNumber); + } + + if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (username != null && !username.isEmpty()) { + stmt.setString(paramIdx, "%" + username + "%"); + } + + rs = stmt.executeQuery(); + + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); } } catch (SQLException e) { - String errorMsg = "SQL error occurred while retrieving the certificates."; + String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, rs); } + return certificateCount; } + } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java index 61d333413e..611295ba3f 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementService.java @@ -17,6 +17,7 @@ */ package io.entgra.device.mgt.core.certificate.mgt.core.service; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.dto.SCEPResponse; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; @@ -71,9 +72,11 @@ public interface CertificateManagementService { CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementException; - PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException; + PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementException; - boolean removeCertificate(String certificateId) throws CertificateManagementException; + boolean removeCertificate(String serialNumber) throws CertificateManagementException; + + boolean getValidateMetaValue() throws CertificateManagementException; List getCertificates() throws CertificateManagementException; diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java index bcd696f21e..047c532197 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -17,6 +17,14 @@ */ package io.entgra.device.mgt.core.certificate.mgt.core.service; + + +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; +import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; +import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagerUtil; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateDAO; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; @@ -27,12 +35,14 @@ import io.entgra.device.mgt.core.certificate.mgt.core.exception.KeystoreExceptio import io.entgra.device.mgt.core.certificate.mgt.core.exception.TransactionManagementException; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.impl.KeyStoreReader; -import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagementConstants; -import io.entgra.device.mgt.core.certificate.mgt.core.util.CertificateManagerUtil; + +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.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.pkcs.PKCS10CertificationRequest; + import java.io.InputStream; import java.security.PrivateKey; import java.security.cert.Certificate; @@ -154,46 +164,70 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe } @Override - public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException { + public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementException { try { CertificateManagementDAOFactory.openConnection(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); - return certificateDAO.getAllCertificates(rowNum, CertificateManagerUtil.validateCertificateListPageSize(limit)); + return certificateDAO.getAllCertificates(request); } catch (SQLException e) { String msg = "Error occurred while opening a connection to the underlying data source"; log.error(msg, e); throw new CertificateManagementException(msg, e); } catch (CertificateManagementDAOException e) { String msg = "Error occurred while looking up for the list of certificates managed in the underlying " + - "certificate repository"; + "certificate repository"; log.error(msg, e); throw new CertificateManagementException(msg, e); } finally { CertificateManagementDAOFactory.closeConnection(); } } - @Override - public boolean removeCertificate(String certificateId) throws CertificateManagementException { + public boolean removeCertificate(String serialNumber) throws CertificateManagementException { try { CertificateManagementDAOFactory.beginTransaction(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); - boolean status = certificateDAO.removeCertificate(certificateId); + boolean status = certificateDAO.removeCertificate(serialNumber); CertificateManagementDAOFactory.commitTransaction(); return status; } catch (TransactionManagementException e) { - String msg = "Error occurred while removing certificate carrying certificate id '" + certificateId + "'"; + String msg = "Error occurred while removing certificate carrying serialNumber '" + serialNumber + "'"; log.error(msg, e); throw new CertificateManagementException(msg, e); } catch (CertificateManagementDAOException e) { CertificateManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while removing the certificate carrying certificate id '" + certificateId + + String msg = "Error occurred while removing the certificate carrying serialNumber '" + serialNumber + "' from the certificate repository"; log.error(msg, e); throw new CertificateManagementException(msg, e); } } + @Override + public boolean getValidateMetaValue() throws CertificateManagementException { + Metadata metadata; + try { + metadata = CertificateManagerUtil.getMetadataManagementService().retrieveMetadata(CertificateManagementConstants.CERTIFICATE_DELETE); + if (metadata != null) { + String metaValue = metadata.getMetaValue(); + if (metaValue != null && !metaValue.isEmpty()) { + JsonParser parser = new JsonParser(); + JsonObject jsonObject = parser.parse(metaValue).getAsJsonObject(); + return jsonObject.get(CertificateManagementConstants.IS_CERTIFICATE_DELETE_ENABLE).getAsBoolean(); + } + } + return false; + } catch (MetadataManagementException e) { + String msg = "Error occurred while getting the metadata entry for metaKey: " + CertificateManagementConstants.CERTIFICATE_DELETE; + log.error(msg, e); + throw new CertificateManagementException(msg, e); + } catch (JsonParseException e) { + String msg = "Error occurred while parsing the JSON metadata value for metaKey: " + CertificateManagementConstants.CERTIFICATE_DELETE; + log.error(msg, e); + throw new CertificateManagementException(msg, e); + } + } + @Override public List getCertificates() throws CertificateManagementException { try { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java index 8235b3ee77..f851bd05f0 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagementConstants.java @@ -41,6 +41,12 @@ public final class CertificateManagementConstants { public static final int RSA_KEY_LENGTH = 2048; public static final String SIGNING_ALGORITHM = "SHA256withRSA"; + public static final int DEFAULT_PAGE_LIMIT = 50; + + public static final String CERTIFICATE_DELETE = "CERTIFICATE_DELETE"; + public static final String IS_CERTIFICATE_DELETE_ENABLE = "isCertificateDelete"; + + public static final class DataBaseTypes { private DataBaseTypes() { throw new AssertionError(); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java index cfa613ba5a..2da3d4d414 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/util/CertificateManagerUtil.java @@ -19,6 +19,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.util; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; @@ -28,6 +29,7 @@ import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.DataSour import io.entgra.device.mgt.core.certificate.mgt.core.config.datasource.JNDILookupDefinition; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.exception.CertificateManagementException; +import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.sql.DataSource; import javax.xml.XMLConstants; @@ -41,6 +43,7 @@ public class CertificateManagerUtil { public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; public static final String MONITORING_FREQUENCY = "notifierFrequency"; + private static MetadataManagementService metadataManagementService; private static final Log log = LogFactory.getLog(CertificateManagerUtil.class); public static Document convertToDocument(File file) throws CertificateManagementException { @@ -105,4 +108,26 @@ public class CertificateManagerUtil { return limit; } + /** + * Initializing and accessing method for MetadataManagementService. + * + * @return MetadataManagementService instance + * @throws IllegalStateException if metadataManagementService cannot be initialized + */ + public static MetadataManagementService getMetadataManagementService() { + if (metadataManagementService == null) { + synchronized (CertificateManagerUtil.class) { + if (metadataManagementService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + metadataManagementService = (MetadataManagementService) ctx.getOSGiService( + MetadataManagementService.class, null); + if (metadataManagementService == null) { + throw new IllegalStateException("Metadata Management service not initialized."); + } + } + } + } + return metadataManagementService; + } + } \ No newline at end of file diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java index b1ce7cb8b6..7aff1cd586 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplNegativeTests.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.impl; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; @@ -110,7 +111,8 @@ public class CertificateManagementServiceImplNegativeTests extends PowerMockTest public void negativeTestGetAllCertificates() throws Exception { PowerMockito.mockStatic(CertificateManagementDAOFactory.class); PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection"); - instance.getAllCertificates(1, 2); + CertificatePaginationRequest request = new CertificatePaginationRequest(0, 2); + instance.getAllCertificates(request); } @Test(description = "This test case tests behaviour when an error occurs getting the list of certificates from repository" @@ -118,7 +120,8 @@ public class CertificateManagementServiceImplNegativeTests extends PowerMockTest public void negativeTestGetAllCertificates2() throws Exception { CertificateManagementDAOFactory.init(daoExceptionDatasource); CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance(); - instance1.getAllCertificates(1, 2); + CertificatePaginationRequest request = new CertificatePaginationRequest(0, 2); + instance.getAllCertificates(request); } @Test(description = "This test case tests behaviour when data source transaction error occurs when removing the certificate" diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java index ff6ad09e88..a57bfbb4d0 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateManagementServiceImplTests.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.certificate.mgt.core.impl; import io.entgra.device.mgt.core.certificate.mgt.core.util.CSRGenerator; import io.entgra.device.mgt.core.certificate.mgt.core.util.DummyCertificate; +import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -217,7 +218,8 @@ public class CertificateManagementServiceImplTests extends BaseDeviceManagementC public void testGetAllCertificatesPaginated() throws CertificateManagementException, KeystoreException { managementService.generateX509Certificate(); managementService.generateX509Certificate(); - PaginationResult allCertificates = managementService.getAllCertificates(0, 2); + CertificatePaginationRequest request = new CertificatePaginationRequest(0,2); + PaginationResult allCertificates = managementService.getAllCertificates(request); Assert.assertEquals(allCertificates.getData().size(), 2); log.info("GetAllCertificatesPaginated Test Successful"); } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql index 46582aa390..0fb769e406 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql @@ -37,6 +37,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, + DEVICE_IDENTIFIER VARCHAR(300), USERNAME VARCHAR(500) DEFAULT NULL, PRIMARY KEY (ID) ); \ 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/CertificatePaginationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/CertificatePaginationRequest.java new file mode 100644 index 0000000000..fdfcf5d30c --- /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/CertificatePaginationRequest.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.device.mgt.core.device.mgt.common; + +public class CertificatePaginationRequest { + private int startIndex; + private int rowCount; + private String serialNumber; + private String deviceIdentifier; + private String username; + + public CertificatePaginationRequest(int start, int rowCount) { + this.startIndex = start; + this.rowCount = rowCount; + } + + public int getStartIndex() { + return startIndex; + } + + public void setStartIndex(int startIndex) { + this.startIndex = startIndex; + } + + public int getRowCount() { + return rowCount; + } + + public void setRowCount(int rowCount) { + this.rowCount = rowCount; + } + + public String getSerialNumber() { + return serialNumber; + } + + public void setSerialNumber(String serialNumber) { + this.serialNumber = serialNumber; + } + + public String getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(String deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String toString() { + return "Certificate serial number '" + this.serialNumber + "' num of rows: " + this.rowCount + " start index: " + this.startIndex; + } +} From dbc73d18ede97983f30b5e7480332f9e62902a9b Mon Sep 17 00:00:00 2001 From: navodzoysa Date: Thu, 24 Aug 2023 16:05:14 +0530 Subject: [PATCH 36/36] Add improvements to certificate component --- .../CertificateManagementAdminService.java | 11 +- ...CertificateManagementAdminServiceImpl.java | 23 +-- .../pom.xml | 1 + .../dao/impl/GenericCertificateDAOImpl.java | 136 +++++++++--------- .../dao/impl/OracleCertificateDAOImpl.java | 126 ++++++++-------- .../impl/PostgreSQLCertificateDAOImpl.java | 127 ++++++++-------- .../dao/impl/SQLServerCertificateDAOImpl.java | 127 ++++++++-------- .../CertificateManagementServiceImpl.java | 5 +- 8 files changed, 265 insertions(+), 291 deletions(-) diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java index cd2be07ac9..af77d74719 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/CertificateManagementAdminService.java @@ -311,20 +311,17 @@ public interface CertificateManagementAdminService { @ApiParam( name = "serialNumber", value = "The serial number of the certificates", - required = false, - defaultValue = "0") + required = false) @QueryParam("serialNumber") String serialNumber, @ApiParam( name = "deviceIdentifier", value = "The device identifier of the certificates", - required = false, - defaultValue = "0") + required = false) @QueryParam("deviceIdentifier") String deviceIdentifier, @ApiParam( name = "username", - value = "User name of the certificate added user" , - required = false, - defaultValue = "0") + value = "User name of the certificate added user", + required = false) @QueryParam("username") String username, @ApiParam( name = "If-Modified-Since", diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java index 3f124a8946..815e141f38 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/src/main/java/io/entgra/device/mgt/core/certificate/mgt/cert/admin/api/impl/CertificateManagementAdminServiceImpl.java @@ -27,6 +27,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.CertificateManagementAdminService; @@ -138,20 +139,23 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem */ @GET public Response getAllCertificates( - @QueryParam("serialNumber") String serialNumber, @QueryParam("deviceIdentifier") String deviceIdentifier, - @QueryParam("username") String username, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, + @QueryParam("serialNumber") String serialNumber, + @QueryParam("deviceIdentifier") String deviceIdentifier, + @QueryParam("username") String username, + @HeaderParam("If-Modified-Since") String ifModifiedSince, + @QueryParam("offset") int offset, @QueryParam("limit") int limit) { RequestValidationUtil.validatePaginationInfo(offset, limit); CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); CertificatePaginationRequest request = new CertificatePaginationRequest(offset, limit); - if (serialNumber != null && !serialNumber.isEmpty()) { + if (StringUtils.isNotEmpty(serialNumber)) { request.setSerialNumber(serialNumber); } - if (deviceIdentifier != null){ + if (StringUtils.isNotEmpty(deviceIdentifier)){ request.setDeviceIdentifier(deviceIdentifier); } - if (username != null){ + if (StringUtils.isNotEmpty(username)){ request.setUsername(username); } try { @@ -188,18 +192,19 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem serialNumber + "' has been removed").build(); } } catch (CertificateManagementException e) { - String msg = "Error occurred while converting PEM file to X509Certificate"; + String msg = "Error occurred while removing certificate with the given " + + "serial number '" + serialNumber + "'"; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } else { - return Response.status(Response.Status.NOT_FOUND).entity( - "User not have to access delete certificate " + + return Response.status(Response.Status.UNAUTHORIZED).entity( + "User unauthorized to delete certificate with " + "serial number '" + serialNumber + "'").build(); } } catch (CertificateManagementException e) { - String msg = "Error occurred while converting PEM file to X509Certificate"; + String msg = "Error occurred while getting the metadata entry for certificate deletion."; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); 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 cb44ff8045..ef8abbba07 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 @@ -56,6 +56,7 @@ org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.apache.commons.lang, org.apache.commons.logging, org.apache.commons.collections.map, javax.security.auth.x500, diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index b24cc7625e..7655e46005 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -21,11 +21,11 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -55,66 +55,58 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { String serialNumber = request.getSerialNumber(); String deviceIdentifier = request.getDeviceIdentifier(); String username = request.getUsername(); - PreparedStatement stmt = null; - ResultSet rs = null; try { Connection conn = this.getConnection(); - StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; - if (serialNumber != null && !serialNumber.isEmpty()) { - queryBuilder.append(" AND SERIAL_NUMBER = ?"); + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; } - if (username != null && !username.isEmpty()) { - queryBuilder.append(" AND USERNAME LIKE ?"); + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME LIKE ?"; } - String sql = queryBuilder.toString(); - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - - int paramIdx = 2; - if (serialNumber != null && !serialNumber.isEmpty()) { - stmt.setString(paramIdx++, serialNumber); - } - - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - stmt.setString(paramIdx++, deviceIdentifier); - } - - if (username != null && !username.isEmpty()) { - stmt.setString(paramIdx, "%" + username + "%"); - } - - rs = stmt.executeQuery(); - - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } + + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } + + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } } } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, rs); } - return certificateCount; } - @Override public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - PreparedStatement stmt = null; - ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; @@ -130,59 +122,59 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { String query = "SELECT * " + "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; - if (serialNumber != null && !serialNumber.isEmpty()) { + + if (StringUtils.isNotEmpty(serialNumber)) { query += "AND SERIAL_NUMBER = ? "; isCertificateSerialNumberProvided = true; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + if (StringUtils.isNotEmpty(deviceIdentifier)) { query += "AND DEVICE_IDENTIFIER = ? "; isCertificateDeviceIdentifierProvided = true; } - if (username != null && !username.isEmpty()) { + if (StringUtils.isNotEmpty(username)) { query += "AND USERNAME LIKE ? "; isCertificateUsernameProvided = true; } query += "ORDER BY ID LIMIT ?,?"; - stmt = conn.prepareStatement(query); - int paramIdx = 1; - stmt.setInt(paramIdx++, tenantId); - if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + try (PreparedStatement stmt = conn.prepareStatement(query)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - if (isCertificateDeviceIdentifierProvided) { - stmt.setString(paramIdx++, deviceIdentifier); - } - if (isCertificateUsernameProvided) { - stmt.setString(paramIdx++, "%" + username + "%"); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx++, request.getRowCount()); - resultSet = stmt.executeQuery(); - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(request)); - } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java index 7941cb60b7..9231a0d746 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java @@ -21,11 +21,11 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -47,8 +47,6 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { @Override public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - PreparedStatement stmt = null; - ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; @@ -64,58 +62,58 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { String query = "SELECT * " + "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; - if (serialNumber != null && !serialNumber.isEmpty()) { + if (StringUtils.isNotEmpty(serialNumber)) { query += "AND SERIAL_NUMBER = ? "; isCertificateSerialNumberProvided = true; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + if (StringUtils.isNotEmpty(deviceIdentifier)) { query += "AND DEVICE_IDENTIFIER = ? "; isCertificateDeviceIdentifierProvided = true; } - if (username != null && !username.isEmpty()) { + if (StringUtils.isNotEmpty(username)) { query += "AND USERNAME LIKE ? "; isCertificateUsernameProvided = true; } query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(query); - int paramIdx = 1; - stmt.setInt(paramIdx++, tenantId); - if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + try (PreparedStatement stmt = conn.prepareStatement(query)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - if (isCertificateDeviceIdentifierProvided) { - stmt.setString(paramIdx++, deviceIdentifier); - } - if (isCertificateUsernameProvided) { - stmt.setString(paramIdx++, "%" + username + "%"); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx++, request.getRowCount()); - resultSet = stmt.executeQuery(); - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(request)); } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } @@ -130,56 +128,52 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { String serialNumber = request.getSerialNumber(); String deviceIdentifier = request.getDeviceIdentifier(); String username = request.getUsername(); - PreparedStatement stmt = null; - ResultSet rs = null; try { Connection conn = this.getConnection(); - StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; - if (serialNumber != null && !serialNumber.isEmpty()) { - queryBuilder.append(" AND SERIAL_NUMBER = ?"); + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; } - if (username != null && !username.isEmpty()) { - queryBuilder.append(" AND USERNAME LIKE ?"); + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME LIKE ?"; } - String sql = queryBuilder.toString(); - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); - int paramIdx = 2; - if (serialNumber != null && !serialNumber.isEmpty()) { - stmt.setString(paramIdx++, serialNumber); - } + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - stmt.setString(paramIdx++, deviceIdentifier); - } + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } - if (username != null && !username.isEmpty()) { - stmt.setString(paramIdx, "%" + username + "%"); - } + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } - rs = stmt.executeQuery(); - - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } } } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, rs); } - return certificateCount; } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java index 1c84fccbe0..e31e005f0b 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java @@ -21,11 +21,11 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -47,8 +47,6 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { @Override public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - PreparedStatement stmt = null; - ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; @@ -64,59 +62,58 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { String query = "SELECT * " + "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; - if (serialNumber != null && !serialNumber.isEmpty()) { + if (StringUtils.isNotEmpty(serialNumber)) { query += "AND SERIAL_NUMBER = ? "; isCertificateSerialNumberProvided = true; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + if (StringUtils.isNotEmpty(deviceIdentifier)) { query += "AND DEVICE_IDENTIFIER = ? "; isCertificateDeviceIdentifierProvided = true; } - if (username != null && !username.isEmpty()) { + if (StringUtils.isNotEmpty(username)) { query += "AND USERNAME LIKE ? "; isCertificateUsernameProvided = true; } query += "ORDER BY ID LIMIT ? OFFSET ?"; - stmt = conn.prepareStatement(query); - int paramIdx = 1; - stmt.setInt(paramIdx++, tenantId); - if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + try (PreparedStatement stmt = conn.prepareStatement(query)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - if (isCertificateDeviceIdentifierProvided) { - stmt.setString(paramIdx++, deviceIdentifier); - } - if (isCertificateUsernameProvided) { - stmt.setString(paramIdx++, "%" + username + "%"); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx++, request.getRowCount()); - resultSet = stmt.executeQuery(); - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(request)); - } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } @@ -131,56 +128,52 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { String serialNumber = request.getSerialNumber(); String deviceIdentifier = request.getDeviceIdentifier(); String username = request.getUsername(); - PreparedStatement stmt = null; - ResultSet rs = null; try { Connection conn = this.getConnection(); - StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; - if (serialNumber != null && !serialNumber.isEmpty()) { - queryBuilder.append(" AND SERIAL_NUMBER = ?"); + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; } - if (username != null && !username.isEmpty()) { - queryBuilder.append(" AND USERNAME ILIKE ?"); + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME ILIKE ?"; } - String sql = queryBuilder.toString(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } - int paramIdx = 2; - if (serialNumber != null && !serialNumber.isEmpty()) { - stmt.setString(paramIdx++, serialNumber); - } + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - stmt.setString(paramIdx++, deviceIdentifier); - } + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } - if (username != null && !username.isEmpty()) { - stmt.setString(paramIdx, "%" + username + "%"); - } - - rs = stmt.executeQuery(); - - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } } } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, rs); } - return certificateCount; } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java index 9fe8733264..6e0908a286 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java @@ -21,11 +21,11 @@ package io.entgra.device.mgt.core.certificate.mgt.core.dao.impl; import io.entgra.device.mgt.core.device.mgt.common.CertificatePaginationRequest; import io.entgra.device.mgt.core.certificate.mgt.core.dto.CertificateResponse; import io.entgra.device.mgt.core.certificate.mgt.core.impl.CertificateGenerator; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOException; import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOFactory; -import io.entgra.device.mgt.core.certificate.mgt.core.dao.CertificateManagementDAOUtil; import io.entgra.device.mgt.core.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -47,8 +47,6 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { @Override public PaginationResult getAllCertificates(CertificatePaginationRequest request) throws CertificateManagementDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - PreparedStatement stmt = null; - ResultSet resultSet = null; CertificateResponse certificateResponse; List certificates = new ArrayList<>(); PaginationResult paginationResult; @@ -64,59 +62,58 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { String query = "SELECT * " + "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; - if (serialNumber != null && !serialNumber.isEmpty()) { + if (StringUtils.isNotEmpty(serialNumber)) { query += "AND SERIAL_NUMBER = ? "; isCertificateSerialNumberProvided = true; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { + if (StringUtils.isNotEmpty(deviceIdentifier)) { query += "AND DEVICE_IDENTIFIER = ? "; isCertificateDeviceIdentifierProvided = true; } - if (username != null && !username.isEmpty()) { + if (StringUtils.isNotEmpty(username)) { query += "AND USERNAME LIKE ? "; isCertificateUsernameProvided = true; } query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; - stmt = conn.prepareStatement(query); - int paramIdx = 1; - stmt.setInt(paramIdx++, tenantId); - if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + try (PreparedStatement stmt = conn.prepareStatement(query)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isCertificateSerialNumberProvided) { + stmt.setString(paramIdx++, serialNumber); + } + if (isCertificateDeviceIdentifierProvided) { + stmt.setString(paramIdx++, deviceIdentifier); + } + if (isCertificateUsernameProvided) { + stmt.setString(paramIdx++, "%" + username + "%"); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx++, request.getRowCount()); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setCertificateId(resultSet.getString("ID")); + certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(this.getCertificateCount(request)); + } } - if (isCertificateDeviceIdentifierProvided) { - stmt.setString(paramIdx++, deviceIdentifier); - } - if (isCertificateUsernameProvided) { - stmt.setString(paramIdx++, "%" + username + "%"); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx++, request.getRowCount()); - resultSet = stmt.executeQuery(); - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setCertificateId(resultSet.getString("ID")); - certificateResponse.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFIER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - paginationResult = new PaginationResult(); - paginationResult.setData(certificates); - paginationResult.setRecordsTotal(this.getCertificateCount(request)); - } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificates."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); } return paginationResult; } @@ -131,56 +128,52 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { String serialNumber = request.getSerialNumber(); String deviceIdentifier = request.getDeviceIdentifier(); String username = request.getUsername(); - PreparedStatement stmt = null; - ResultSet rs = null; try { Connection conn = this.getConnection(); - StringBuilder queryBuilder = new StringBuilder("SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ?"); + String sql = "SELECT COUNT(*) AS DEVICE_CERTIFICATE_COUNT " + + "FROM DM_DEVICE_CERTIFICATE " + + "WHERE TENANT_ID = ?"; - if (serialNumber != null && !serialNumber.isEmpty()) { - queryBuilder.append(" AND SERIAL_NUMBER = ?"); + if (StringUtils.isNotEmpty(serialNumber)) { + sql += " AND SERIAL_NUMBER = ?"; } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - queryBuilder.append(" AND DEVICE_IDENTIFIER = ?"); + if (StringUtils.isNotEmpty(deviceIdentifier)) { + sql += " AND DEVICE_IDENTIFIER = ?"; } - if (username != null && !username.isEmpty()) { - queryBuilder.append(" AND USERNAME LIKE ?"); + if (StringUtils.isNotEmpty(username)) { + sql += " AND USERNAME LIKE ?"; } - String sql = queryBuilder.toString(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); + int paramIdx = 2; + if (StringUtils.isNotEmpty(serialNumber)) { + stmt.setString(paramIdx++, serialNumber); + } - int paramIdx = 2; - if (serialNumber != null && !serialNumber.isEmpty()) { - stmt.setString(paramIdx++, serialNumber); - } + if (StringUtils.isNotEmpty(deviceIdentifier)) { + stmt.setString(paramIdx++, deviceIdentifier); + } - if (deviceIdentifier != null && !deviceIdentifier.isEmpty()) { - stmt.setString(paramIdx++, deviceIdentifier); - } + if (StringUtils.isNotEmpty(username)) { + stmt.setString(paramIdx, "%" + username + "%"); + } - if (username != null && !username.isEmpty()) { - stmt.setString(paramIdx, "%" + username + "%"); - } - - rs = stmt.executeQuery(); - - if (rs.next()) { - certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + certificateCount = rs.getInt("DEVICE_CERTIFICATE_COUNT"); + } + } } } catch (SQLException e) { String errorMsg = "SQL error occurred while retrieving the certificate count."; log.error(errorMsg, e); throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, rs); } - return certificateCount; } diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java index 047c532197..06cbedfb4d 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -17,8 +17,6 @@ */ package io.entgra.device.mgt.core.certificate.mgt.core.service; - - import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; @@ -38,6 +36,7 @@ import io.entgra.device.mgt.core.certificate.mgt.core.impl.KeyStoreReader; 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.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.pkcs.PKCS10CertificationRequest; @@ -210,7 +209,7 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe metadata = CertificateManagerUtil.getMetadataManagementService().retrieveMetadata(CertificateManagementConstants.CERTIFICATE_DELETE); if (metadata != null) { String metaValue = metadata.getMetaValue(); - if (metaValue != null && !metaValue.isEmpty()) { + if (StringUtils.isNotEmpty(metaValue)) { JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(metaValue).getAsJsonObject(); return jsonObject.get(CertificateManagementConstants.IS_CERTIFICATE_DELETE_ENABLE).getAsBoolean();