Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto empty trash #81

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
* @author Etienne Homer <etienne.homer at rte-france.com>
*/
@SuppressWarnings("checkstyle:HideUtilityClassConstructor")
@SpringBootApplication
@EnableScheduling
public class ExploreApplication {
public static void main(String[] args) {
SpringApplication.run(ExploreApplication.class, args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,16 @@ public ElementAttributes getElementInfos(UUID elementUuid) {
.getBody();
}

public List<ElementAttributes> getStashedElementInfos(int daysAgo) {
String path = UriComponentsBuilder
.fromPath(ELEMENTS_SERVER_ROOT_PATH + "/stashed")
.queryParam("daysAgo", daysAgo)
.toUriString();
return restTemplate.exchange(directoryServerBaseUri + path, HttpMethod.GET, null, new ParameterizedTypeReference<List<ElementAttributes>>() {
})
.getBody();
}

private List<ElementAttributes> getElementsInfos(List<UUID> elementsUuids, List<String> elementTypes) {
var ids = elementsUuids.stream().map(UUID::toString).collect(Collectors.joining(","));
String path = UriComponentsBuilder.fromPath(ELEMENTS_SERVER_ROOT_PATH).toUriString() + "?ids=" + ids;
Expand Down Expand Up @@ -168,8 +178,12 @@ private List<ElementAttributes> getDirectoryElements(UUID directoryUuid, String

public void deleteElement(UUID id, String userId) {
ElementAttributes elementAttribute = getElementInfos(id);
IDirectoryElementsService service = getGenericService(elementAttribute.getType());
service.delete(elementAttribute.getElementUuid(), userId);
deleteElementByElementAttribute(elementAttribute, userId);
}

public void deleteElementByElementAttribute(ElementAttributes elementAttributes, String userId) {
IDirectoryElementsService service = getGenericService(elementAttributes.getType());
service.delete(elementAttributes.getElementUuid(), userId);
}

private IDirectoryElementsService getGenericService(String type) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import static org.gridsuite.explore.server.ExploreException.Type.NOT_ALLOWED;
import static org.gridsuite.explore.server.ExploreException.Type.UNKNOWN_ELEMENT_TYPE;
Expand Down Expand Up @@ -215,6 +216,35 @@ public void deleteElements(List<UUID> uuids, String userId) {
}
}

public void deleteElementsByElementAttributes(String userId, List<ElementAttributes> elementsAttributes) {
try {
elementsAttributes.forEach(elementAttributes ->
directoryService.deleteElementByElementAttribute(elementAttributes, userId));
} catch (Exception e) {
LOGGER.error(e.toString(), e);
} finally {
List<UUID> elementsUuid = elementsAttributes.stream()
.map(ElementAttributes::getElementUuid)
.toList();
directoryService.deleteDirectoryElements(
elementsUuid,
userId);
}
}

public void deleteStashedElementsOlderThanDays(int daysAgo) {
Map<String, List<ElementAttributes>> stashedElementsToDelete = directoryService.getStashedElementInfos(daysAgo).stream()
.collect(Collectors.groupingBy(ElementAttributes::getOwner));
if (stashedElementsToDelete.isEmpty()) {
LOGGER.error("No elements found in the trash to clean up.");
return;
}
stashedElementsToDelete.forEach((owner, elementAttributesList) ->
deleteElementsByElementAttributes(owner, elementAttributesList)
);
LOGGER.error("Trash cleanup completed successfully.");
}

public void updateFilter(UUID id, String filter, String userId, String name) {
filterService.updateFilter(id, filter, userId);
updateElementName(id, name, userId);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package org.gridsuite.explore.server.services;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;

@Service
public class ScheduledCleaner {
private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledCleaner.class);

private ExploreService exploreService;

public ScheduledCleaner(ExploreService exploreService) {
this.exploreService = exploreService;
}

@Scheduled(cron = "${cleaning-stash-cron}", zone = "UTC")
public void deleteStashedExpired() {
ZonedDateTime startZonedDateTime = ZonedDateTime.now(ZoneOffset.UTC);
LOGGER.info("Cleaning cases cron starting execution at {}", startZonedDateTime);
exploreService.deleteStashedElementsOlderThanDays(30); // delete all stashed elements older than 30 days
ZonedDateTime endZonedDateTime = ZonedDateTime.now(ZoneOffset.UTC);
LOGGER.info("Cleaning cases cron finished execution at {}", endZonedDateTime);
}
}
4 changes: 4 additions & 0 deletions src/main/resources/config/application.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
spring:
application:
name: explore-server

# At 01:00 AM every day.
cleaning-stash-cron: "0 0 1 * * *"

51 changes: 50 additions & 1 deletion src/test/java/org/gridsuite/explore/server/ExploreTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
Expand Down Expand Up @@ -63,6 +66,8 @@ public class ExploreTest {
private static final UUID CASE_UUID = UUID.randomUUID();
private static final UUID NON_EXISTING_CASE_UUID = UUID.randomUUID();
private static final UUID PARENT_DIRECTORY_UUID = UUID.randomUUID();

private static final UUID DIRECTORY_UUID = UUID.fromString("3cd7cdc4-5a5d-4970-913e-3e91deeb8c35");
private static final UUID PARENT_DIRECTORY_WITH_ERROR_UUID = UUID.randomUUID();
private static final UUID PRIVATE_STUDY_UUID = UUID.randomUUID();
private static final UUID PUBLIC_STUDY_UUID = UUID.randomUUID();
Expand All @@ -86,11 +91,17 @@ public class ExploreTest {
private final Map<String, Object> modificationSpecificMetadata = Map.of("id", MODIFICATION_UUID, "type", "LOAD_MODIFICATION");

private static final UUID SCRIPT_ID_BASE_FORM_CONTINGENCY_LIST_UUID = UUID.randomUUID();
ElementAttributes contingencyElementAttributes = new ElementAttributes(CONTINGENCY_LIST_UUID, "directory", "CONTINGENCY_LIST", new AccessRightsAttributes(true), USER1, 0, null);

@Autowired
private MockMvc mockMvc;
@Autowired
private DirectoryService directoryService;

@Mock
private DirectoryService directoryServiceMock;
@InjectMocks
private ExploreService exploreServiceMock;
@Autowired
private ContingencyListService contingencyListService;
@Autowired
Expand All @@ -107,6 +118,12 @@ public class ExploreTest {
private ObjectMapper mapper;
private MockWebServer server;

@InjectMocks
private ScheduledCleaner scheduledCleaner;

@Mock
private ExploreService exploreService;

@Before
public void setup() throws IOException {
server = new MockWebServer();
Expand Down Expand Up @@ -141,6 +158,8 @@ public void setup() throws IOException {
String modificationElementAttributesAsString = mapper.writeValueAsString(new ElementAttributes(MODIFICATION_UUID, "one modif", "MODIFICATION", new AccessRightsAttributes(true), USER1, 0L, null));
String modificationInfosAttributesAsString = mapper.writeValueAsString(List.of(modificationSpecificMetadata));
String modificationIdsAsString = mapper.writeValueAsString(Map.of(MODIFICATION_UUID, MODIFICATION_UUID));
String directoryAttributesAsString2 = mapper.writeValueAsString(new ElementAttributes(DIRECTORY_UUID, "directory", "DIRECTORY", new AccessRightsAttributes(true), USER1, 0, null));
String contingencyAttributesStashedAsString = mapper.writeValueAsString(List.of(contingencyElementAttributes));

final Dispatcher dispatcher = new Dispatcher() {
@SneakyThrows
Expand Down Expand Up @@ -261,6 +280,8 @@ public MockResponse dispatch(RecordedRequest request) {
return new MockResponse().setResponseCode(200).addHeader("Content-Type", "application/json; charset=utf-8");
} else if (path.matches("/v1/elements/" + PARENT_DIRECTORY_UUID)) {
return new MockResponse().setBody(directoryAttributesAsString).setResponseCode(200).addHeader("Content-Type", "application/json; charset=utf-8");
} else if (path.matches("/v1/elements/" + DIRECTORY_UUID)) {
return new MockResponse().setBody(directoryAttributesAsString2).setResponseCode(200).addHeader("Content-Type", "application/json; charset=utf-8");
} else if (path.matches("/v1/filters/metadata[?]ids=" + FILTER_UUID)) {
return new MockResponse().setBody(listOfFilterAttributesAsString.replace("elementUuid", "id")).setResponseCode(200).addHeader("Content-Type", "application/json; charset=utf-8");
} else if (path.matches("/v1/cases/metadata[?]ids=" + CASE_UUID)) {
Expand All @@ -270,6 +291,9 @@ public MockResponse dispatch(RecordedRequest request) {
} else if (path.matches("/v1/studies/metadata[?]ids=" + PRIVATE_STUDY_UUID)) {
return new MockResponse().setBody(listOfPrivateStudyAttributesAsString.replace("elementUuid", "id")).setResponseCode(200)
.addHeader("Content-Type", "application/json; charset=utf-8");
} else if (path.matches("/v1/elements/stashed\\?daysAgo=.*")) {
return new MockResponse().setBody(contingencyAttributesStashedAsString).setResponseCode(200)
.addHeader("Content-Type", "application/json; charset=utf-8");
}
} else if ("DELETE".equals(request.getMethod())) {
if (path.matches("/v1/filters/" + FILTER_UUID)) {
Expand Down Expand Up @@ -298,7 +322,7 @@ public MockResponse dispatch(RecordedRequest request) {
return new MockResponse().setResponseCode(200);
} else if (path.matches("/v1/parameters/" + PARAMETERS_UUID)) {
return new MockResponse().setResponseCode(200);
} else if (path.matches("\\/v1\\/elements\\?ids=([^,]+,){2,}[^,]+$")) {
} else if (path.matches("\\/v1\\/elements\\?ids=([^,]+,?)+$")) {
return new MockResponse().setResponseCode(200);
}
return new MockResponse().setResponseCode(404);
Expand Down Expand Up @@ -698,4 +722,29 @@ public void testGetModificationMetadata() {
assertEquals(1, elementsMetadata.size());
assertEquals(mapper.writeValueAsString(elementsMetadata.get(0)), expectedResult);
}

@Test
public void testDeleteStashedExpired() {
scheduledCleaner.deleteStashedExpired();
Mockito.verify(exploreService).deleteStashedElementsOlderThanDays(30);
}

@Test
public void testDeleteStashedElementsOlderThanDaysWithNonEmptyList() {
Mockito.when(directoryServiceMock.getStashedElementInfos(Mockito.anyInt())).thenReturn(List.of(contingencyElementAttributes));

exploreServiceMock.deleteStashedElementsOlderThanDays(30);

Mockito.verify(directoryServiceMock, Mockito.atLeastOnce()).deleteElementByElementAttribute(Mockito.any(ElementAttributes.class), Mockito.anyString());
Mockito.verify(directoryServiceMock, Mockito.atLeastOnce()).deleteDirectoryElements(Mockito.anyList(), Mockito.anyString());
}

@Test
public void testGetStashedElementInfos() {
List<ElementAttributes> elementAttributes = directoryService.getStashedElementInfos(30);
assertEquals(1, elementAttributes.size());
assertEquals(CONTINGENCY_LIST_UUID, elementAttributes.get(0).getElementUuid());
assertEquals(USER1, elementAttributes.get(0).getOwner());

}
}
Loading