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

MARP-473 Update installation count #23

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
@@ -1,14 +1,12 @@
package com.axonivy.market.controller;

import com.axonivy.market.model.MavenArtifactVersionModel;
import com.axonivy.market.service.ProductService;
import com.axonivy.market.service.VersionService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

Expand All @@ -17,10 +15,11 @@
@RestController
@RequestMapping(PRODUCT_DETAILS)
public class ProductDetailsController {
private final VersionService service;

public ProductDetailsController(VersionService service) {
this.service = service;
private final VersionService versionService;
private final ProductService productService;
public ProductDetailsController(VersionService versionService, ProductService productService) {
this.versionService = versionService;
this.productService = productService;
}

@GetMapping("/{id}")
Expand All @@ -33,8 +32,15 @@ public ResponseEntity<Object> findProduct(@PathVariable("id") String key,
public ResponseEntity<List<MavenArtifactVersionModel>> findProductVersionsById(@PathVariable("id") String id,
@RequestParam(name = "isShowDevVersion") boolean isShowDevVersion,
@RequestParam(name = "designerVersion", required = false) String designerVersion) {
List<MavenArtifactVersionModel> models = service.getArtifactsAndVersionToDisplay(id, isShowDevVersion,
List<MavenArtifactVersionModel> models = versionService.getArtifactsAndVersionToDisplay(id, isShowDevVersion,
designerVersion);
return new ResponseEntity<>(models, HttpStatus.OK);
}

@Operation(summary = "increase installation count by 1", description = "increase installation count by 1")
@PutMapping("/installationcount/{key}")
public ResponseEntity<Integer> syncInstallationCount(@PathVariable("key") String key) {
int result = productService.updateInstallationCountForProduct(key);
return new ResponseEntity<>(result, HttpStatus.OK);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.List;

import com.axonivy.market.github.model.MavenArtifact;
import lombok.*;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.data.annotation.Id;
Expand All @@ -15,15 +16,11 @@
import com.axonivy.market.model.MultilingualismValue;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Document(PRODUCT)
public class Product implements Serializable {

Expand Down Expand Up @@ -53,10 +50,11 @@ public class Product implements Serializable {
private String compatibility;
private Boolean validate;
private Boolean contactUs;
private Integer installationCount;
private int installationCount;
private Date newestPublishedDate;
private String newestReleaseVersion;
private List<MavenArtifact> artifacts;
private Boolean synchronizedInstallationCount;

@Override
public int hashCode() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ public interface ProductService {
Page<Product> findProducts(String type, String keyword, String language, Pageable pageable);

boolean syncLatestDataFromMarketRepo();

int updateInstallationCountForProduct(String key);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,22 @@

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.kohsuke.github.GHCommit;
import org.kohsuke.github.GHContent;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHTag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
Expand Down Expand Up @@ -53,6 +58,10 @@ public class ProductServiceImpl implements ProductService {

private GHCommit lastGHCommit;
private GitHubRepoMeta marketRepoMeta;
private final ObjectMapper mapper = new ObjectMapper();

@Value("${synchronized.installation.counts.path}")
private String installationCountPath;

public ProductServiceImpl(ProductRepository productRepository, GHAxonIvyMarketRepoService axonIvyMarketRepoService,
GitHubRepoMetaRepository gitHubRepoMetaRepository, GitHubService gitHubService) {
Expand Down Expand Up @@ -103,6 +112,35 @@ public boolean syncLatestDataFromMarketRepo() {
return isAlreadyUpToDate;
}

@Override
public int updateInstallationCountForProduct(String key) {
return productRepository.findById(key).map(product -> {
log.info("updating installation count for product {}", key);
if (!BooleanUtils.isTrue(product.getSynchronizedInstallationCount())) {
syncInstallationCountWithProduct(product);
}
product.setInstallationCount(product.getInstallationCount() + 1);
return productRepository.save(product);
}).map(Product::getInstallationCount).orElse(0);
}

private void syncInstallationCountWithProduct(Product product) {
log.info("synchronizing installation count for product");
try {
String installationCounts = Files.readString(Paths.get(installationCountPath));
Map<String, Integer> mapping = mapper.readValue(installationCounts, HashMap.class);
List<String> keyList = mapping.keySet().stream().toList();
if (keyList.contains(product.getId())) {
product.setInstallationCount(mapping.get(product.getId()));
}
product.setSynchronizedInstallationCount(true);
log.info("synchronized installation count for products");
} catch (IOException ex) {
log.error(ex.getMessage());
throw new RuntimeException(ex);
}
}

private void syncRepoMetaDataStatus() {
if (lastGHCommit == null) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
market.cors.allowed.origin.patterns=http://localhost:[*], http://10.193.8.78:[*], http://marketplace.server.ivy-cloud.com:[*]
market.cors.allowed.origin.maxAge=3600
synchronized.installation.counts.path=D:/work/Document for RICOH/Credentials/market-installations.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.axonivy.market.controller;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;

import com.axonivy.market.model.MavenArtifactVersionModel;
import com.axonivy.market.service.ProductService;
import com.axonivy.market.service.VersionService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
Expand All @@ -23,6 +25,9 @@ class ProductDetailsControllerTest {
@InjectMocks
private ProductDetailsController productDetailsController;

@Mock
private ProductService productService;

@Mock
VersionService versionService;

Expand All @@ -35,10 +40,19 @@ void testFindProduct() {
@Test
void testFindProductVersionsById(){
List<MavenArtifactVersionModel> models = List.of(new MavenArtifactVersionModel());
Mockito.when(versionService.getArtifactsAndVersionToDisplay(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn(models);
when(versionService.getArtifactsAndVersionToDisplay(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString())).thenReturn(models);
ResponseEntity<List<MavenArtifactVersionModel>> result = productDetailsController.findProductVersionsById("protal", true, "10.0.1");
Assertions.assertEquals(HttpStatus.OK, result.getStatusCode());
Assertions.assertEquals(1, Objects.requireNonNull(result.getBody()).size());
Assertions.assertEquals(models, result.getBody());
}

@Test
public void testSyncInstallationCount() throws Exception {
when(productService.updateInstallationCountForProduct("google-maps-connector")).thenReturn(1);

var result = productDetailsController.syncInstallationCount("google-maps-connector");

assertEquals(1, result.getBody());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,21 @@
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

Expand All @@ -27,14 +32,19 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.kohsuke.github.GHCommit;
import org.kohsuke.github.GHContent;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.test.util.ReflectionTestUtils;

import com.axonivy.market.constants.GitHubConstants;
import com.axonivy.market.entity.GitHubRepoMeta;
Expand Down Expand Up @@ -76,6 +86,9 @@ class ProductServiceImplTest {
@Mock
private GitHubService gitHubService;

@Captor
ArgumentCaptor<Product> argumentCaptor = ArgumentCaptor.forClass(Product.class);

@InjectMocks
private ProductServiceImpl productService;

Expand All @@ -84,6 +97,50 @@ public void setup() {
mockResultReturn = createPageProductsMock();
}

@Test
public void testUpdateInstallationCount() {
// prepare
Mockito.when(productRepository.findById("google-maps-connector")).thenReturn(Optional.of(mockProduct()));

// exercise
productService.updateInstallationCountForProduct("google-maps-connector");

// Verify
verify(productRepository).save(argumentCaptor.capture());
int updatedInstallationCount = argumentCaptor.getValue().getInstallationCount();

assertEquals(1, updatedInstallationCount);
verify(productRepository, times(1)).findById(Mockito.anyString());
verify(productRepository, times(1)).save(Mockito.any());
}

@Test
void testSyncInstallationCountWithProduct() throws Exception {
// Mock data
ReflectionTestUtils.setField(productService, "installationCountPath", "path/to/installationCount.json");
Product product = mockProduct();
product.setSynchronizedInstallationCount(false);
Mockito.when(productRepository.findById("google-maps-connector")).thenReturn(Optional.of(product));
Mockito.when(productRepository.save(any())).thenReturn(product);
// Mock the behavior of Files.readString and ObjectMapper.readValue
String installationCounts = "{\"google-maps-connector\": 10}";
try (MockedStatic<Files> filesMockedStatic = mockStatic(Files.class)) {
when(Files.readString(Paths.get("path/to/installationCount.json"))).thenReturn(installationCounts);
// Call the method
int result = productService.updateInstallationCountForProduct("google-maps-connector");

// Verify the results
assertEquals(11, result);
assertEquals(true, product.getSynchronizedInstallationCount());
assertTrue(product.getSynchronizedInstallationCount());
}
}

private Product mockProduct() {
return Product.builder().id("google-maps-connector").language("English")
.synchronizedInstallationCount(true).build();
}

@Test
void testFindProducts() {
langague = "en";
Expand Down Expand Up @@ -282,4 +339,5 @@ private GHContent mockGHContentAsMetaJSON() {
when(mockGHContent.getName()).thenReturn(META_FILE);
return mockGHContent;
}

}
Loading