sergehuber commented on code in PR #763:
URL: https://github.com/apache/unomi/pull/763#discussion_r3377906755


##########
tools/shell-dev-commands/src/main/java/org/apache/unomi/shell/dev/commands/apikeys/ApiKeyCrudCommand.java:
##########
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.shell.dev.commands.apikeys;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.unomi.api.PartialList;
+import org.apache.unomi.api.query.Query;
+import org.apache.unomi.api.tenants.ApiKey;
+import org.apache.unomi.api.tenants.ApiKey.ApiKeyType;
+import org.apache.unomi.api.tenants.Tenant;
+import org.apache.unomi.api.tenants.TenantService;
+import org.apache.unomi.persistence.spi.CustomObjectMapper;
+import org.apache.unomi.shell.dev.services.BaseCrudCommand;
+import org.apache.unomi.shell.dev.services.CrudCommand;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Reference;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Component(service = CrudCommand.class, immediate = true)
+public class ApiKeyCrudCommand extends BaseCrudCommand {
+
+    private static final ObjectMapper OBJECT_MAPPER = new CustomObjectMapper();
+    private static final List<String> PROPERTY_NAMES = List.of(
+        "itemId", "name", "description", "keyType", "key", "tenantId"
+    );

Review Comment:
   Good spot — `validityPeriod` was handled in `create()` but never listed in 
`PROPERTY_NAMES`, so tab-completion would never suggest it. Added it to the 
list.



##########
tools/shell-dev-commands/src/main/java/org/apache/unomi/shell/dev/commands/apikeys/ApiKeyCrudCommand.java:
##########
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.shell.dev.commands.apikeys;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.unomi.api.PartialList;
+import org.apache.unomi.api.query.Query;
+import org.apache.unomi.api.tenants.ApiKey;
+import org.apache.unomi.api.tenants.ApiKey.ApiKeyType;
+import org.apache.unomi.api.tenants.Tenant;
+import org.apache.unomi.api.tenants.TenantService;
+import org.apache.unomi.persistence.spi.CustomObjectMapper;
+import org.apache.unomi.shell.dev.services.BaseCrudCommand;
+import org.apache.unomi.shell.dev.services.CrudCommand;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Reference;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Component(service = CrudCommand.class, immediate = true)
+public class ApiKeyCrudCommand extends BaseCrudCommand {
+
+    private static final ObjectMapper OBJECT_MAPPER = new CustomObjectMapper();
+    private static final List<String> PROPERTY_NAMES = List.of(
+        "itemId", "name", "description", "keyType", "key", "tenantId"
+    );
+
+    @Reference
+    private TenantService tenantService;
+
+    @Override
+    public String getObjectType() {
+        return "apikey";
+    }
+
+    @Override
+    protected String[] getHeadersWithoutTenant() {
+        return new String[] {
+            "Identifier",
+            "Name",
+            "Description",
+            "Key Type",
+            "Key"
+        };
+    }
+
+    @Override
+    protected PartialList<?> getItems(Query query) {
+        List<ApiKey> allApiKeys = new ArrayList<>();
+        for (Tenant tenant : tenantService.getAllTenants()) {
+            if (tenant.getApiKeys() != null) {
+                allApiKeys.addAll(tenant.getApiKeys());
+            }
+        }
+
+        // Apply query limit
+        Integer offset = query.getOffset();
+        Integer limit = query.getLimit();
+        int start = offset == null ? 0 : offset;
+        int size = limit == null ? allApiKeys.size() : limit;
+        int end = Math.min(start + size, allApiKeys.size());
+
+        List<ApiKey> pagedApiKeys = allApiKeys.subList(start, end);
+        return new PartialList<ApiKey>(pagedApiKeys, start, 
pagedApiKeys.size(), allApiKeys.size(), PartialList.Relation.EQUAL);
+    }
+
+    @Override
+    protected String[] buildRow(Object item) {
+        ApiKey apiKey = (ApiKey) item;
+        return new String[] {
+            apiKey.getItemId(),
+            apiKey.getName(),
+            apiKey.getDescription(),
+            apiKey.getKeyType().toString(),
+            apiKey.getKey()
+        };
+    }
+
+    @Override
+    public String create(Map<String, Object> properties) {
+        String tenantId = (String) properties.get("tenantId");
+        if (StringUtils.isBlank(tenantId)) {
+            throw new IllegalArgumentException("tenantId is required");
+        }
+
+        ApiKeyType keyType = ApiKeyType.valueOf((String) 
properties.get("keyType"));
+        Long validityPeriod = properties.containsKey("validityPeriod") ?
+            Long.valueOf((String) properties.get("validityPeriod")) : null;
+
+        ApiKey apiKey = tenantService.generateApiKeyWithType(tenantId, 
keyType, validityPeriod);
+        if (apiKey != null) {
+            apiKey.setName((String) properties.get("name"));
+            apiKey.setDescription((String) properties.get("description"));
+
+            // Update the tenant with the new API key metadata
+            Tenant tenant = tenantService.getTenant(tenantId);
+            tenantService.saveTenant(tenant);
+        }
+        return apiKey.getItemId();
+    }

Review Comment:
   Correct. Setting fields on the returned `ApiKey` had no effect since the 
Tenant document holds the embedded list. Fixed by reloading the tenant after 
key generation, finding the new key by `itemId` in the embedded list, setting 
the metadata there, then calling `saveTenant`.



##########
tools/shell-dev-commands/src/main/java/org/apache/unomi/shell/dev/commands/apikeys/ApiKeyCrudCommand.java:
##########
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.shell.dev.commands.apikeys;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.unomi.api.PartialList;
+import org.apache.unomi.api.query.Query;
+import org.apache.unomi.api.tenants.ApiKey;
+import org.apache.unomi.api.tenants.ApiKey.ApiKeyType;
+import org.apache.unomi.api.tenants.Tenant;
+import org.apache.unomi.api.tenants.TenantService;
+import org.apache.unomi.persistence.spi.CustomObjectMapper;
+import org.apache.unomi.shell.dev.services.BaseCrudCommand;
+import org.apache.unomi.shell.dev.services.CrudCommand;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Reference;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Component(service = CrudCommand.class, immediate = true)
+public class ApiKeyCrudCommand extends BaseCrudCommand {
+
+    private static final ObjectMapper OBJECT_MAPPER = new CustomObjectMapper();
+    private static final List<String> PROPERTY_NAMES = List.of(
+        "itemId", "name", "description", "keyType", "key", "tenantId"
+    );
+
+    @Reference
+    private TenantService tenantService;
+
+    @Override
+    public String getObjectType() {
+        return "apikey";
+    }
+
+    @Override
+    protected String[] getHeadersWithoutTenant() {
+        return new String[] {
+            "Identifier",
+            "Name",
+            "Description",
+            "Key Type",
+            "Key"
+        };
+    }
+
+    @Override
+    protected PartialList<?> getItems(Query query) {
+        List<ApiKey> allApiKeys = new ArrayList<>();
+        for (Tenant tenant : tenantService.getAllTenants()) {
+            if (tenant.getApiKeys() != null) {
+                allApiKeys.addAll(tenant.getApiKeys());
+            }
+        }

Review Comment:
   Correct. `TenantServiceImpl` doesn't populate `tenantId` on embedded 
`ApiKey` objects, so `BaseCrudCommand`'s Tenant column was always blank. Fixed 
by iterating over each tenant's keys and calling 
`k.setTenantId(tenant.getItemId())` before adding them to the list.



##########
tools/shell-dev-commands/src/main/java/org/apache/unomi/shell/dev/commands/CacheCommands.java:
##########
@@ -0,0 +1,368 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.shell.dev.commands;
+
+import org.apache.commons.csv.CSVFormat;
+import org.apache.commons.csv.CSVPrinter;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.Option;
+import org.apache.karaf.shell.api.action.lifecycle.Reference;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.apache.karaf.shell.support.table.ShellTable;
+
+import org.apache.unomi.api.services.ExecutionContextManager;
+import org.apache.unomi.api.services.cache.MultiTypeCacheService;
+import 
org.apache.unomi.api.services.cache.MultiTypeCacheService.CacheStatistics;
+import 
org.apache.unomi.api.services.cache.MultiTypeCacheService.CacheStatistics.TypeStatistics;
+import org.apache.unomi.api.tenants.TenantService;
+import org.apache.unomi.shell.dev.commands.TenantContextHelper;
+
+import java.io.PrintStream;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+@Service
+@Command(scope = "unomi", name = "cache", description = "Cache management 
commands")
+public class CacheCommands extends BaseSimpleCommand {
+
+    @Reference
+    private MultiTypeCacheService cacheService;
+
+    @Reference
+    private TenantService tenantService;
+
+    @Reference
+    private ExecutionContextManager executionContextManager;
+
+    @Option(name = "--stats", description = "Display cache statistics", 
required = false)
+    private boolean showStats = false;
+
+    @Option(name = "--reset", description = "Reset statistics after displaying 
them", required = false)
+    private boolean reset = false;
+
+    @Option(name = "--type", description = "Filter by type", required = false)
+    private String type;
+
+    @Option(name = "--tenant", description = "Filter by tenant ID", required = 
false)
+    private String tenantId;
+
+    @Option(name = "--clear", description = "Clear cache for specified 
tenant", required = false)
+    private boolean clear = false;
+
+    @Option(name = "--inspect", description = "Inspect cache contents", 
required = false)
+    private boolean inspect = false;
+
+    @Option(name = "--detailed", description = "Show detailed statistics", 
required = false)
+    private boolean detailed = false;
+
+    @Option(name = "--watch", description = "Watch cache statistics (refresh 
interval in seconds)", required = false)
+    private int watchInterval = 0;
+
+    @Option(name = "--csv", description = "Output statistics in CSV format", 
required = false)
+    private boolean csv = false;
+
+    @Option(name = "--id", description = "Specific entry ID to view or 
remove", required = false)
+    private String entryId;
+
+    @Option(name = "--view", description = "View a specific cache entry", 
required = false)
+    private boolean view = false;
+
+    @Option(name = "--remove", description = "Remove a specific cache entry", 
required = false)
+    private boolean remove = false;
+
+    @Override
+    public Object execute() throws Exception {
+        if (cacheService == null) {
+            println("Cache service not available");
+            return null;
+        }
+
+        // Initialize execution context from session
+        TenantContextHelper.initializeExecutionContext(session, 
executionContextManager);
+
+        // Set default tenant if not specified
+        if (tenantId == null) {
+            tenantId = 
executionContextManager.getCurrentContext().getTenantId();
+        }
+
+        if (view && entryId != null) {
+            viewCacheEntry();
+            return null;
+        }
+
+        if (remove && entryId != null) {
+            removeCacheEntry();
+            return null;
+        }
+
+        if (clear) {
+            clearCache();
+            return null;
+        }
+
+        if (inspect) {
+            inspectCache();
+            return null;
+        }
+
+        if (watchInterval > 0) {
+            watchStatistics();
+            return null;
+        }
+
+        if (showStats || (!clear && !inspect && !view && !remove)) {
+            displayStatistics();
+        }
+
+        return null;
+    }
+
+    private void viewCacheEntry() {
+        if (type == null) {
+            println("Please specify a type to view the entry");
+            return;
+        }
+
+        try {
+            Class<? extends Serializable> typeClass = (Class<? extends 
Serializable>) Class.forName(type);
+            Map<String, ? extends Serializable> typeCache = 
cacheService.getTenantCache(tenantId, typeClass);
+
+            Serializable entry = typeCache.get(entryId);
+            if (entry != null) {
+                println("Cache entry found:");
+                println("  Tenant: " + tenantId);
+                println("  Type: " + type);
+                println("  ID: " + entryId);
+                println("  Value: " + entry);
+                // Add any additional entry details you want to display
+            } else {
+                println("No cache entry found for ID: " + entryId);
+            }
+        } catch (ClassNotFoundException e) {
+            println("Invalid type specified: " + type);
+        }
+    }
+
+    private void removeCacheEntry() {
+        if (type == null) {
+            println("Please specify a type to remove the entry");
+            return;
+        }
+
+        try {
+            Class<? extends Serializable> typeClass = (Class<? extends 
Serializable>) Class.forName(type);
+
+            // First check if the entry exists
+            Map<String, ? extends Serializable> typeCache = 
cacheService.getTenantCache(tenantId, typeClass);
+            if (typeCache.containsKey(entryId)) {
+                cacheService.remove(type, entryId, tenantId, typeClass);
+                println("Successfully removed cache entry:");

Review Comment:
   Spot on. The `--type` option expects a Java class name (for 
`Class.forName`), but the 4-arg `remove()` overload expects the registered 
`itemType` string (e.g. `"patch"`, `"goal"`), not the FQCN. Added a new 
`remove(id, tenantId, typeClass)` overload to `MultiTypeCacheService` that 
resolves the `itemType` internally from the registered `CacheableTypeConfig` 
map, and updated the command to use that instead.



##########
tools/shell-dev-commands/src/main/java/org/apache/unomi/shell/dev/commands/apikeys/ApiKeyCrudCommand.java:
##########
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.unomi.shell.dev.commands.apikeys;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.unomi.api.PartialList;
+import org.apache.unomi.api.query.Query;
+import org.apache.unomi.api.tenants.ApiKey;
+import org.apache.unomi.api.tenants.ApiKey.ApiKeyType;
+import org.apache.unomi.api.tenants.Tenant;
+import org.apache.unomi.api.tenants.TenantService;
+import org.apache.unomi.persistence.spi.CustomObjectMapper;
+import org.apache.unomi.shell.dev.services.BaseCrudCommand;
+import org.apache.unomi.shell.dev.services.CrudCommand;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Reference;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Component(service = CrudCommand.class, immediate = true)
+public class ApiKeyCrudCommand extends BaseCrudCommand {
+
+    private static final ObjectMapper OBJECT_MAPPER = new CustomObjectMapper();
+    private static final List<String> PROPERTY_NAMES = List.of(
+        "itemId", "name", "description", "keyType", "key", "tenantId"
+    );
+
+    @Reference
+    private TenantService tenantService;
+
+    @Override
+    public String getObjectType() {
+        return "apikey";
+    }
+
+    @Override
+    protected String[] getHeadersWithoutTenant() {
+        return new String[] {
+            "Identifier",
+            "Name",
+            "Description",
+            "Key Type",
+            "Key"
+        };
+    }
+
+    @Override
+    protected PartialList<?> getItems(Query query) {
+        List<ApiKey> allApiKeys = new ArrayList<>();
+        for (Tenant tenant : tenantService.getAllTenants()) {
+            if (tenant.getApiKeys() != null) {
+                allApiKeys.addAll(tenant.getApiKeys());
+            }
+        }
+
+        // Apply query limit
+        Integer offset = query.getOffset();
+        Integer limit = query.getLimit();
+        int start = offset == null ? 0 : offset;
+        int size = limit == null ? allApiKeys.size() : limit;
+        int end = Math.min(start + size, allApiKeys.size());
+
+        List<ApiKey> pagedApiKeys = allApiKeys.subList(start, end);
+        return new PartialList<ApiKey>(pagedApiKeys, start, 
pagedApiKeys.size(), allApiKeys.size(), PartialList.Relation.EQUAL);
+    }
+
+    @Override
+    protected String[] buildRow(Object item) {
+        ApiKey apiKey = (ApiKey) item;
+        return new String[] {
+            apiKey.getItemId(),
+            apiKey.getName(),
+            apiKey.getDescription(),
+            apiKey.getKeyType().toString(),
+            apiKey.getKey()
+        };
+    }
+
+    @Override
+    public String create(Map<String, Object> properties) {
+        String tenantId = (String) properties.get("tenantId");
+        if (StringUtils.isBlank(tenantId)) {
+            throw new IllegalArgumentException("tenantId is required");
+        }
+
+        ApiKeyType keyType = ApiKeyType.valueOf((String) 
properties.get("keyType"));
+        Long validityPeriod = properties.containsKey("validityPeriod") ?
+            Long.valueOf((String) properties.get("validityPeriod")) : null;
+

Review Comment:
   Valid. The `Long.valueOf((String) ...)` cast fails for Jackson-deserialized 
numbers; fixed with an `instanceof Number` check falling back to 
`Long.parseLong`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to