Hibernate support (#2147)

* Hibernate support

---------

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2024-12-16 16:08:07 +02:00
committed by GitHub
parent af50e8c938
commit db3ac7f2dd
51 changed files with 1397 additions and 704 deletions

View File

@@ -1,88 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.hawkbit.repository.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.sql.SQLException;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.PersistenceException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.junit.jupiter.api.Test;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.UncategorizedDataAccessException;
/**
* Mapping tests for {@link HawkbitEclipseLinkJpaDialect}.
*/
@Feature("Unit Tests - Repository")
@Story("Exception handling")
public class HawkBitEclipseLinkJpaDialectTest {
private final HawkbitEclipseLinkJpaDialect hawkBitEclipseLinkJpaDialectUnderTest = new HawkbitEclipseLinkJpaDialect();
@Test
@Description("Use Case: PersistenceException that can be mapped by EclipseLinkJpaDialect into corresponding DataAccessException.")
public void jpaOptimisticLockExceptionIsConcurrencyFailureException() {
assertThat(
hawkBitEclipseLinkJpaDialectUnderTest.translateExceptionIfPossible(mock(OptimisticLockException.class)))
.isInstanceOf(ConcurrencyFailureException.class);
}
@Test
@Description("Use Case: PersistenceException that could not be mapped by EclipseLinkJpaDialect directly but "
+ "instead is wrapped into JpaSystemException. Cause of PersistenceException is an SQLException.")
public void jpaSystemExceptionWithSqlDeadLockExceptionIsConcurrencyFailureException() {
final PersistenceException persEception = mock(PersistenceException.class);
when(persEception.getCause()).thenReturn(new SQLException("simulated transaction ER_LOCK_DEADLOCK", "40001"));
assertThat(hawkBitEclipseLinkJpaDialectUnderTest.translateExceptionIfPossible(persEception))
.isInstanceOf(ConcurrencyFailureException.class);
}
@Test
@Description("Use Case: PersistenceException that could not be mapped by EclipseLinkJpaDialect directly but instead is wrapped"
+ " into JpaSystemException. Cause of PersistenceException is not an SQLException.")
public void jpaSystemExceptionWithNumberFormatExceptionIsNull() {
final PersistenceException persEception = mock(PersistenceException.class);
when(persEception.getCause()).thenReturn(new NumberFormatException());
assertThat(hawkBitEclipseLinkJpaDialectUnderTest.translateExceptionIfPossible(persEception))
.isInstanceOf(UncategorizedDataAccessException.class);
}
@Test
@Description("Use Case: RuntimeException that could not be mapped by EclipseLinkJpaDialect directly. Cause of "
+ "RuntimeException is an SQLException.")
public void runtimeExceptionWithSqlDeadLockExceptionIsConcurrencyFailureException() {
final RuntimeException persEception = mock(RuntimeException.class);
when(persEception.getCause()).thenReturn(new SQLException("simulated transaction ER_LOCK_DEADLOCK", "40001"));
assertThat(hawkBitEclipseLinkJpaDialectUnderTest.translateExceptionIfPossible(persEception))
.isInstanceOf(ConcurrencyFailureException.class);
}
@Test
@Description("Use Case: RuntimeException that could not be mapped by EclipseLinkJpaDialect directly. Cause of "
+ "RuntimeException is not an SQLException.")
public void runtimeExceptionWithNumberFormatExceptionIsNull() {
final RuntimeException persEception = mock(RuntimeException.class);
when(persEception.getCause()).thenReturn(new NumberFormatException());
assertThat(hawkBitEclipseLinkJpaDialectUnderTest.translateExceptionIfPossible(persEception)).isNull();
}
}

View File

@@ -37,8 +37,7 @@ class ActionTest extends AbstractJpaIntegrationTest {
@Test
@Description("Ensures that timeforced moded switch from soft to forces after defined timeframe.")
void timeforcedHitNewHasCodeIsGenerated() {
void timeForcedHitNewHasCodeIsGenerated() {
// current time + 1 seconds
final long sleepTime = 1000;
final long timeForceTimeAt = System.currentTimeMillis() + sleepTime;
@@ -48,8 +47,7 @@ class ActionTest extends AbstractJpaIntegrationTest {
assertThat(timeforcedAction.isForcedOrTimeForced()).isFalse();
// wait until timeforce time is hit
Awaitility.await().atMost(Duration.ofSeconds(2)).pollInterval(Duration.ofMillis(100))
.until(timeforcedAction::isForcedOrTimeForced);
Awaitility.await().atMost(Duration.ofSeconds(2)).pollInterval(Duration.ofMillis(100)).until(timeforcedAction::isForcedOrTimeForced);
}
@Test
@@ -57,12 +55,11 @@ class ActionTest extends AbstractJpaIntegrationTest {
void testActionTypeConvert() {
final long id = createAction().getId();
for (final ActionType actionType : ActionType.values()) {
final JpaAction action = actionRepository
.findById(id).orElseThrow(() -> new IllegalStateException("Action not found"));
final JpaAction action = actionRepository.findById(id).orElseThrow(() -> new IllegalStateException("Action not found"));
action.setActionType(actionType);
actionRepository.save(action);
assertThat(actionRepository.findById(id).orElseThrow(() -> new IllegalStateException("Action not found"))
.getActionType()).isEqualTo(actionType);
assertThat(actionRepository.findById(id).orElseThrow(() -> new IllegalStateException("Action not found")).getActionType())
.isEqualTo(actionType);
}
}
@@ -71,12 +68,11 @@ class ActionTest extends AbstractJpaIntegrationTest {
void testStatusConvert() {
final long id = createAction().getId();
for (final Status status : Status.values()) {
final JpaAction action = actionRepository
.findById(id).orElseThrow(() -> new IllegalStateException("Action not found"));
final JpaAction action = actionRepository.findById(id).orElseThrow(() -> new IllegalStateException("Action not found"));
action.setStatus(status);
actionRepository.save(action);
assertThat(actionRepository.findById(id).orElseThrow(() -> new IllegalStateException("Action not found"))
.getStatus()).isEqualTo(status);
assertThat(actionRepository.findById(id).orElseThrow(() -> new IllegalStateException("Action not found")).getStatus())
.isEqualTo(status);
}
}
@@ -113,4 +109,4 @@ class ActionTest extends AbstractJpaIntegrationTest {
action.setActive(true);
return actionRepository.save(action);
}
}
}

View File

@@ -16,7 +16,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
@@ -36,7 +35,6 @@ import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.event.remote.SoftwareModuleDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException;
import org.eclipse.hawkbit.repository.exception.FileSizeQuotaExceededException;
@@ -47,7 +45,6 @@ import org.eclipse.hawkbit.repository.exception.InvalidSHA256HashException;
import org.eclipse.hawkbit.repository.exception.StorageQuotaExceededException;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.jpa.RandomGeneratedInputStream;
import org.eclipse.hawkbit.repository.jpa.model.JpaArtifact;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.ArtifactUpload;
@@ -73,53 +70,46 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule module = testdataFactory.createSoftwareModuleOs();
assertThat(artifactManagement.get(NOT_EXIST_IDL)).isNotPresent();
assertThat(artifactManagement.getByFilenameAndSoftwareModule(NOT_EXIST_ID, module.getId()).isPresent())
.isFalse();
assertThat(artifactManagement.getByFilenameAndSoftwareModule(NOT_EXIST_ID, module.getId())).isEmpty();
assertThat(artifactManagement.findFirstBySHA1(NOT_EXIST_ID)).isNotPresent();
assertThat(artifactManagement.loadArtifactBinary(NOT_EXIST_ID, module.getId(), module.isEncrypted()))
.isNotPresent();
assertThat(artifactManagement.loadArtifactBinary(NOT_EXIST_ID, module.getId(), module.isEncrypted())).isEmpty();
}
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({ @Expect(type = SoftwareModuleDeletedEvent.class, count = 0) })
void entityQueriesReferringToNotExistingEntitiesThrowsException() throws URISyntaxException {
@Description("Verifies that management queries react as specfied on calls for non existing entities by means of " +
"throwing EntityNotFoundException.")
@ExpectEvents()
void entityQueriesReferringToNotExistingEntitiesThrowsException() {
final String artifactData = "test";
final int artifactSize = artifactData.length();
verifyThrownExceptionBy(
() -> artifactManagement.create(new ArtifactUpload(IOUtils.toInputStream(artifactData, "UTF-8"),
NOT_EXIST_IDL, "xxx", null, null, null, false, null, artifactSize)),
"SoftwareModule");
() -> artifactManagement.create(new ArtifactUpload(
IOUtils.toInputStream(artifactData, "UTF-8"),
NOT_EXIST_IDL, "xxx", null, null, null, false, null, artifactSize)), "SoftwareModule");
verifyThrownExceptionBy(
() -> artifactManagement.create(new ArtifactUpload(IOUtils.toInputStream(artifactData, "UTF-8"),
NOT_EXIST_IDL, "xxx", null, null, null, false, null, artifactSize)),
"SoftwareModule");
() -> artifactManagement.create(new ArtifactUpload(
IOUtils.toInputStream(artifactData, "UTF-8"),
NOT_EXIST_IDL, "xxx", null, null, null, false, null, artifactSize)), "SoftwareModule");
verifyThrownExceptionBy(() -> artifactManagement.delete(NOT_EXIST_IDL), "Artifact");
verifyThrownExceptionBy(() -> artifactManagement.findBySoftwareModule(PAGE, NOT_EXIST_IDL), "SoftwareModule");
assertThat(artifactManagement.getByFilename(NOT_EXIST_ID).isPresent()).isFalse();
assertThat(artifactManagement.getByFilename(NOT_EXIST_ID)).isEmpty();
verifyThrownExceptionBy(() -> artifactManagement.getByFilenameAndSoftwareModule("xxx", NOT_EXIST_IDL),
"SoftwareModule");
verifyThrownExceptionBy(() -> artifactManagement.getByFilenameAndSoftwareModule("xxx", NOT_EXIST_IDL), "SoftwareModule");
}
@Test
@Description("Test if a local artifact can be created by API including metadata.")
void createArtifact() throws IOException {
// check baseline
assertThat(softwareModuleRepository.findAll()).hasSize(0);
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(softwareModuleRepository.findAll()).isEmpty();
assertThat(artifactRepository.findAll()).isEmpty();
final JpaSoftwareModule sm = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
final JpaSoftwareModule sm = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 3", "version 3"));
final int artifactSize = 5 * 1024;
@@ -129,49 +119,43 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final InputStream inputStream2 = new ByteArrayInputStream(randomBytes);
final InputStream inputStream3 = new ByteArrayInputStream(randomBytes);
final InputStream inputStream4 = new ByteArrayInputStream(randomBytes)) {
final Artifact artifact1 = createArtifactForSoftwareModule("file1", sm.getId(), artifactSize, inputStream1);
createArtifactForSoftwareModule("file11", sm.getId(), artifactSize, inputStream2);
createArtifactForSoftwareModule("file12", sm.getId(), artifactSize, inputStream3);
final Artifact artifact2 = createArtifactForSoftwareModule("file2", sm2.getId(), artifactSize,
inputStream4);
final Artifact artifact2 = createArtifactForSoftwareModule("file2", sm2.getId(), artifactSize, inputStream4);
assertThat(artifact1).isInstanceOf(Artifact.class);
assertThat(artifact1.getSoftwareModule().getId()).isEqualTo(sm.getId());
assertThat(artifact2.getSoftwareModule().getId()).isEqualTo(sm2.getId());
assertThat(((JpaArtifact) artifact1).getFilename()).isEqualTo("file1");
assertThat(((JpaArtifact) artifact1).getSha1Hash()).isNotNull();
assertThat(artifact1.getFilename()).isEqualTo("file1");
assertThat(artifact1.getSha1Hash()).isNotNull();
assertThat(artifact1).isNotEqualTo(artifact2);
assertThat(((JpaArtifact) artifact1).getSha1Hash()).isEqualTo(((JpaArtifact) artifact2).getSha1Hash());
assertThat(artifact1.getSha1Hash()).isEqualTo(artifact2.getSha1Hash());
assertThat(artifactManagement.getByFilename("file1").get().getSha1Hash())
.isEqualTo(HashGeneratorUtils.generateSHA1(randomBytes));
assertThat(artifactManagement.getByFilename("file1").get().getMd5Hash())
.isEqualTo(HashGeneratorUtils.generateMD5(randomBytes));
assertThat(artifactManagement.getByFilename("file1").get().getSha256Hash())
.isEqualTo(HashGeneratorUtils.generateSHA256(randomBytes));
assertThat(artifactManagement.getByFilename("file1").get().getSha1Hash()).isEqualTo(HashGeneratorUtils.generateSHA1(randomBytes));
assertThat(artifactManagement.getByFilename("file1").get().getMd5Hash()).isEqualTo(HashGeneratorUtils.generateMD5(randomBytes));
assertThat(artifactManagement.getByFilename("file1").get().getSha256Hash()).isEqualTo(
HashGeneratorUtils.generateSHA256(randomBytes));
assertThat(artifactRepository.findAll()).hasSize(4);
assertThat(softwareModuleRepository.findAll()).hasSize(3);
assertThat(softwareModuleManagement.get(sm.getId()).get().getArtifacts()).hasSize(3);
}
}
@Test
@Description("Verifies that artifact management does not create artifacts with illegal filename.")
void entityQueryWithIllegalFilenameThrowsException() throws URISyntaxException {
void entityQueryWithIllegalFilenameThrowsException() {
final String illegalFilename = "<img src=ernw onerror=alert(1)>.xml";
final String artifactData = "test";
final int artifactSize = artifactData.length();
final long smID = softwareModuleRepository.save(new JpaSoftwareModule(osType, "smIllegalFilenameTest", "1.0"))
.getId();
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(
() -> artifactManagement.create(new ArtifactUpload(IOUtils.toInputStream(artifactData, "UTF-8"), smID,
illegalFilename, false, artifactSize)));
assertThat(softwareModuleManagement.get(smID).get().getArtifacts()).hasSize(0);
final long smID = softwareModuleRepository.save(new JpaSoftwareModule(osType, "smIllegalFilenameTest", "1.0")).getId();
final ArtifactUpload artifactUpload = new ArtifactUpload(
IOUtils.toInputStream(artifactData, "UTF-8"), smID, illegalFilename, false, artifactSize);
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> artifactManagement.create(artifactUpload));
assertThat(softwareModuleManagement.get(smID).get().getArtifacts()).isEmpty();
}
@Test
@@ -206,9 +190,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that the quota specifying the maximum artifact storage is enforced (across software modules).")
void createArtifactsUntilStorageQuotaIsExceeded() throws IOException {
// create as many small artifacts as possible w/o violating the storage
// quota
// create as many small artifacts as possible w/o violating the storage quota
final long maxBytes = quotaManagement.getMaxArtifactStorage();
final List<Long> artifactIds = new ArrayList<>();
@@ -221,99 +203,78 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
// upload one more artifact to trigger the quota exceeded error
final JpaSoftwareModule sm = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "smd" + numArtifacts, "1.0"));
final long smId = softwareModuleRepository.save(new JpaSoftwareModule(osType, "smd" + numArtifacts, "1.0")).getId();
assertThatExceptionOfType(StorageQuotaExceededException.class)
.isThrownBy(() -> createArtifactForSoftwareModule("file" + numArtifacts, sm.getId(), artifactSize));
.isThrownBy(() -> createArtifactForSoftwareModule("file" + numArtifacts, smId, artifactSize));
// delete one of the artifacts
artifactManagement.delete(artifactIds.get(0));
// now we should be able to create an artifact again
createArtifactForSoftwareModule("fileXYZ", sm.getId(), artifactSize);
createArtifactForSoftwareModule("fileXYZ", smId, artifactSize);
}
@Test
@Description("Verifies that you cannot create artifacts which exceed the configured maximum size.")
void createArtifactFailsIfTooLarge() {
// create a software module
final JpaSoftwareModule sm1 = softwareModuleRepository.save(new JpaSoftwareModule(osType, "sm1", "1.0"));
final long smId = softwareModuleRepository.save(new JpaSoftwareModule(osType, "sm1", "1.0")).getId();
// create an artifact that exceeds the configured quota
final long maxSize = quotaManagement.getMaxArtifactSize();
final int artifactSize = Math.toIntExact(quotaManagement.getMaxArtifactSize()) + 8;
assertThatExceptionOfType(FileSizeQuotaExceededException.class)
.isThrownBy(() -> createArtifactForSoftwareModule("file", sm1.getId(), Math.toIntExact(maxSize) + 8));
.isThrownBy(() -> createArtifactForSoftwareModule("file", smId, artifactSize));
}
@Test
@Description("Tests hard delete directly on repository.")
void hardDeleteSoftwareModule() throws IOException {
final JpaSoftwareModule sm = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
createArtifactForSoftwareModule("file1", sm.getId(), 5 * 1024);
assertThat(artifactRepository.findAll()).hasSize(1);
softwareModuleRepository.deleteAll();
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(artifactRepository.findAll()).isEmpty();
}
/**
* Test method for
* {@link org.eclipse.hawkbit.repository.ArtifactManagement#delete(long)} .
*
* @throws IOException
* Test method for {@link org.eclipse.hawkbit.repository.ArtifactManagement#delete(long)}.
*/
@Test
@Description("Tests the deletion of a local artifact including metadata.")
void deleteArtifact() throws IOException {
final JpaSoftwareModule sm = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
final JpaSoftwareModule sm = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
assertThat(artifactRepository.findAll()).isEmpty();
final int artifactSize = 5 * 1024;
try (final InputStream inputStream1 = new RandomGeneratedInputStream(artifactSize);
final InputStream inputStream2 = new RandomGeneratedInputStream(artifactSize)) {
final Artifact artifact1 = createArtifactForSoftwareModule("file1", sm.getId(), artifactSize, inputStream1);
final Artifact artifact2 = createArtifactForSoftwareModule("file2", sm2.getId(), artifactSize,
inputStream2);
final Artifact artifact2 = createArtifactForSoftwareModule("file2", sm2.getId(), artifactSize, inputStream2);
assertThat(artifactRepository.findAll()).hasSize(2);
assertThat(artifact1.getId()).isNotNull();
assertThat(artifact2.getId()).isNotNull();
assertThat(((JpaArtifact) artifact1).getSha1Hash()).isNotEqualTo(((JpaArtifact) artifact2).getSha1Hash());
assertThat(artifact1.getSha1Hash()).isNotEqualTo(artifact2.getSha1Hash());
assertThat(
binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash()))
.isNotNull();
assertThat(
binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact2.getSha1Hash()))
.isNotNull();
assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash())).isNotNull();
assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact2.getSha1Hash())).isNotNull();
artifactManagement.delete(artifact1.getId());
assertThat(artifactRepository.findAll()).hasSize(1);
assertThat(
binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash()))
.isNull();
assertThat(
binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact2.getSha1Hash()))
.isNotNull();
assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash())).isNull();
assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact2.getSha1Hash())).isNotNull();
artifactManagement.delete(artifact2.getId());
assertThat(
binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact2.getSha1Hash()))
.isNull();
assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact2.getSha1Hash())).isNull();
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(artifactRepository.findAll()).isEmpty();
}
}
@@ -321,10 +282,8 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
@Description("Test the deletion of an artifact metadata where the binary is still linked to another metadata element. " +
"The expected result is that the metadata is deleted but the binary kept.")
void deleteDuplicateArtifacts() throws IOException {
final JpaSoftwareModule sm = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
final JpaSoftwareModule sm = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
final int artifactSize = 5 * 1024;
final byte[] randomBytes = randomBytes(artifactSize);
@@ -347,49 +306,44 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
artifactManagement.delete(artifact2.getId());
assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash())).isNull();
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(artifactRepository.findAll()).isEmpty();
}
}
@Test
@Description("Verifies that you cannot delete an artifact which exists with the same hash, in the same tenant and the SoftwareModule is not deleted .")
void deleteArtifactWithSameHashAndSoftwareModuleIsNotDeletedInSameTenants() throws IOException {
final JpaSoftwareModule sm = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository
.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
final JpaSoftwareModule sm = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
final int artifactSize = 5 * 1024;
final byte[] randomBytes = randomBytes(artifactSize);
try (final InputStream inputStream1 = new ByteArrayInputStream(randomBytes);
final InputStream inputStream2 = new ByteArrayInputStream(randomBytes)) {
final Artifact artifact1 = createArtifactForSoftwareModule("file1", sm.getId(), artifactSize, inputStream1);
final Artifact artifact2 = createArtifactForSoftwareModule("file2", sm2.getId(), artifactSize,
inputStream2);
final Artifact artifact2 = createArtifactForSoftwareModule("file2", sm2.getId(), artifactSize, inputStream2);
assertEqualFileContents(
artifactManagement.loadArtifactBinary(artifact2.getSha1Hash(), sm2.getId(), sm2.isEncrypted()),
randomBytes);
artifactManagement.loadArtifactBinary(artifact2.getSha1Hash(), sm2.getId(), sm2.isEncrypted()), randomBytes);
assertThat(artifactRepository.findAll()).hasSize(2);
assertThat(artifact1.getSha1Hash()).isEqualTo(artifact2.getSha1Hash());
assertThat(artifactRepository.countBySha1HashAndTenantAndSoftwareModuleDeletedIsFalse(
artifact1.getSha1Hash(), artifact1.getTenant())).isGreaterThan(1);
artifact1.getSha1Hash(), artifact1.getTenant()))
.isGreaterThan(1);
artifactRepository.deleteById(artifact1.getId());
assertThat(artifactRepository.findAll()).hasSize(1);
assertThat(artifactRepository.countBySha1HashAndTenantAndSoftwareModuleDeletedIsFalse(
artifact2.getSha1Hash(), artifact2.getTenant())).isLessThanOrEqualTo(1);
artifact2.getSha1Hash(), artifact2.getTenant()))
.isLessThanOrEqualTo(1);
artifactRepository.deleteById(artifact2.getId());
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(artifactRepository.findAll()).isEmpty();
}
}
@@ -427,7 +381,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
try (final InputStream inputStream = new RandomGeneratedInputStream(artifactSize)) {
final Artifact artifact = createArtifactForSoftwareModule(
"file1", testdataFactory.createSoftwareModuleOs().getId(), artifactSize, inputStream);
assertThat(artifactManagement.get(artifact.getId()).get()).isEqualTo(artifact);
assertThat(artifactManagement.get(artifact.getId())).contains(artifact);
}
}
@@ -440,8 +394,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule smOs = testdataFactory.createSoftwareModuleOs();
final Artifact artifact = createArtifactForSoftwareModule("file1", smOs.getId(), artifactSize, input);
assertEqualFileContents(
artifactManagement.loadArtifactBinary(artifact.getSha1Hash(), smOs.getId(), smOs.isEncrypted()),
randomBytes);
artifactManagement.loadArtifactBinary(artifact.getSha1Hash(), smOs.getId(), smOs.isEncrypted()), randomBytes);
}
}
@@ -492,24 +445,25 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final DbArtifactHash artifactHashes = calcHashes(testData);
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUploadWithInvalidSha1 = new ArtifactUpload(inputStream, sm.getId(),
"test-file", artifactHashes.getMd5(), "sha1", artifactHashes.getSha256(), false, null,
testData.length);
final ArtifactUpload artifactUploadWithInvalidSha1 = new ArtifactUpload(
inputStream, sm.getId(), "test-file",
artifactHashes.getMd5(), "sha1", artifactHashes.getSha256(), false, null, testData.length);
assertThatExceptionOfType(InvalidSHA1HashException.class)
.isThrownBy(() -> artifactManagement.create(artifactUploadWithInvalidSha1));
}
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUploadWithInvalidMd5 = new ArtifactUpload(inputStream, sm.getId(), "test-file",
final ArtifactUpload artifactUploadWithInvalidMd5 = new ArtifactUpload(
inputStream, sm.getId(), "test-file",
"md5", artifactHashes.getSha1(), artifactHashes.getSha256(), false, null, testData.length);
assertThatExceptionOfType(InvalidMD5HashException.class)
.isThrownBy(() -> artifactManagement.create(artifactUploadWithInvalidMd5));
}
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUploadWithInvalidSha256 = new ArtifactUpload(inputStream, sm.getId(),
"test-file", artifactHashes.getMd5(), artifactHashes.getSha1(), "sha256", false, null,
testData.length);
final ArtifactUpload artifactUploadWithInvalidSha256 = new ArtifactUpload(
inputStream, sm.getId(), "test-file",
artifactHashes.getMd5(), artifactHashes.getSha1(), "sha256", false, null, testData.length);
assertThatExceptionOfType(InvalidSHA256HashException.class)
.isThrownBy(() -> artifactManagement.create(artifactUploadWithInvalidSha256));
}
@@ -524,17 +478,16 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final DbArtifactHash artifactHashes = calcHashes(testData);
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUpload = new ArtifactUpload(inputStream, sm.getId(), "test-file",
artifactHashes.getMd5(), artifactHashes.getSha1(), artifactHashes.getSha256(), false, null,
testData.length);
final ArtifactUpload artifactUpload = new ArtifactUpload(
inputStream, sm.getId(), "test-file",
artifactHashes.getMd5(), artifactHashes.getSha1(), artifactHashes.getSha256(), false, null, testData.length);
final Artifact createdArtifact = artifactManagement.create(artifactUpload);
assertThat(createdArtifact.getSha1Hash()).isEqualTo(artifactHashes.getSha1());
assertThat(createdArtifact.getMd5Hash()).isEqualTo(artifactHashes.getMd5());
assertThat(createdArtifact.getSha256Hash()).isEqualTo(artifactHashes.getSha256());
}
final Optional<DbArtifact> dbArtifact = artifactManagement.loadArtifactBinary(artifactHashes.getSha1(),
sm.getId(), sm.isEncrypted());
final Optional<DbArtifact> dbArtifact = artifactManagement.loadArtifactBinary(artifactHashes.getSha1(), sm.getId(), sm.isEncrypted());
assertThat(dbArtifact).isPresent();
}
@@ -548,19 +501,19 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final DbArtifactHash artifactHashes = calcHashes(testData);
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUpload = new ArtifactUpload(inputStream, smOs.getId(), "test-file",
artifactHashes.getMd5(), artifactHashes.getSha1(), artifactHashes.getSha256(), false, null,
testData.length);
final ArtifactUpload artifactUpload = new ArtifactUpload(
inputStream, smOs.getId(), "test-file",
artifactHashes.getMd5(), artifactHashes.getSha1(), artifactHashes.getSha256(), false, null, testData.length);
final Artifact artifact = artifactManagement.create(artifactUpload);
assertThat(artifact).isNotNull();
}
final Optional<DbArtifact> dbArtifact = artifactManagement.loadArtifactBinary(artifactHashes.getSha1(),
smOs.getId(), smOs.isEncrypted());
final Optional<DbArtifact> dbArtifact = artifactManagement.loadArtifactBinary(
artifactHashes.getSha1(), smOs.getId(), smOs.isEncrypted());
assertThat(dbArtifact).isPresent();
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload existingArtifactUpload = new ArtifactUpload(inputStream, smApp.getId(), "test-file",
false, testData.length);
final ArtifactUpload existingArtifactUpload = new ArtifactUpload(
inputStream, smApp.getId(), "test-file", false, testData.length);
final Artifact createdArtifact = artifactManagement.create(existingArtifactUpload);
assertThat(createdArtifact.getSha1Hash()).isEqualTo(artifactHashes.getSha1());
assertThat(createdArtifact.getMd5Hash()).isEqualTo(artifactHashes.getMd5());
@@ -594,8 +547,8 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
private Artifact createArtifactForSoftwareModule(final String filename, final long moduleId, final int artifactSize,
final InputStream inputStream) {
private Artifact createArtifactForSoftwareModule(
final String filename, final long moduleId, final int artifactSize, final InputStream inputStream) {
return artifactManagement.create(new ArtifactUpload(inputStream, moduleId, filename, false, artifactSize));
}
@@ -607,8 +560,8 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
return runAsTenant(tenant, () -> testdataFactory.createSoftwareModuleApp());
}
private Artifact createArtifactForTenant(final String tenant, final String artifactData, final long moduleId,
final String filename) throws Exception {
private Artifact createArtifactForTenant(final String tenant, final String artifactData, final long moduleId, final String filename)
throws Exception {
return runAsTenant(tenant, () -> testdataFactory.createArtifact(artifactData, moduleId, filename));
}
@@ -616,12 +569,11 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
assertThat(runAsTenant(tenant, () -> artifactRepository.findAll())).hasSize(count);
}
private void assertEqualFileContents(final Optional<DbArtifact> artifact, final byte[] randomBytes)
throws IOException {
private void assertEqualFileContents(final Optional<DbArtifact> artifact, final byte[] randomBytes) throws IOException {
try (final InputStream inputStream = artifact.get().getFileInputStream()) {
assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(randomBytes), inputStream),
assertTrue(
IOUtils.contentEquals(new ByteArrayInputStream(randomBytes), inputStream),
"The stored binary matches the given binary");
}
}
}
}

View File

@@ -607,17 +607,15 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
void lockDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1");
assertThat(
distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked)
.orElse(true))
distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(true))
.isFalse();
distributionSetManagement.lock(distributionSet.getId());
assertThat(
distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked)
.orElse(false))
distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false))
.isTrue();
// assert software modules are locked
assertThat(distributionSet.getModules().size()).isNotEqualTo(0);
distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::getModules)
distributionSetManagement.getWithDetails(distributionSet.getId()).map(DistributionSet::getModules)
.orElseThrow().forEach(module -> assertThat(module.isLocked()).isTrue());
}
@@ -668,7 +666,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isFalse();
// assert software modules are not unlocked
assertThat(distributionSet.getModules().size()).isNotEqualTo(0);
distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::getModules)
distributionSetManagement.getWithDetails(distributionSet.getId()).map(DistributionSet::getModules)
.orElseThrow().forEach(module -> assertThat(module.isLocked()).isTrue());
}
@@ -688,7 +686,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.as("Attempt to modify a locked DS software modules should throw an exception")
.isThrownBy(() -> distributionSetManagement.assignSoftwareModules(
distributionSet.getId(), List.of(testdataFactory.createSoftwareModule("sm-1").getId())));
assertThat(distributionSetManagement.get(distributionSet.getId()).get().getModules().size())
assertThat(distributionSetManagement.getWithDetails(distributionSet.getId()).get().getModules().size())
.as("Software module shall not be added to a locked DS.")
.isEqualTo(softwareModuleCount);
@@ -697,7 +695,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.as("Attempt to modify a locked DS software modules should throw an exception")
.isThrownBy(() -> distributionSetManagement.unassignSoftwareModule(
distributionSet.getId(), distributionSet.getModules().stream().findFirst().get().getId()));
assertThat(distributionSetManagement.get(distributionSet.getId()).get().getModules().size())
assertThat(distributionSetManagement.getWithDetails(distributionSet.getId()).get().getModules().size())
.as("Software module shall not be removed from a locked DS.")
.isEqualTo(softwareModuleCount);
}
@@ -722,8 +720,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.toList());
// assert that implicit lock locks for every skip tag
skipTags.forEach(skipTag -> {
DistributionSet distributionSetWithSkipTag =
testdataFactory.createDistributionSet("ds-skip-" + skipTag.getName());
DistributionSet distributionSetWithSkipTag = testdataFactory.createDistributionSet("ds-skip-" + skipTag.getName());
distributionSetManagement.assignTag(List.of(distributionSetWithSkipTag.getId()), skipTag.getId());
distributionSetWithSkipTag = distributionSetManagement.get(distributionSetWithSkipTag.getId()).orElseThrow();
// assert that implicit lock isn't applicable for skip tags

View File

@@ -33,7 +33,7 @@ import org.springframework.core.env.Environment;
@Feature("Component Tests - Repository")
@Story("Tenant Configuration Management")
public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest implements EnvironmentAware {
class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest implements EnvironmentAware {
private Environment environment;
@@ -44,7 +44,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Tests that tenant specific configuration can be persisted and in case the tenant does not have specific configuration the default from environment is used instead.")
public void storeTenantSpecificConfigurationAsString() {
void storeTenantSpecificConfigurationAsString() {
final String envPropertyDefault = environment
.getProperty("hawkbit.server.ddi.security.authentication.gatewaytoken.key");
assertThat(envPropertyDefault).isNotNull();
@@ -73,7 +73,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Tests that the tenant specific configuration can be updated")
public void updateTenantSpecificConfiguration() {
void updateTenantSpecificConfiguration() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY;
final String value1 = "firstValue";
final String value2 = "secondValue";
@@ -89,7 +89,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Tests that the tenant specific configuration can be batch updated")
public void batchUpdateTenantSpecificConfiguration() {
void batchUpdateTenantSpecificConfiguration() {
Map<String, Serializable> configuration = new HashMap<>() {{
put(TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY, "token_123");
put(TenantConfigurationKey.ROLLOUT_APPROVAL_ENABLED, true);
@@ -107,7 +107,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Tests that the configuration value can be converted from String to Integer automatically")
public void storeAndUpdateTenantSpecificConfigurationAsBoolean() {
void storeAndUpdateTenantSpecificConfigurationAsBoolean() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_ENABLED;
final Boolean value1 = true;
tenantConfigurationManagement.addOrUpdateConfiguration(configKey, value1);
@@ -119,7 +119,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Tests that the get configuration throws exception in case the value cannot be automatically converted from String to Boolean")
public void wrongTenantConfigurationValueTypeThrowsException() {
void wrongTenantConfigurationValueTypeThrowsException() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_ENABLED;
final String value1 = "thisIsNotABoolean";
@@ -131,7 +131,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Tests that the get configuration throws exception in case the value is the wrong type")
public void batchWrongTenantConfigurationValueTypeThrowsException() {
void batchWrongTenantConfigurationValueTypeThrowsException() {
final Map<String, Serializable> configuration = new HashMap<>() {{
put(TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY, "token_123");
put(TenantConfigurationKey.ROLLOUT_APPROVAL_ENABLED, true);
@@ -155,7 +155,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Tests that a deletion of a tenant specific configuration deletes it from the database.")
public void deleteConfigurationReturnNullConfiguration() {
void deleteConfigurationReturnNullConfiguration() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY;
// gateway token does not have default value so no configuration value should be available
@@ -180,7 +180,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Test that an Exception is thrown, when an integer is stored but a string expected.")
public void storesIntegerWhenStringIsExpected() {
void storesIntegerWhenStringIsExpected() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY;
final Integer wrongDatType = 123;
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDatType))
@@ -190,7 +190,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Test that an Exception is thrown, when an integer is stored but a boolean expected.")
public void storesIntegerWhenBooleanIsExpected() {
void storesIntegerWhenBooleanIsExpected() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED;
final Integer wrongDataType = 123;
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataType))
@@ -200,7 +200,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Test that an Exception is thrown, when an integer is stored as PollingTime.")
public void storesIntegerWhenPollingIntervalIsExpected() {
void storesIntegerWhenPollingIntervalIsExpected() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
final Integer wrongDataType = 123;
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataType))
@@ -210,7 +210,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Test that an Exception is thrown, when an invalid formatted string is stored as PollingTime.")
public void storesWrongFormattedStringAsPollingInterval() {
void storesWrongFormattedStringAsPollingInterval() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
final String wrongFormatted = "wrongFormatted";
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongFormatted))
@@ -220,7 +220,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Test that an Exception is thrown, when an invalid formatted string is stored as PollingTime.")
public void storesTooSmallDurationAsPollingInterval() {
void storesTooSmallDurationAsPollingInterval() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
final String tooSmallDuration = DurationHelper
@@ -232,7 +232,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Stores a correct formatted PollignTime and reads it again.")
public void storesCorrectDurationAsPollingInterval() {
void storesCorrectDurationAsPollingInterval() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
final Duration duration = DurationHelper.getDurationByTimeValues(1, 2, 0);
@@ -246,7 +246,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Request a config value in a wrong Value")
public void requestConfigValueWithWrongType() {
void requestConfigValueWithWrongType() {
assertThatThrownBy(() -> tenantConfigurationManagement.getConfigurationValue(
TenantConfigurationKey.POLLING_TIME_INTERVAL, Serializable.class))
.isInstanceOf(TenantConfigurationValidatorException.class);
@@ -254,7 +254,7 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Verifies that every TenenatConfiguraationKeyName exists only once")
public void verifyThatAllKeysAreDifferent() {
void verifyThatAllKeysAreDifferent() {
final Map<String, Void> keyNames = new HashMap<>();
tenantConfigurationProperties.getConfigurationKeys().forEach(key -> {
if (keyNames.containsKey(key.getKeyName())) {
@@ -266,14 +266,14 @@ public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTes
@Test
@Description("Get TenantConfigurationKeyByName")
public void getTenantConfigurationKeyByName() {
void getTenantConfigurationKeyByName() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
assertThat(tenantConfigurationProperties.fromKeyName(configKey).getKeyName()).isEqualTo(configKey);
}
@Test
@Description("Tenant configuration which is not declared throws exception")
public void storeTenantConfigurationWhichIsNotDeclaredThrowsException() {
void storeTenantConfigurationWhichIsNotDeclaredThrowsException() {
final String configKeyWhichDoesNotExists = "configKeyWhichDoesNotExists";
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKeyWhichDoesNotExists, "value"))
.as("Expected InvalidTenantConfigurationKeyException for tenant configuration key which is not declared")

View File

@@ -9,6 +9,8 @@
*/
package org.eclipse.hawkbit.repository.jpa.rsql;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import jakarta.persistence.EntityManager;
@@ -23,11 +25,9 @@ import cz.jirutka.rsql.parser.ast.Node;
import cz.jirutka.rsql.parser.ast.RSQLOperators;
import cz.jirutka.rsql.parser.ast.RSQLVisitor;
import org.eclipse.hawkbit.repository.RsqlQueryField;
import org.eclipse.hawkbit.repository.jpa.Jpa;
import org.eclipse.hawkbit.repository.rsql.RsqlConfigHolder;
import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.jpa.JpaQuery;
import org.eclipse.persistence.queries.DatabaseQuery;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.util.CollectionUtils;
@@ -40,23 +40,33 @@ public class RSQLToSQL {
this.entityManager = entityManager;
}
public <T, A extends Enum<A> & RsqlQueryField> String toSQL(final Class<T> domainClass, final Class<A> fieldsClass, final String rsql,
final boolean legacyRsqlVisitor) {
return createDbQuery(domainClass, fieldsClass, rsql, legacyRsqlVisitor).getSQLString();
}
public <T, A extends Enum<A> & RsqlQueryField> DatabaseQuery createDbQuery(final Class<T> domainClass, final Class<A> fieldsClass,
final String rsql, final boolean legacyRsqlVisitor) {
public <T, A extends Enum<A> & RsqlQueryField> String toSQL(
final Class<T> domainClass, final Class<A> fieldsClass, final String rsql, final boolean legacyRsqlVisitor) {
final CriteriaQuery<T> query = createQuery(domainClass, fieldsClass, rsql, legacyRsqlVisitor);
final TypedQuery<?> typedQuery = entityManager.createQuery(query);
// executes the query - otherwise the SQL string is not generated
typedQuery.setParameter(PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT, "DEFAULT");
typedQuery.getResultList();
return typedQuery.unwrap(JpaQuery.class).getDatabaseQuery();
if (Jpa.JPA_VENDOR.equals(Jpa.JpaVendor.ECLIPSELINK)) {
typedQuery.setParameter("eclipselink.tenant-id", "DEFAULT");
typedQuery.getResultList();
try {
final Class<?> jpaQueryClass = Class.forName("org.eclipse.persistence.jpa.JpaQuery");
final Method getDatabaseQueryMethod = jpaQueryClass.getMethod("getDatabaseQuery");
final Method getSQLString = getDatabaseQueryMethod.getReturnType().getMethod("getSQLString");
return (String)getSQLString.invoke(getDatabaseQueryMethod.invoke(typedQuery.unwrap(jpaQueryClass)));
} catch (final RuntimeException e) {
throw e;
} catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException e) {
throw new UnsupportedOperationException("EclipseLink is not supported", e);
} catch (final InvocationTargetException e) {
throw e.getCause() instanceof RuntimeException ? (RuntimeException)e.getCause() : new RuntimeException(e.getCause());
}
} else { // hibernate
throw new UnsupportedOperationException("Hibernate is not supported");
}
}
private <T, A extends Enum<A> & RsqlQueryField> CriteriaQuery<T> createQuery(final Class<T> domainClass, final Class<A> fieldsClass,
final String rsql, final boolean legacyRsqlVisitor) {
private <T, A extends Enum<A> & RsqlQueryField> CriteriaQuery<T> createQuery(
final Class<T> domainClass, final Class<A> fieldsClass, final String rsql, final boolean legacyRsqlVisitor) {
final CriteriaQuery<T> query = entityManager.getCriteriaBuilder().createQuery(domainClass);
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
return query.where(
@@ -78,16 +88,15 @@ public class RSQLToSQL {
query.distinct(true);
final RSQLVisitor<List<Predicate>, String> jpqQueryRSQLVisitor =
legacyRsqlVisitor ?
new JpaQueryRsqlVisitor<>(
legacyRsqlVisitor
? new JpaQueryRsqlVisitor<>(
root, cb, fieldsClass,
virtualPropertyReplacer, DATABASE, query,
!RsqlConfigHolder.getInstance().isCaseInsensitiveDB() && RsqlConfigHolder.getInstance().isIgnoreCase())
:
new JpaQueryRsqlVisitorG2<>(
fieldsClass, root, query, cb,
DATABASE, virtualPropertyReplacer,
!RsqlConfigHolder.getInstance().isCaseInsensitiveDB() && RsqlConfigHolder.getInstance().isIgnoreCase());
: new JpaQueryRsqlVisitorG2<>(
fieldsClass, root, query, cb,
DATABASE, virtualPropertyReplacer,
!RsqlConfigHolder.getInstance().isCaseInsensitiveDB() && RsqlConfigHolder.getInstance().isIgnoreCase());
final List<Predicate> accept = rootNode.accept(jpqQueryRSQLVisitor);
if (CollectionUtils.isEmpty(accept)) {

View File

@@ -15,7 +15,18 @@ logging.level.org.eclipse.persistence=ERROR
spring.jpa.properties.eclipselink.logging.level=FINE
spring.jpa.properties.eclipselink.logging.level.sql=FINE
spring.jpa.properties.eclipselink.logging.parameters=true
#hibernate.generate_statistics=true
#logging.level.org.hibernate.SQL=TRACE
#logging.level.org.hibernate.stat=TRACE
# Debug utility functions - END
# Switch to mysql
#spring.jpa.database=MYSQL
#spring.datasource.url=jdbc:mariadb://localhost:3306/hawkbit_test
#spring.datasource.driverClassName=org.mariadb.jdbc.Driver
#spring.datasource.username=root
#spring.datasource.password=
# enable / disable case sensitiveness of the DB when playing around
#hawkbit.rsql.caseInsensitiveDB=true