hawkBit repository uses Optional on single entity find/get requests (#435)

* Repo returns optionals.
* Improved exception handling for collection usage in repo queries.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>
This commit is contained in:
Kai Zimmermann
2017-02-16 10:09:14 +01:00
committed by GitHub
parent d21af83804
commit 804522f966
232 changed files with 2104 additions and 2377 deletions

View File

@@ -17,7 +17,7 @@
<artifactId>hawkbit-extensions-parent</artifactId> <artifactId>hawkbit-extensions-parent</artifactId>
</parent> </parent>
<artifactId>hawkbit-extension-artifact-repository-mongo</artifactId> <artifactId>hawkbit-extension-artifact-repository-mongo</artifactId>
<name>hawkBit :: Artifact Repository Mongo</name> <name>hawkBit :: Extensions :: Artifact Repository Mongo</name>
<dependencies> <dependencies>
@@ -49,16 +49,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>ru.yandex.qatools.allure</groupId> <groupId>ru.yandex.qatools.allure</groupId>
<artifactId>allure-junit-adaptor</artifactId> <artifactId>allure-junit-adaptor</artifactId>
@@ -70,12 +60,6 @@
<artifactId>de.flapdoodle.embed.mongo</artifactId> <artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- Mockito -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.artifact.repository; package org.eclipse.hawkbit.artifact.repository;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.security.DigestInputStream; import java.security.DigestInputStream;

View File

@@ -16,7 +16,7 @@
<version>0.2.0-SNAPSHOT</version> <version>0.2.0-SNAPSHOT</version>
</parent> </parent>
<artifactId>hawkbit-extension-artifact-repository-s3</artifactId> <artifactId>hawkbit-extension-artifact-repository-s3</artifactId>
<name>hawkBit :: S3 Repository</name> <name>hawkBit :: Extensions :: S3 Repository</name>
<dependencies> <dependencies>
@@ -50,18 +50,8 @@
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.easytesting</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>fest-assert-core</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.artifact.repository; package org.eclipse.hawkbit.artifact.repository;
import static org.fest.assertions.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;

View File

@@ -59,4 +59,5 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<name>hawkBit :: Extensions :: UAA Integration</name>
</project> </project>

View File

@@ -40,18 +40,8 @@
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.easytesting</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>fest-assert-core</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>

View File

@@ -8,15 +8,15 @@
*/ */
package org.eclipse.hawkbit.artifact.repository; package org.eclipse.hawkbit.artifact.repository;
import static org.fest.assertions.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Random; import java.util.Random;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.fest.assertions.api.Assertions;
import org.junit.Test; import org.junit.Test;
import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Description;

View File

@@ -8,14 +8,14 @@
*/ */
package org.eclipse.hawkbit.artifact.repository; package org.eclipse.hawkbit.artifact.repository;
import static org.fest.assertions.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.fest.assertions.api.Assertions; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.Test;
import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Description;

View File

@@ -33,16 +33,6 @@
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
</dependency> </dependency>
<!-- Test --> <!-- Test -->
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
@@ -53,16 +43,6 @@
<artifactId>allure-junit-adaptor</artifactId> <artifactId>allure-junit-adaptor</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId> <artifactId>spring-boot-configuration-processor</artifactId>

View File

@@ -32,7 +32,7 @@ public enum SpServerError {
/** /**
* *
*/ */
SP_REPO_ENTITY_NOT_EXISTS("hawkbit.server.error.repo.entitiyNotFound", "The given entity does not exist in database"), SP_REPO_ENTITY_NOT_EXISTS("hawkbit.server.error.repo.entitiyNotFound", "The given entity does not exist in the repository"),
/** /**
* *
*/ */

View File

@@ -49,7 +49,7 @@ public class TenantConfigurationProperties {
* @return the TenantConfigurationKey with the name keyName * @return the TenantConfigurationKey with the name keyName
*/ */
public TenantConfigurationKey fromKeyName(final String keyName) { public TenantConfigurationKey fromKeyName(final String keyName) {
return configuration.values().stream().filter(conf -> conf.getKeyName().equals(keyName)).findFirst() return configuration.values().stream().filter(conf -> conf.getKeyName().equals(keyName)).findAny()
.orElseThrow(() -> new InvalidTenantConfigurationKeyException( .orElseThrow(() -> new InvalidTenantConfigurationKeyException(
"The given configuration key " + keyName + " does not exist.")); "The given configuration key " + keyName + " does not exist."));
} }

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.api; package org.eclipse.hawkbit.api;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test; import org.junit.Test;

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.api; package org.eclipse.hawkbit.api;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import java.net.URI; import java.net.URI;

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.cache; package org.eclipse.hawkbit.cache;
import static org.fest.assertions.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;

View File

@@ -128,16 +128,6 @@
<artifactId>spring-security-aspects</artifactId> <artifactId>spring-security-aspects</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>ru.yandex.qatools.allure</groupId> <groupId>ru.yandex.qatools.allure</groupId>
<artifactId>allure-junit-adaptor</artifactId> <artifactId>allure-junit-adaptor</artifactId>

View File

@@ -10,7 +10,7 @@ package org.eclipse.hawkbit.ddi.rest.resource;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.Optional;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@@ -21,6 +21,7 @@ import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.RepositoryConstants; import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.exception.SoftwareModuleNotAssignedToTargetException;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.ActionStatus;
@@ -73,18 +74,15 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
public ResponseEntity<InputStream> downloadArtifactByFilename(@PathVariable("tenant") final String tenant, public ResponseEntity<InputStream> downloadArtifactByFilename(@PathVariable("tenant") final String tenant,
@PathVariable("fileName") final String fileName) { @PathVariable("fileName") final String fileName) {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
final List<Artifact> foundArtifacts = artifactManagement.findArtifactByFilename(fileName); final Optional<Artifact> foundArtifacts = artifactManagement.findArtifactByFilename(fileName);
if (foundArtifacts.isEmpty()) { if (!foundArtifacts.isPresent()) {
LOG.warn("Software artifact with name {} could not be found.", fileName); LOG.warn("Software artifact with name {} could not be found.", fileName);
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} }
if (foundArtifacts.size() > 1) {
LOG.warn("Software artifact name {} is not unique. We will use the first entry.", fileName);
}
ResponseEntity<InputStream> result; ResponseEntity<InputStream> result;
final Artifact artifact = foundArtifacts.get(0); final Artifact artifact = foundArtifacts.get();
final String ifMatch = requestResponseContextHolder.getHttpServletRequest().getHeader("If-Match"); final String ifMatch = requestResponseContextHolder.getHttpServletRequest().getHeader("If-Match");
if (ifMatch != null && !RestResourceConversionHelper.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) { if (ifMatch != null && !RestResourceConversionHelper.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) {
@@ -116,18 +114,16 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
@Override @Override
public ResponseEntity<Void> downloadArtifactMD5ByFilename(@PathVariable("tenant") final String tenant, public ResponseEntity<Void> downloadArtifactMD5ByFilename(@PathVariable("tenant") final String tenant,
@PathVariable("fileName") final String fileName) { @PathVariable("fileName") final String fileName) {
final List<Artifact> foundArtifacts = artifactManagement.findArtifactByFilename(fileName); final Optional<Artifact> foundArtifacts = artifactManagement.findArtifactByFilename(fileName);
if (foundArtifacts.isEmpty()) { if (!foundArtifacts.isPresent()) {
LOG.warn("Softeare artifact with name {} could not be found.", fileName); LOG.warn("Software artifact with name {} could not be found.", fileName);
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} else if (foundArtifacts.size() > 1) {
LOG.error("Softeare artifact name {} is not unique.", fileName);
} }
try { try {
DataConversionHelper.writeMD5FileResponse(fileName, requestResponseContextHolder.getHttpServletResponse(), DataConversionHelper.writeMD5FileResponse(fileName, requestResponseContextHolder.getHttpServletResponse(),
foundArtifacts.get(0)); foundArtifacts.get());
} catch (final IOException e) { } catch (final IOException e) {
LOG.error("Failed to stream MD5 File", e); LOG.error("Failed to stream MD5 File", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
@@ -142,7 +138,10 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
IpUtil.getClientIpFromRequest(request, securityProperties)); IpUtil.getClientIpFromRequest(request, securityProperties));
final Action action = controllerManagement final Action action = controllerManagement
.getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), artifact.getSoftwareModule()); .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(),
artifact.getSoftwareModule().getId())
.orElseThrow(() -> new SoftwareModuleNotAssignedToTargetException(artifact.getSoftwareModule().getId(),
target.getControllerId()));
final String range = request.getHeader("Range"); final String range = request.getHeader("Range");
String message; String message;
@@ -156,5 +155,4 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
return controllerManagement.addInformationalActionStatus( return controllerManagement.addInformationalActionStatus(
entityFactory.actionStatus().create(action.getId()).status(Status.DOWNLOAD).message(message)); entityFactory.actionStatus().create(action.getId()).status(Status.DOWNLOAD).message(message));
} }
} }

View File

@@ -37,6 +37,7 @@ import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.builder.ActionStatusCreate; import org.eclipse.hawkbit.repository.builder.ActionStatusCreate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.SoftwareModuleNotAssignedToTargetException;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.ActionStatus;
@@ -112,13 +113,8 @@ public class DdiRootController implements DdiRootControllerRestApi {
final Target target = controllerManagement.updateLastTargetQuery(controllerId, IpUtil final Target target = controllerManagement.updateLastTargetQuery(controllerId, IpUtil
.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties)); .getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties));
final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(softwareModuleId); final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (softwareModule == null) {
LOG.warn("Software module with id {} could not be found.", softwareModuleId);
throw new EntityNotFoundException("Software module does not exist");
}
return new ResponseEntity<>( return new ResponseEntity<>(
DataConversionHelper.createArtifacts(target, softwareModule, artifactUrlHandler, systemManagement, DataConversionHelper.createArtifacts(target, softwareModule, artifactUrlHandler, systemManagement,
@@ -147,7 +143,8 @@ public class DdiRootController implements DdiRootControllerRestApi {
final Target target = controllerManagement.updateLastTargetQuery(controllerId, IpUtil final Target target = controllerManagement.updateLastTargetQuery(controllerId, IpUtil
.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties)); .getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties));
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId); final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (checkModule(fileName, module)) { if (checkModule(fileName, module)) {
LOG.warn("Softare module with id {} could not be found.", softwareModuleId); LOG.warn("Softare module with id {} could not be found.", softwareModuleId);
@@ -166,7 +163,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
result = new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED); result = new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED);
} else { } else {
final ActionStatus action = checkAndLogDownload(requestResponseContextHolder.getHttpServletRequest(), final ActionStatus action = checkAndLogDownload(requestResponseContextHolder.getHttpServletRequest(),
target, module); target, module.getId());
result = RestResourceConversionHelper.writeFileResponse(artifact, result = RestResourceConversionHelper.writeFileResponse(artifact,
requestResponseContextHolder.getHttpServletResponse(), requestResponseContextHolder.getHttpServletResponse(),
requestResponseContextHolder.getHttpServletRequest(), file, controllerManagement, requestResponseContextHolder.getHttpServletRequest(), file, controllerManagement,
@@ -176,10 +173,10 @@ public class DdiRootController implements DdiRootControllerRestApi {
return result; return result;
} }
private ActionStatus checkAndLogDownload(final HttpServletRequest request, final Target target, private ActionStatus checkAndLogDownload(final HttpServletRequest request, final Target target, final Long module) {
final SoftwareModule module) {
final Action action = controllerManagement final Action action = controllerManagement
.getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module); .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module)
.orElseThrow(() -> new SoftwareModuleNotAssignedToTargetException(module, target.getControllerId()));
final String range = request.getHeader("Range"); final String range = request.getHeader("Range");
String message; String message;
@@ -209,7 +206,8 @@ public class DdiRootController implements DdiRootControllerRestApi {
controllerManagement.updateLastTargetQuery(controllerId, IpUtil controllerManagement.updateLastTargetQuery(controllerId, IpUtil
.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties)); .getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties));
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId); final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (checkModule(fileName, module)) { if (checkModule(fileName, module)) {
LOG.warn("Software module with id {} could not be found.", softwareModuleId); LOG.warn("Software module with id {} could not be found.", softwareModuleId);
@@ -483,10 +481,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
} }
private Action findActionWithExceptionIfNotFound(final Long actionId) { private Action findActionWithExceptionIfNotFound(final Long actionId) {
final Action findAction = controllerManagement.findActionWithDetails(actionId); return controllerManagement.findActionWithDetails(actionId)
if (findAction == null) { .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
throw new EntityNotFoundException("Action with Id {" + actionId + "} does not exist");
}
return findAction;
} }
} }

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.ddi.rest.resource; package org.eclipse.hawkbit.ddi.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -90,7 +90,7 @@ public class DdiArtifactDownloadTest extends AbstractDDiApiIntegrationTest {
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024); final byte random[] = RandomUtils.nextBytes(5 * 1024);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random),
ds.findFirstModuleByType(osType).getId(), "file1", false); ds.findFirstModuleByType(osType).get().getId(), "file1", false);
// no artifact available // no artifact available
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/123455", mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/123455",
@@ -254,7 +254,7 @@ public class DdiArtifactDownloadTest extends AbstractDDiApiIntegrationTest {
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(ARTIFACT_SIZE); final byte random[] = RandomUtils.nextBytes(ARTIFACT_SIZE);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random),
ds.findFirstModuleByType(osType).getId(), "file1", false); ds.findFirstModuleByType(osType).get().getId(), "file1", false);
// download fails as artifact is not yet assigned // download fails as artifact is not yet assigned
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}", mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}",

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.ddi.rest.resource; package org.eclipse.hawkbit.ddi.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.Matchers.startsWith;
@@ -52,7 +52,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget(); final Target savedTarget = testdataFactory.createTarget();
final Action updateAction = deploymentManagement.findActionWithDetails( final Action updateAction = deploymentManagement.findActionWithDetails(
assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0)); assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0)).get();
final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId()); final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId());
@@ -74,11 +74,11 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.deployment.download", equalTo("forced"))) .andExpect(jsonPath("$.deployment.download", equalTo("forced")))
.andExpect(jsonPath("$.deployment.update", equalTo("forced"))) .andExpect(jsonPath("$.deployment.update", equalTo("forced")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version",
contains(ds.findFirstModuleByType(runtimeType).getVersion()))) contains(ds.findFirstModuleByType(runtimeType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version",
contains(ds.findFirstModuleByType(osType).getVersion()))) contains(ds.findFirstModuleByType(osType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version",
contains(ds.findFirstModuleByType(appType).getVersion()))); contains(ds.findFirstModuleByType(appType).get().getVersion())));
// and finish it // and finish it
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/"
@@ -88,12 +88,12 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// check database after test // check database after test
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getAssignedDistributionSet().getId()).isEqualTo(ds.getId()); .getAssignedDistributionSet().getId()).isEqualTo(ds.getId());
assertThat(targetManagement.findTargetByControllerIDWithDetails(TestdataFactory.DEFAULT_CONTROLLER_ID) assertThat(targetManagement.findTargetByControllerIDWithDetails(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(ds.getId()); .getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(ds.getId());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getInstallationDate()).isGreaterThanOrEqualTo(current); .getTargetInfo().getInstallationDate()).isGreaterThanOrEqualTo(current);
} }
@@ -104,7 +104,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget(); final Target savedTarget = testdataFactory.createTarget();
final Action updateAction = deploymentManagement.findActionWithDetails( final Action updateAction = deploymentManagement.findActionWithDetails(
assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0)); assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0)).get();
long current = System.currentTimeMillis(); long current = System.currentTimeMillis();
mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(), mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(),
@@ -118,10 +118,10 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and // often too fast and
// the following assert will fail // the following assert will fail
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); .getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isGreaterThanOrEqualTo(current); .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
// Retrieved is reported // Retrieved is reported
@@ -150,24 +150,24 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and // often too fast and
// the following assert will fail // the following assert will fail
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); .getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isGreaterThanOrEqualTo(current); .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); .getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
+ cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) + cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId())))) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId()))))
.andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction.getId())))); .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction.getId()))));
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); .getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isGreaterThanOrEqualTo(current); .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
// controller confirmed cancelled action, should not be active anymore // controller confirmed cancelled action, should not be active anymore
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
@@ -178,7 +178,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()); activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId());
assertThat(activeActionsByTarget).hasSize(0); assertThat(activeActionsByTarget).hasSize(0);
final Action canceledAction = deploymentManagement.findAction(cancelAction.getId()); final Action canceledAction = deploymentManagement.findAction(cancelAction.getId()).get();
assertThat(canceledAction.isActive()).isFalse(); assertThat(canceledAction.isActive()).isFalse();
assertThat(canceledAction.getStatus()).isEqualTo(Status.CANCELED); assertThat(canceledAction.getStatus()).isEqualTo(Status.CANCELED);
@@ -221,7 +221,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final List<Target> toAssign = new ArrayList<>(); final List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget); toAssign.add(savedTarget);
final Action updateAction = deploymentManagement final Action updateAction = deploymentManagement
.findActionWithDetails(assignDistributionSet(ds, toAssign).getActions().get(0)); .findActionWithDetails(assignDistributionSet(ds, toAssign).getActions().get(0)).get();
return deploymentManagement.cancelAction(updateAction.getId()); return deploymentManagement.cancelAction(updateAction.getId());
} }
@@ -234,8 +234,10 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget(); final Target savedTarget = testdataFactory.createTarget();
final Action updateAction = deploymentManagement.findActionWithDetails( final Action updateAction = deploymentManagement
assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); .findActionWithDetails(
assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
.get();
// cancel action manually // cancel action manually
final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId()); final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId());
@@ -248,8 +250,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isGreaterThanOrEqualTo(current); .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
@@ -260,8 +262,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "resumed")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "resumed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isGreaterThanOrEqualTo(current); .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4);
@@ -271,8 +273,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "scheduled")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "scheduled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isGreaterThanOrEqualTo(current); .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
@@ -284,8 +286,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "canceled")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "canceled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isGreaterThanOrEqualTo(current); .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
@@ -300,8 +302,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isGreaterThanOrEqualTo(current); .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
@@ -312,8 +314,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getLastTargetQuery()).isGreaterThanOrEqualTo(current); .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(0); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(0);
} }
@@ -327,12 +329,18 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget(); final Target savedTarget = testdataFactory.createTarget();
final Action updateAction = deploymentManagement.findActionWithDetails( final Action updateAction = deploymentManagement
assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); .findActionWithDetails(
final Action updateAction2 = deploymentManagement.findActionWithDetails( assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
assignDistributionSet(ds2.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); .get();
final Action updateAction3 = deploymentManagement.findActionWithDetails( final Action updateAction2 = deploymentManagement
assignDistributionSet(ds3.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); .findActionWithDetails(
assignDistributionSet(ds2.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
.get();
final Action updateAction3 = deploymentManagement
.findActionWithDetails(
assignDistributionSet(ds3.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
.get();
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
@@ -395,7 +403,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9);
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getAssignedDistributionSet()).isEqualTo(ds3); .getAssignedDistributionSet()).isEqualTo(ds3);
mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/"
+ updateAction3.getId(), tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) + updateAction3.getId(), tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
@@ -410,7 +418,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
// action is in cancelling state // action is in cancelling state
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3); assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3);
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getAssignedDistributionSet()).isEqualTo(ds3); .getAssignedDistributionSet()).isEqualTo(ds3);
mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
@@ -440,8 +448,10 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target target = testdataFactory.createTarget(); final Target target = testdataFactory.createTarget();
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
final Action action = deploymentManagement.findActionWithDetails( final Action action = deploymentManagement
assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); .findActionWithDetails(
assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
.get();
final Action cancelAction = deploymentManagement.cancelAction(action.getId()); final Action cancelAction = deploymentManagement.cancelAction(action.getId());

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.ddi.rest.resource; package org.eclipse.hawkbit.ddi.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -58,9 +58,9 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and // often too fast and
// the following assert will fail // the following assert will fail
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis()); .isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
savedTarget.getTargetInfo().getControllerAttributes().put("dsafsdf", "sdsds"); savedTarget.getTargetInfo().getControllerAttributes().put("dsafsdf", "sdsds");
@@ -97,13 +97,12 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and // often too fast and
// the following assert will fail // the following assert will fail
assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4717").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis()); .isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4717").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
assertThat( assertThat(targetManagement.findTargetByControllerIDWithDetails("4717").get().getTargetInfo()
targetManagement.findTargetByControllerIDWithDetails("4717").getTargetInfo().getControllerAttributes()) .getControllerAttributes()).isEqualTo(attributes);
.isEqualTo(attributes);
// update // update
attributes.put("sdsds", "123412"); attributes.put("sdsds", "123412");
@@ -114,13 +113,12 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and // often too fast and
// the following assert will fail // the following assert will fail
assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4717").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis()); .isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4717").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
assertThat( assertThat(targetManagement.findTargetByControllerIDWithDetails("4717").get().getTargetInfo()
targetManagement.findTargetByControllerIDWithDetails("4717").getTargetInfo().getControllerAttributes()) .getControllerAttributes()).isEqualTo(attributes);
.isEqualTo(attributes);
} }
@Test @Test

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.ddi.rest.resource; package org.eclipse.hawkbit.ddi.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
@@ -27,6 +27,7 @@ import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.assertj.core.api.Condition;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.ActionCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.ActionCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
@@ -47,7 +48,6 @@ import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.fest.assertions.core.Condition;
import org.junit.Test; import org.junit.Test;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
@@ -88,7 +88,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
assignDistributionSet(distributionSet.getId(), target.getName()); assignDistributionSet(distributionSet.getId(), target.getName());
final Long softwareModuleId = distributionSet.getModules().stream().findFirst().get().getId(); final Long softwareModuleId = distributionSet.getModules().stream().findAny().get().getId();
mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts", mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts",
tenantAware.getCurrentTenant(), target.getName(), softwareModuleId)).andDo(MockMvcResultPrinter.print()) tenantAware.getCurrentTenant(), target.getName(), softwareModuleId)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(0))); .andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(0)));
@@ -146,16 +146,16 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/" .andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/"
+ tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId()))); + tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId())));
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis()); .isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
final DistributionSet findDistributionSetByAction = distributionSetManagement final DistributionSet findDistributionSetByAction = distributionSetManagement
.findDistributionSetByAction(action.getId()); .findDistributionSetByAction(action.getId()).get();
mvc.perform( mvc.perform(
get("/{tenant}/controller/v1/4712/deploymentBase/" + uaction.getId(), tenantAware.getCurrentTenant()) get("/{tenant}/controller/v1/4712/deploymentBase/" + uaction.getId(), tenantAware.getCurrentTenant())
@@ -166,31 +166,28 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.deployment.download", equalTo("forced"))) .andExpect(jsonPath("$.deployment.download", equalTo("forced")))
.andExpect(jsonPath("$.deployment.update", equalTo("forced"))) .andExpect(jsonPath("$.deployment.update", equalTo("forced")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].name",
contains(ds.findFirstModuleByType(runtimeType).getName()))) contains(ds.findFirstModuleByType(runtimeType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version",
contains(ds.findFirstModuleByType(runtimeType).getVersion()))) contains(ds.findFirstModuleByType(runtimeType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].name",
contains(ds.findFirstModuleByType(osType).getName()))) contains(ds.findFirstModuleByType(osType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version",
contains(ds.findFirstModuleByType(osType).getVersion()))) contains(ds.findFirstModuleByType(osType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].size", contains(5 * 1024))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].size", contains(5 * 1024)))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5",
contains(artifact.getMd5Hash()))) contains(artifact.getMd5Hash())))
.andExpect( .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1",
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1", contains(artifact.getSha1Hash())))
contains(artifact.getSha1Hash()))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href",
.andExpect( contains(
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href", HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/controller/v1/4712/softwaremodules/"
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ "/artifacts/test1"))) + "/artifacts/test1")))
.andExpect( .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href",
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href", contains(
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ "/artifacts/test1.MD5SUM"))) + "/artifacts/test1.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].size", contains(5 * 1024))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].size", contains(5 * 1024)))
@@ -205,19 +202,18 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href", jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href",
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
+ "/controller/v1/4712/softwaremodules/" + "/controller/v1/4712/softwaremodules/"
+ findDistributionSetByAction.findFirstModuleByType(osType).getId() + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/artifacts/test1.signature"))) + "/artifacts/test1.signature")))
.andExpect( .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href",
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href", contains(
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ "/artifacts/test1.signature.MD5SUM"))) + "/artifacts/test1.signature.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version",
contains(ds.findFirstModuleByType(appType).getVersion()))) contains(ds.findFirstModuleByType(appType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name",
contains(ds.findFirstModuleByType(appType).getName()))); contains(ds.findFirstModuleByType(appType).get().getName())));
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
// Retrieved is reported // Retrieved is reported
@@ -312,16 +308,16 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/" .andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/"
+ tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId()))); + tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId())));
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis()); .isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
final DistributionSet findDistributionSetByAction = distributionSetManagement final DistributionSet findDistributionSetByAction = distributionSetManagement
.findDistributionSetByAction(action.getId()); .findDistributionSetByAction(action.getId()).get();
mvc.perform( mvc.perform(
get("/{tenant}/controller/v1/4712/deploymentBase/" + uaction.getId(), tenantAware.getCurrentTenant()) get("/{tenant}/controller/v1/4712/deploymentBase/" + uaction.getId(), tenantAware.getCurrentTenant())
@@ -332,13 +328,13 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.deployment.download", equalTo("attempt"))) .andExpect(jsonPath("$.deployment.download", equalTo("attempt")))
.andExpect(jsonPath("$.deployment.update", equalTo("attempt"))) .andExpect(jsonPath("$.deployment.update", equalTo("attempt")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].name",
contains(ds.findFirstModuleByType(runtimeType).getName()))) contains(ds.findFirstModuleByType(runtimeType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version",
contains(ds.findFirstModuleByType(runtimeType).getVersion()))) contains(ds.findFirstModuleByType(runtimeType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].name",
contains(ds.findFirstModuleByType(osType).getName()))) contains(ds.findFirstModuleByType(osType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version",
contains(ds.findFirstModuleByType(osType).getVersion()))) contains(ds.findFirstModuleByType(osType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].size", contains(5 * 1024))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].size", contains(5 * 1024)))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5",
@@ -372,10 +368,10 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
+ "/controller/v1/4712/softwaremodules/" + getOsModule(findDistributionSetByAction) + "/controller/v1/4712/softwaremodules/" + getOsModule(findDistributionSetByAction)
+ "/artifacts/test1.signature.MD5SUM"))) + "/artifacts/test1.signature.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version",
contains(ds.findFirstModuleByType(appType).getVersion()))) contains(ds.findFirstModuleByType(appType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name",
contains(ds.findFirstModuleByType(appType).getName()))); contains(ds.findFirstModuleByType(appType).get().getName())));
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
// Retrieved is reported // Retrieved is reported
@@ -428,16 +424,16 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/" .andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/"
+ tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId()))); + tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId())));
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis()); .isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
final DistributionSet findDistributionSetByAction = distributionSetManagement final DistributionSet findDistributionSetByAction = distributionSetManagement
.findDistributionSetByAction(action.getId()); .findDistributionSetByAction(action.getId()).get();
mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/{actionId}", tenantAware.getCurrentTenant(), mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/{actionId}", tenantAware.getCurrentTenant(),
uaction.getId()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) uaction.getId()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -446,31 +442,28 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.deployment.download", equalTo("forced"))) .andExpect(jsonPath("$.deployment.download", equalTo("forced")))
.andExpect(jsonPath("$.deployment.update", equalTo("forced"))) .andExpect(jsonPath("$.deployment.update", equalTo("forced")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].name",
contains(ds.findFirstModuleByType(runtimeType).getName()))) contains(ds.findFirstModuleByType(runtimeType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version",
contains(ds.findFirstModuleByType(runtimeType).getVersion()))) contains(ds.findFirstModuleByType(runtimeType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].name",
contains(ds.findFirstModuleByType(osType).getName()))) contains(ds.findFirstModuleByType(osType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version",
contains(ds.findFirstModuleByType(osType).getVersion()))) contains(ds.findFirstModuleByType(osType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].size", contains(5 * 1024))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].size", contains(5 * 1024)))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5",
contains(artifact.getMd5Hash()))) contains(artifact.getMd5Hash())))
.andExpect( .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1",
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1", contains(artifact.getSha1Hash())))
contains(artifact.getSha1Hash()))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href",
.andExpect( contains(
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href", HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/controller/v1/4712/softwaremodules/"
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ "/artifacts/test1"))) + "/artifacts/test1")))
.andExpect( .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href",
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href", contains(
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ "/artifacts/test1.MD5SUM"))) + "/artifacts/test1.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].size", contains(5 * 1024))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].size", contains(5 * 1024)))
@@ -478,27 +471,24 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
contains("test1.signature"))) contains("test1.signature")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.md5", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.md5",
contains(artifactSignature.getMd5Hash()))) contains(artifactSignature.getMd5Hash())))
.andExpect( .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.sha1",
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.sha1", contains(artifactSignature.getSha1Hash())))
contains(artifactSignature.getSha1Hash()))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href",
.andExpect( contains(
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href", HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/controller/v1/4712/softwaremodules/"
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ "/artifacts/test1.signature"))) + "/artifacts/test1.signature")))
.andExpect( .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href",
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href", contains(
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ "/artifacts/test1.signature.MD5SUM"))) + "/artifacts/test1.signature.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version",
contains(ds.findFirstModuleByType(appType).getVersion()))) contains(ds.findFirstModuleByType(appType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name",
contains(ds.findFirstModuleByType(appType).getName()))); contains(ds.findFirstModuleByType(appType).get().getName())));
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
// Retrieved is reported // Retrieved is reported
@@ -538,7 +528,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final DistributionSet savedSet = testdataFactory.createDistributionSet(""); final DistributionSet savedSet = testdataFactory.createDistributionSet("");
final Action action1 = deploymentManagement final Action action1 = deploymentManagement
.findActionWithDetails(assignDistributionSet(savedSet, toAssign).getActions().get(0)); .findActionWithDetails(assignDistributionSet(savedSet, toAssign).getActions().get(0)).get();
mvc.perform( mvc.perform(
get("/{tenant}/controller/v1/4712/deploymentBase/" + action1.getId(), tenantAware.getCurrentTenant())) get("/{tenant}/controller/v1/4712/deploymentBase/" + action1.getId(), tenantAware.getCurrentTenant()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -589,13 +579,13 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
toAssign.add(savedTarget1); toAssign.add(savedTarget1);
final Action action1 = deploymentManagement final Action action1 = deploymentManagement
.findActionWithDetails(assignDistributionSet(ds1.getId(), "4712").getActions().get(0)); .findActionWithDetails(assignDistributionSet(ds1.getId(), "4712").getActions().get(0)).get();
final Action action2 = deploymentManagement final Action action2 = deploymentManagement
.findActionWithDetails(assignDistributionSet(ds2.getId(), "4712").getActions().get(0)); .findActionWithDetails(assignDistributionSet(ds2.getId(), "4712").getActions().get(0)).get();
final Action action3 = deploymentManagement final Action action3 = deploymentManagement
.findActionWithDetails(assignDistributionSet(ds3.getId(), "4712").getActions().get(0)); .findActionWithDetails(assignDistributionSet(ds3.getId(), "4712").getActions().get(0)).get();
Target myT = targetManagement.findTargetByControllerID("4712"); Target myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(3); assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(3);
assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3); assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3);
@@ -611,7 +601,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action1.getId().toString(), "closed")) .content(JsonBuilder.deploymentActionFeedback(action1.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerIDWithDetails("4712"); myT = targetManagement.findTargetByControllerIDWithDetails("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
@@ -631,7 +621,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action2.getId().toString(), "closed")) .content(JsonBuilder.deploymentActionFeedback(action2.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerIDWithDetails("4712"); myT = targetManagement.findTargetByControllerIDWithDetails("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
@@ -651,7 +641,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action3.getId().toString(), "closed")) .content(JsonBuilder.deploymentActionFeedback(action3.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
@@ -671,10 +661,10 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
DistributionSet ds = testdataFactory.createDistributionSet(""); DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = testdataFactory.createTarget("4712"); final Target savedTarget = testdataFactory.createTarget("4712");
List<Target> toAssign = new ArrayList<>(); final List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget); toAssign.add(savedTarget);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN); .isEqualTo(TargetUpdateStatus.UNKNOWN);
assignDistributionSet(ds, toAssign); assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds.getId()).getContent() final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds.getId()).getContent()
@@ -687,10 +677,10 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
"error message")) "error message"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
Target myT = targetManagement.findTargetByControllerID("4712"); Target myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.ERROR); .isEqualTo(TargetUpdateStatus.ERROR);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
.hasSize(0); .hasSize(0);
@@ -706,10 +696,8 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.ERROR)); assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.ERROR));
// redo // redo
toAssign = new ArrayList<>(); ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()).get();
toAssign.add(targetManagement.findTargetByControllerID("4712")); assignDistributionSet(ds, Lists.newArrayList(targetManagement.findTargetByControllerID("4712").get()));
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId());
assignDistributionSet(ds, toAssign);
final Action action2 = deploymentManagement.findActiveActionsByTarget(myT.getControllerId()).get(0); final Action action2 = deploymentManagement.findActiveActionsByTarget(myT.getControllerId()).get(0);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
@@ -719,7 +707,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
@@ -748,13 +736,13 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final List<Target> toAssign = Lists.newArrayList(savedTarget); final List<Target> toAssign = Lists.newArrayList(savedTarget);
Target myT = targetManagement.findTargetByControllerID("4712"); Target myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
assignDistributionSet(ds, toAssign); assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds.getId()).getContent() final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds.getId()).getContent()
.get(0); .get(0);
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.findTargetByInstalledDistributionSet(ds.getId(), pageReq)).hasSize(0); assertThat(targetManagement.findTargetByInstalledDistributionSet(ds.getId(), pageReq)).hasSize(0);
assertThat(targetManagement.findTargetByAssignedDistributionSet(ds.getId(), pageReq)).hasSize(1); assertThat(targetManagement.findTargetByAssignedDistributionSet(ds.getId(), pageReq)).hasSize(1);
@@ -771,7 +759,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
} }
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
@@ -791,7 +779,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "scheduled")) .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "scheduled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
@@ -811,7 +799,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "resumed")) .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "resumed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
@@ -831,7 +819,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "canceled")) .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "canceled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1);
@@ -854,7 +842,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "rejected")) .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "rejected"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1);
@@ -872,7 +860,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "closed")) .content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(0); assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(0);

View File

@@ -8,11 +8,11 @@
*/ */
package org.eclipse.hawkbit.ddi.rest.resource; package org.eclipse.hawkbit.ddi.rest.resource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.CONTROLLER_ROLE; import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.CONTROLLER_ROLE;
import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS; import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS;
import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION; import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION;
import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.SYSTEM_ROLE; import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.SYSTEM_ROLE;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
@@ -99,7 +99,8 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
final String knownTargetControllerId = "target1"; final String knownTargetControllerId = "target1";
final String knownCreatedBy = "knownPrincipal"; final String knownCreatedBy = "knownPrincipal";
testdataFactory.createTarget(knownTargetControllerId); testdataFactory.createTarget(knownTargetControllerId);
final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId); final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId)
.get();
assertThat(findTargetByControllerID.getCreatedBy()).isEqualTo(knownCreatedBy); assertThat(findTargetByControllerID.getCreatedBy()).isEqualTo(knownCreatedBy);
assertThat(findTargetByControllerID.getCreatedAt()).isNotNull(); assertThat(findTargetByControllerID.getCreatedAt()).isNotNull();
@@ -112,7 +113,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
}); });
// verify that audit information has not changed // verify that audit information has not changed
final Target targetVerify = targetManagement.findTargetByControllerID(knownTargetControllerId); final Target targetVerify = targetManagement.findTargetByControllerID(knownTargetControllerId).get();
assertThat(targetVerify.getCreatedBy()).isEqualTo(findTargetByControllerID.getCreatedBy()); assertThat(targetVerify.getCreatedBy()).isEqualTo(findTargetByControllerID.getCreatedBy());
assertThat(targetVerify.getCreatedAt()).isEqualTo(findTargetByControllerID.getCreatedAt()); assertThat(targetVerify.getCreatedAt()).isEqualTo(findTargetByControllerID.getCreatedAt());
assertThat(targetVerify.getLastModifiedBy()).isEqualTo(findTargetByControllerID.getLastModifiedBy()); assertThat(targetVerify.getLastModifiedBy()).isEqualTo(findTargetByControllerID.getLastModifiedBy());
@@ -137,10 +138,10 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
mvc.perform(get("/default-tenant/controller/v1/4711")).andDo(MockMvcResultPrinter.print()) mvc.perform(get("/default-tenant/controller/v1/4711")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JSON_HAL_UTF))
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))); .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")));
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.REGISTERED); .isEqualTo(TargetUpdateStatus.REGISTERED);
// not allowed methods // not allowed methods
@@ -194,7 +195,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()).header("If-None-Match", etag)) mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()).header("If-None-Match", etag))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotModified()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotModified());
final Target target = targetManagement.findTargetByControllerID("4711"); final Target target = targetManagement.findTargetByControllerID("4711").get();
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
assignDistributionSet(ds.getId(), "4711"); assignDistributionSet(ds.getId(), "4711");
@@ -253,7 +254,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
public void rootRsPrecommissioned() throws Exception { public void rootRsPrecommissioned() throws Exception {
final Target target = testdataFactory.createTarget("4711"); final Target target = testdataFactory.createTarget("4711");
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN); .isEqualTo(TargetUpdateStatus.UNKNOWN);
final long current = System.currentTimeMillis(); final long current = System.currentTimeMillis();
@@ -262,12 +263,12 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
.andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(content().contentType(APPLICATION_JSON_HAL_UTF))
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))); .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")));
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis()); .isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current); .isGreaterThanOrEqualTo(current);
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.REGISTERED); .isEqualTo(TargetUpdateStatus.REGISTERED);
} }
@@ -282,7 +283,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// verify // verify
final Target target = targetManagement.findTargetByControllerID(knownControllerId1); final Target target = targetManagement.findTargetByControllerID(knownControllerId1).get();
assertThat(target.getTargetInfo().getAddress()).isEqualTo(IpUtil.createHttpUri("127.0.0.1")); assertThat(target.getTargetInfo().getAddress()).isEqualTo(IpUtil.createHttpUri("127.0.0.1"));
} }
@@ -300,7 +301,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// verify // verify
final Target target = targetManagement.findTargetByControllerID(knownControllerId1); final Target target = targetManagement.findTargetByControllerID(knownControllerId1).get();
assertThat(target.getTargetInfo().getAddress()).isEqualTo(IpUtil.createHttpUri("***")); assertThat(target.getTargetInfo().getAddress()).isEqualTo(IpUtil.createHttpUri("***"));
securityProperties.getClients().setTrackRemoteIp(true); securityProperties.getClients().setTrackRemoteIp(true);

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.ddi.rest.resource; package org.eclipse.hawkbit.ddi.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

View File

@@ -122,21 +122,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.security</groupId> <groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId> <artifactId>spring-security-config</artifactId>

View File

@@ -155,21 +155,26 @@ public class AmqpAuthenticationMessageHandler extends BaseAmqpService {
LOG.info("download security check for target {} and artifact {} granted", controllerId, sha1Hash); LOG.info("download security check for target {} and artifact {} granted", controllerId, sha1Hash);
} }
private Optional<String> findArtifactByFileResource(final FileResource fileResource) { private Optional<org.eclipse.hawkbit.repository.model.Artifact> findArtifactByFileResource(
final FileResource fileResource) {
if (fileResource.getSha1() != null) { if (fileResource.getSha1() != null) {
return Optional.ofNullable(fileResource.getSha1()); return artifactManagement.findFirstArtifactBySHA1(fileResource.getSha1());
} else if (fileResource.getFilename() != null) {
return artifactManagement.findArtifactByFilename(fileResource.getFilename()).stream().findFirst()
.map(org.eclipse.hawkbit.repository.model.Artifact::getSha1Hash);
} else if (fileResource.getArtifactId() != null) {
return Optional.ofNullable(artifactManagement.findArtifact(fileResource.getArtifactId()))
.map(org.eclipse.hawkbit.repository.model.Artifact::getSha1Hash);
} else if (fileResource.getSoftwareModuleFilenameResource() != null) {
return artifactManagement
.findByFilenameAndSoftwareModule(fileResource.getSoftwareModuleFilenameResource().getFilename(),
fileResource.getSoftwareModuleFilenameResource().getSoftwareModuleId())
.stream().findFirst().map(org.eclipse.hawkbit.repository.model.Artifact::getSha1Hash);
} }
if (fileResource.getFilename() != null) {
return artifactManagement.findArtifactByFilename(fileResource.getFilename());
}
if (fileResource.getArtifactId() != null) {
return artifactManagement.findArtifact(fileResource.getArtifactId());
}
if (fileResource.getSoftwareModuleFilenameResource() != null) {
return artifactManagement.findByFilenameAndSoftwareModule(
fileResource.getSoftwareModuleFilenameResource().getFilename(),
fileResource.getSoftwareModuleFilenameResource().getSoftwareModuleId());
}
return Optional.empty(); return Optional.empty();
} }
@@ -190,24 +195,20 @@ public class AmqpAuthenticationMessageHandler extends BaseAmqpService {
try { try {
SecurityContextHolder.getContext().setAuthentication(authenticationManager.doAuthenticate(secruityToken)); SecurityContextHolder.getContext().setAuthentication(authenticationManager.doAuthenticate(secruityToken));
final Optional<String> sha1Hash = findArtifactByFileResource(fileResource); final String sha1Hash = findArtifactByFileResource(fileResource)
.map(org.eclipse.hawkbit.repository.model.Artifact::getSha1Hash)
.orElseThrow(() -> new EntityNotFoundException());
if (!sha1Hash.isPresent()) { checkIfArtifactIsAssignedToTarget(secruityToken, sha1Hash);
LOG.info("target {} requested file resource {} which does not exists to download",
secruityToken.getControllerId(), fileResource);
throw new EntityNotFoundException();
}
checkIfArtifactIsAssignedToTarget(secruityToken, sha1Hash.get()); final Artifact artifact = convertDbArtifact(artifactManagement.loadArtifactBinary(sha1Hash));
final Artifact artifact = convertDbArtifact(artifactManagement.loadArtifactBinary(sha1Hash.get()));
if (artifact == null) { if (artifact == null) {
throw new EntityNotFoundException(); throw new EntityNotFoundException();
} }
authentificationResponse.setArtifact(artifact); authentificationResponse.setArtifact(artifact);
final String downloadId = UUID.randomUUID().toString(); final String downloadId = UUID.randomUUID().toString();
// SHA1 key is set, download by SHA1 // SHA1 key is set, download by SHA1
final DownloadArtifactCache downloadCache = new DownloadArtifactCache(DownloadType.BY_SHA1, sha1Hash.get()); final DownloadArtifactCache downloadCache = new DownloadArtifactCache(DownloadType.BY_SHA1, sha1Hash);
cache.put(downloadId, downloadCache); cache.put(downloadId, downloadCache);
authentificationResponse authentificationResponse
.setDownloadUrl(UriComponentsBuilder.fromUri(hostnameResolver.resolveHostname().toURI()) .setDownloadUrl(UriComponentsBuilder.fromUri(hostnameResolver.resolveHostname().toURI())

View File

@@ -103,8 +103,8 @@ public class AmqpMessageDispatcherService extends BaseAmqpService {
} }
sendUpdateMessageToTarget(assignedEvent.getTenant(), sendUpdateMessageToTarget(assignedEvent.getTenant(),
targetManagement.findTargetByControllerID(assignedEvent.getControllerId()), assignedEvent.getActionId(), targetManagement.findTargetByControllerID(assignedEvent.getControllerId()).get(),
assignedEvent.getModules()); assignedEvent.getActionId(), assignedEvent.getModules());
} }
void sendUpdateMessageToTarget(final String tenant, final Target target, final Long actionId, void sendUpdateMessageToTarget(final String tenant, final Target target, final Long actionId,

View File

@@ -28,7 +28,6 @@ import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.RepositoryConstants; import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.builder.ActionStatusCreate; import org.eclipse.hawkbit.repository.builder.ActionStatusCreate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
@@ -317,6 +316,9 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
return controllerManagement.addUpdateActionStatus(actionStatus); return controllerManagement.addUpdateActionStatus(actionStatus);
} }
// Exception squid:S3655 - logAndThrowMessageError throws exception, i.e.
// get will not be called
@SuppressWarnings("squid:S3655")
private Action checkActionExist(final Message message, final ActionUpdateStatus actionUpdateStatus) { private Action checkActionExist(final Message message, final ActionUpdateStatus actionUpdateStatus) {
final Long actionId = actionUpdateStatus.getActionId(); final Long actionId = actionUpdateStatus.getActionId();
LOG.debug("Target notifies intermediate about action {} with status {}.", actionId, LOG.debug("Target notifies intermediate about action {} with status {}.", actionId,
@@ -326,17 +328,12 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
logAndThrowMessageError(message, "Invalid message no action id"); logAndThrowMessageError(message, "Invalid message no action id");
} }
try { final Optional<Action> findActionWithDetails = controllerManagement.findActionWithDetails(actionId);
final Action findActionWithDetails = controllerManagement.findActionWithDetails(actionId); if (!findActionWithDetails.isPresent()) {
if (findActionWithDetails == null) {
logAndThrowMessageError(message,
"Got intermediate notification about action " + actionId + " but action does not exist");
}
return findActionWithDetails;
} catch (@SuppressWarnings("squid:S1166") final EntityNotFoundException e) {
logAndThrowMessageError(message, logAndThrowMessageError(message,
"Got intermediate notification about action " + actionId + " but action does not exist"); "Got intermediate notification about action " + actionId + " but action does not exist");
} }
return null;
return findActionWithDetails.get();
} }
} }

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.amqp; package org.eclipse.hawkbit.amqp;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
@@ -17,6 +17,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.net.URL; import java.net.URL;
import java.util.Optional;
import org.eclipse.hawkbit.api.HostnameResolver; import org.eclipse.hawkbit.api.HostnameResolver;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
@@ -134,8 +135,8 @@ public class AmqpControllerAuthenticationTest {
.thenReturn(CONFIG_VALUE_FALSE); .thenReturn(CONFIG_VALUE_FALSE);
final ControllerManagement controllerManagement = mock(ControllerManagement.class); final ControllerManagement controllerManagement = mock(ControllerManagement.class);
when(controllerManagement.findByControllerId(anyString())).thenReturn(targteMock); when(controllerManagement.findByControllerId(anyString())).thenReturn(Optional.of(targteMock));
when(controllerManagement.findByTargetId(any(Long.class))).thenReturn(targteMock); when(controllerManagement.findByTargetId(any(Long.class))).thenReturn(Optional.of(targteMock));
when(targteMock.getSecurityToken()).thenReturn(CONTROLLER_ID); when(targteMock.getSecurityToken()).thenReturn(CONTROLLER_ID);
when(targteMock.getControllerId()).thenReturn(CONTROLLER_ID); when(targteMock.getControllerId()).thenReturn(CONTROLLER_ID);
@@ -156,8 +157,8 @@ public class AmqpControllerAuthenticationTest {
new JpaSoftwareModuleType("a key", "a name", null, 1), "a name", null, null, null)); new JpaSoftwareModuleType("a key", "a name", null, 1), "a name", null, null, null));
testArtifact.setId(1L); testArtifact.setId(1L);
when(artifactManagementMock.findArtifact(ARTIFACT_ID)).thenReturn(testArtifact); when(artifactManagementMock.findArtifact(ARTIFACT_ID)).thenReturn(Optional.of(testArtifact));
when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(testArtifact); when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(Optional.of(testArtifact));
final DbArtifact artifact = new DbArtifact(); final DbArtifact artifact = new DbArtifact();
artifact.setSize(ARTIFACT_SIZE); artifact.setSize(ARTIFACT_SIZE);

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.amqp; package org.eclipse.hawkbit.amqp;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -126,13 +126,13 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
private Message getCaptureAdressEvent(final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent) { private Message getCaptureAdressEvent(final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent) {
final Target target = targetManagement final Target target = targetManagement
.findTargetByControllerID(targetAssignDistributionSetEvent.getControllerId()); .findTargetByControllerID(targetAssignDistributionSetEvent.getControllerId()).get();
final Message sendMessage = createArgumentCapture(target.getTargetInfo().getAddress()); final Message sendMessage = createArgumentCapture(target.getTargetInfo().getAddress());
return sendMessage; return sendMessage;
} }
private Action createAction(final DistributionSet testDs) { private Action createAction(final DistributionSet testDs) {
return deploymentManagement.findAction(assignDistributionSet(testDs, testTarget).getActions().get(0)); return deploymentManagement.findAction(assignDistributionSet(testDs, testTarget).getActions().get(0)).get();
} }
@Test @Test
@@ -177,8 +177,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
for (final Artifact artifact : testdataFactory.createArtifacts(module.getId())) { for (final Artifact artifact : testdataFactory.createArtifacts(module.getId())) {
receivedList.add(new DbArtifact()); receivedList.add(new DbArtifact());
} }
module = softwareManagement.findSoftwareModuleById(module.getId()); module = softwareManagement.findSoftwareModuleById(module.getId()).get();
dsA = distributionSetManagement.findDistributionSetById(dsA.getId()); dsA = distributionSetManagement.findDistributionSetById(dsA.getId()).get();
final Action action = createAction(dsA); final Action action = createAction(dsA);
@@ -205,7 +205,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
module.getArtifacts().forEach(dbArtifact -> { module.getArtifacts().forEach(dbArtifact -> {
final Optional<org.eclipse.hawkbit.dmf.json.model.Artifact> found = softwareModule.getArtifacts() final Optional<org.eclipse.hawkbit.dmf.json.model.Artifact> found = softwareModule.getArtifacts()
.stream().filter(dmfartifact -> dmfartifact.getFilename().equals(dbArtifact.getFilename())) .stream().filter(dmfartifact -> dmfartifact.getFilename().equals(dbArtifact.getFilename()))
.findFirst(); .findAny();
assertTrue("The artifact should exist in message", found.isPresent()); assertTrue("The artifact should exist in message", found.isPresent());
assertThat(found.get().getSize()).isEqualTo(dbArtifact.getSize()); assertThat(found.get().getSize()).isEqualTo(dbArtifact.getSize());

View File

@@ -8,8 +8,9 @@
*/ */
package org.eclipse.hawkbit.amqp; package org.eclipse.hawkbit.amqp;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@@ -126,6 +127,8 @@ public class AmqpMessageHandlerServiceTest {
public void before() throws Exception { public void before() throws Exception {
messageConverter = new Jackson2JsonMessageConverter(); messageConverter = new Jackson2JsonMessageConverter();
when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter); when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter);
when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(Optional.empty());
amqpMessageHandlerService = new AmqpMessageHandlerService(rabbitTemplate, amqpMessageDispatcherServiceMock, amqpMessageHandlerService = new AmqpMessageHandlerService(rabbitTemplate, amqpMessageDispatcherServiceMock,
controllerManagementMock, entityFactoryMock); controllerManagementMock, entityFactoryMock);
@@ -163,7 +166,7 @@ public class AmqpMessageHandlerServiceTest {
final ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class); final ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class);
when(controllerManagementMock.findOrRegisterTargetIfItDoesNotexist(targetIdCaptor.capture(), when(controllerManagementMock.findOrRegisterTargetIfItDoesNotexist(targetIdCaptor.capture(),
uriCaptor.capture())).thenReturn(targetMock); uriCaptor.capture())).thenReturn(targetMock);
when(controllerManagementMock.findOldestActiveActionByTarget(Matchers.any())).thenReturn(Optional.empty()); when(controllerManagementMock.findOldestActiveActionByTarget(any())).thenReturn(Optional.empty());
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost"); amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
@@ -295,6 +298,8 @@ public class AmqpMessageHandlerServiceTest {
public void updateActionStatusWithoutExistActionId() { public void updateActionStatusWithoutExistActionId() {
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT); final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name()); messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
when(controllerManagementMock.findActionWithDetails(any())).thenReturn(Optional.empty());
final ActionUpdateStatus actionUpdateStatus = createActionUpdateStatus(ActionStatus.DOWNLOAD); final ActionUpdateStatus actionUpdateStatus = createActionUpdateStatus(ActionStatus.DOWNLOAD);
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus, final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
messageProperties); messageProperties);
@@ -337,7 +342,7 @@ public class AmqpMessageHandlerServiceTest {
messageProperties); messageProperties);
final Artifact localArtifactMock = mock(Artifact.class); final Artifact localArtifactMock = mock(Artifact.class);
when(artifactManagementMock.findFirstArtifactBySHA1(anyString())).thenReturn(localArtifactMock); when(artifactManagementMock.findFirstArtifactBySHA1(anyString())).thenReturn(Optional.of(localArtifactMock));
when(controllerManagementMock.getActionForDownloadByTargetAndSoftwareModule(anyObject(), anyObject())) when(controllerManagementMock.getActionForDownloadByTargetAndSoftwareModule(anyObject(), anyObject()))
.thenThrow(EntityNotFoundException.class); .thenThrow(EntityNotFoundException.class);
@@ -365,7 +370,7 @@ public class AmqpMessageHandlerServiceTest {
when(localArtifactMock.getSha1Hash()).thenReturn(SHA1); when(localArtifactMock.getSha1Hash()).thenReturn(SHA1);
final DbArtifact dbArtifactMock = mock(DbArtifact.class); final DbArtifact dbArtifactMock = mock(DbArtifact.class);
when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(localArtifactMock); when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(Optional.of(localArtifactMock));
when(controllerManagementMock.hasTargetArtifactAssigned(securityToken.getControllerId(), SHA1)) when(controllerManagementMock.hasTargetArtifactAssigned(securityToken.getControllerId(), SHA1))
.thenReturn(true); .thenReturn(true);
when(artifactManagementMock.loadArtifactBinary(anyString())).thenReturn(dbArtifactMock); when(artifactManagementMock.loadArtifactBinary(anyString())).thenReturn(dbArtifactMock);
@@ -395,15 +400,15 @@ public class AmqpMessageHandlerServiceTest {
// Mock // Mock
final Action action = createActionWithTarget(22L, Status.FINISHED); final Action action = createActionWithTarget(22L, Status.FINISHED);
when(controllerManagementMock.findActionWithDetails(Matchers.any())).thenReturn(action); when(controllerManagementMock.findActionWithDetails(any())).thenReturn(Optional.of(action));
when(controllerManagementMock.addUpdateActionStatus(Matchers.any())).thenReturn(action); when(controllerManagementMock.addUpdateActionStatus(any())).thenReturn(action);
final ActionStatusBuilder builder = mock(ActionStatusBuilder.class); final ActionStatusBuilder builder = mock(ActionStatusBuilder.class);
final ActionStatusCreate create = mock(ActionStatusCreate.class); final ActionStatusCreate create = mock(ActionStatusCreate.class);
when(builder.create(22L)).thenReturn(create); when(builder.create(22L)).thenReturn(create);
when(create.status(Matchers.any())).thenReturn(create); when(create.status(any())).thenReturn(create);
when(entityFactoryMock.actionStatus()).thenReturn(builder); when(entityFactoryMock.actionStatus()).thenReturn(builder);
// for the test the same action can be used // for the test the same action can be used
when(controllerManagementMock.findOldestActiveActionByTarget(Matchers.any())).thenReturn(Optional.of(action)); when(controllerManagementMock.findOldestActiveActionByTarget(any())).thenReturn(Optional.of(action));
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT); final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name()); messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
@@ -415,14 +420,14 @@ public class AmqpMessageHandlerServiceTest {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost"); amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
// verify // verify
verify(controllerManagementMock).updateLastTargetQuery(Matchers.any(String.class), Matchers.isNull(URI.class)); verify(controllerManagementMock).updateLastTargetQuery(any(String.class), Matchers.isNull(URI.class));
final ArgumentCaptor<String> tenantCaptor = ArgumentCaptor.forClass(String.class); final ArgumentCaptor<String> tenantCaptor = ArgumentCaptor.forClass(String.class);
final ArgumentCaptor<Target> targetCaptor = ArgumentCaptor.forClass(Target.class); final ArgumentCaptor<Target> targetCaptor = ArgumentCaptor.forClass(Target.class);
final ArgumentCaptor<Long> actionIdCaptor = ArgumentCaptor.forClass(Long.class); final ArgumentCaptor<Long> actionIdCaptor = ArgumentCaptor.forClass(Long.class);
verify(amqpMessageDispatcherServiceMock, times(1)).sendUpdateMessageToTarget(tenantCaptor.capture(), verify(amqpMessageDispatcherServiceMock, times(1)).sendUpdateMessageToTarget(tenantCaptor.capture(),
targetCaptor.capture(), actionIdCaptor.capture(), Matchers.any(Collection.class)); targetCaptor.capture(), actionIdCaptor.capture(), any(Collection.class));
final String tenant = tenantCaptor.getValue(); final String tenant = tenantCaptor.getValue();
final String controllerId = targetCaptor.getValue().getControllerId(); final String controllerId = targetCaptor.getValue().getControllerId();
final Long actionId = actionIdCaptor.getValue(); final Long actionId = actionIdCaptor.getValue();

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.amqp; package org.eclipse.hawkbit.amqp;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
@@ -61,7 +61,7 @@ public class BaseAmqpServiceTest {
ActionUpdateStatus.class); ActionUpdateStatus.class);
assertThat(convertedActionUpdateStatus).as("Converted Action Status is wrong") assertThat(convertedActionUpdateStatus).as("Converted Action Status is wrong")
.isEqualsToByComparingFields(actionUpdateStatus); .isEqualToComparingFieldByField(actionUpdateStatus);
convertedActionUpdateStatus = baseAmqpService.convertMessage(null, ActionUpdateStatus.class); convertedActionUpdateStatus = baseAmqpService.convertMessage(null, ActionUpdateStatus.class);
assertThat(convertedActionUpdateStatus).as("Converted Object should be null when message is null").isNull(); assertThat(convertedActionUpdateStatus).as("Converted Object should be null when message is null").isNull();

View File

@@ -47,16 +47,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>ru.yandex.qatools.allure</groupId> <groupId>ru.yandex.qatools.allure</groupId>
<artifactId>allure-junit-adaptor</artifactId> <artifactId>allure-junit-adaptor</artifactId>

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.security; package org.eclipse.hawkbit.security;
import static org.fest.assertions.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;

View File

@@ -35,8 +35,8 @@
<!-- Test --> <!-- Test -->
<dependency> <dependency>
<groupId>org.easytesting</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>fest-assert</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.mgmt.json.model; package org.eclipse.hawkbit.mgmt.json.model;
import static org.fest.assertions.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.util.ArrayList; import java.util.ArrayList;

View File

@@ -126,16 +126,6 @@
<artifactId>spring-security-aspects</artifactId> <artifactId>spring-security-aspects</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>ru.yandex.qatools.allure</groupId> <groupId>ru.yandex.qatools.allure</groupId>
<artifactId>allure-junit-adaptor</artifactId> <artifactId>allure-junit-adaptor</artifactId>

View File

@@ -162,10 +162,6 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
// check if distribution set exists otherwise throw exception
// immediately
findDistributionSetWithExceptionIfNotFound(distributionSetId);
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam); final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
@@ -256,10 +252,6 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
// check if distribution set exists otherwise throw exception
// immediately
findDistributionSetWithExceptionIfNotFound(distributionSetId);
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeDistributionSetMetadataSortParam(sortParam); final Sort sorting = PagingUtility.sanitizeDistributionSetMetadataSortParam(sortParam);
@@ -288,9 +280,11 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@PathVariable("metadataKey") final String metadataKey) { @PathVariable("metadataKey") final String metadataKey) {
// check if distribution set exists otherwise throw exception // check if distribution set exists otherwise throw exception
// immediately // immediately
final DistributionSetMetadata findOne = distributionSetManagement.findDistributionSetMetadata(distributionSetId, final DistributionSetMetadata findOne = distributionSetManagement
metadataKey); .findDistributionSetMetadata(distributionSetId, metadataKey)
return ResponseEntity.<MgmtMetadata> ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne)); .orElseThrow(() -> new EntityNotFoundException(DistributionSetMetadata.class, distributionSetId,
metadataKey));
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne));
} }
@Override @Override
@@ -347,9 +341,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam) { @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam) {
// check if distribution set exists otherwise throw exception
// immediately
findDistributionSetWithExceptionIfNotFound(distributionSetId);
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeSoftwareModuleSortParam(sortParam); final Sort sorting = PagingUtility.sanitizeSoftwareModuleSortParam(sortParam);
@@ -361,11 +353,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
} }
private DistributionSet findDistributionSetWithExceptionIfNotFound(final Long distributionSetId) { private DistributionSet findDistributionSetWithExceptionIfNotFound(final Long distributionSetId) {
final DistributionSet set = distributionSetManagement.findDistributionSetById(distributionSetId); return distributionSetManagement.findDistributionSetById(distributionSetId)
if (set == null) { .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, distributionSetId));
throw new EntityNotFoundException("DistributionSet with Id {" + distributionSetId + "} does not exist");
}
return set;
} }
} }

View File

@@ -194,16 +194,13 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
} }
private DistributionSetTag findDistributionTagById(final Long distributionsetTagId) { private DistributionSetTag findDistributionTagById(final Long distributionsetTagId) {
final DistributionSetTag tag = this.tagManagement.findDistributionSetTagById(distributionsetTagId); return tagManagement.findDistributionSetTagById(distributionsetTagId)
if (tag == null) { .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, distributionsetTagId));
throw new EntityNotFoundException("Distribution Tag with Id {" + distributionsetTagId + "} does not exist");
}
return tag;
} }
private static List<Long> findDistributionSetIds( private static List<Long> findDistributionSetIds(
final List<MgmtAssignedDistributionSetRequestBody> assignedDistributionSetRequestBodies) { final List<MgmtAssignedDistributionSetRequestBody> assignedDistributionSetRequestBodies) {
return assignedDistributionSetRequestBodies.stream().map(request -> request.getDistributionSetId()) return assignedDistributionSetRequestBodies.stream()
.collect(Collectors.toList()); .map(MgmtAssignedDistributionSetRequestBody::getDistributionSetId).collect(Collectors.toList());
} }
} }

View File

@@ -29,6 +29,7 @@ import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.SoftwareModuleTypeNotInDistributionSetTypeException;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -100,7 +101,6 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@Override @Override
public ResponseEntity<Void> deleteDistributionSetType( public ResponseEntity<Void> deleteDistributionSetType(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) { @PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
distributionSetManagement.deleteDistributionSetType(distributionSetTypeId); distributionSetManagement.deleteDistributionSetType(distributionSetTypeId);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
@@ -127,14 +127,8 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
} }
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final Long distributionSetTypeId) { private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final Long distributionSetTypeId) {
return distributionSetManagement.findDistributionSetTypeById(distributionSetTypeId)
final DistributionSetType module = distributionSetManagement.findDistributionSetTypeById(distributionSetTypeId); .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypeId));
if (module == null) {
throw new EntityNotFoundException(
"DistributionSetType with Id {" + distributionSetTypeId + "} does not exist");
}
return module;
} }
@Override @Override
@@ -154,8 +148,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
if (!foundType.containsMandatoryModuleType(foundSmType)) { if (!foundType.containsMandatoryModuleType(foundSmType)) {
throw new EntityNotFoundException( throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
"Software module with given ID is not part of this distribution set type!");
} }
return ResponseEntity.ok(toResponse(foundSmType)); return ResponseEntity.ok(toResponse(foundSmType));
@@ -170,8 +163,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
if (!foundType.containsOptionalModuleType(foundSmType)) { if (!foundType.containsOptionalModuleType(foundSmType)) {
throw new EntityNotFoundException( throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
"Software module with given ID is not part of this distribution set type!");
} }
return ResponseEntity.ok(toResponse(foundSmType)); return ResponseEntity.ok(toResponse(foundSmType));
@@ -224,12 +216,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) { private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
final SoftwareModuleType module = softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId); return softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId)
if (module == null) { .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId));
throw new EntityNotFoundException(
"SoftwareModuleType with Id {" + softwareModuleTypeId + "} does not exist");
}
return module;
} }
} }

View File

@@ -81,11 +81,10 @@ public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId, private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
final Long artifactId) { final Long artifactId) {
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId); final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
if (module == null) { .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist"); if (artifactId != null && !module.getArtifact(artifactId).isPresent()) {
} else if (artifactId != null && !module.getArtifact(artifactId).isPresent()) { throw new EntityNotFoundException(Artifact.class, artifactId);
throw new EntityNotFoundException("Artifact with Id {" + artifactId + "} does not exist");
} }
return module; return module;
} }

View File

@@ -50,9 +50,6 @@ import org.springframework.web.bind.annotation.RestController;
*/ */
@RestController @RestController
public class MgmtRolloutResource implements MgmtRolloutRestApi { public class MgmtRolloutResource implements MgmtRolloutRestApi {
private static final String DOES_NOT_EXIST = "} does not exist";
@Autowired @Autowired
private RolloutManagement rolloutManagement; private RolloutManagement rolloutManagement;
@@ -94,7 +91,9 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
@Override @Override
public ResponseEntity<MgmtRolloutResponseBody> getRollout(@PathVariable("rolloutId") final Long rolloutId) { public ResponseEntity<MgmtRolloutResponseBody> getRollout(@PathVariable("rolloutId") final Long rolloutId) {
final Rollout findRolloutById = findRolloutOrThrowException(rolloutId); final Rollout findRolloutById = rolloutManagement.findRolloutWithDetailedStatus(rolloutId)
.orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId));
return new ResponseEntity<>(MgmtRolloutMapper.toResponseRollout(findRolloutById, true), HttpStatus.OK); return new ResponseEntity<>(MgmtRolloutMapper.toResponseRollout(findRolloutById, true), HttpStatus.OK);
} }
@@ -176,10 +175,18 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
public ResponseEntity<MgmtRolloutGroupResponseBody> getRolloutGroup(@PathVariable("rolloutId") final Long rolloutId, public ResponseEntity<MgmtRolloutGroupResponseBody> getRolloutGroup(@PathVariable("rolloutId") final Long rolloutId,
@PathVariable("groupId") final Long groupId) { @PathVariable("groupId") final Long groupId) {
findRolloutOrThrowException(rolloutId); findRolloutOrThrowException(rolloutId);
final RolloutGroup rolloutGroup = findRolloutGroupOrThrowException(groupId);
final RolloutGroup rolloutGroup = rolloutGroupManagement.findRolloutGroupWithDetailedStatus(groupId)
.orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutId));
return ResponseEntity.ok(MgmtRolloutMapper.toResponseRolloutGroup(rolloutGroup, true)); return ResponseEntity.ok(MgmtRolloutMapper.toResponseRolloutGroup(rolloutGroup, true));
} }
private void findRolloutOrThrowException(final Long rolloutId) {
if (!rolloutManagement.exists(rolloutId)) {
throw new EntityNotFoundException(Rollout.class, rolloutId);
}
}
@Override @Override
public ResponseEntity<PagedList<MgmtTarget>> getRolloutGroupTargets(@PathVariable("rolloutId") final Long rolloutId, public ResponseEntity<PagedList<MgmtTarget>> getRolloutGroupTargets(@PathVariable("rolloutId") final Long rolloutId,
@PathVariable("groupId") final Long groupId, @PathVariable("groupId") final Long groupId,
@@ -205,30 +212,10 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
return new ResponseEntity<>(new PagedList<>(rest, rolloutGroupTargets.getTotalElements()), HttpStatus.OK); return new ResponseEntity<>(new PagedList<>(rest, rolloutGroupTargets.getTotalElements()), HttpStatus.OK);
} }
private Rollout findRolloutOrThrowException(final Long rolloutId) {
final Rollout rollout = this.rolloutManagement.findRolloutWithDetailedStatus(rolloutId);
if (rollout == null) {
throw new EntityNotFoundException("Rollout with Id {" + rolloutId + DOES_NOT_EXIST);
}
return rollout;
}
private RolloutGroup findRolloutGroupOrThrowException(final Long rolloutGroupId) {
final RolloutGroup rolloutGroup = this.rolloutGroupManagement
.findRolloutGroupWithDetailedStatus(rolloutGroupId);
if (rolloutGroup == null) {
throw new EntityNotFoundException("Group with Id {" + rolloutGroupId + DOES_NOT_EXIST);
}
return rolloutGroup;
}
private DistributionSet findDistributionSetOrThrowException(final MgmtRolloutRestRequestBody rolloutRequestBody) { private DistributionSet findDistributionSetOrThrowException(final MgmtRolloutRestRequestBody rolloutRequestBody) {
final DistributionSet ds = this.distributionSetManagement return this.distributionSetManagement.findDistributionSetById(rolloutRequestBody.getDistributionSetId())
.findDistributionSetById(rolloutRequestBody.getDistributionSetId()); .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class,
if (ds == null) { rolloutRequestBody.getDistributionSetId()));
throw new EntityNotFoundException(
"DistributionSet with Id {" + rolloutRequestBody.getDistributionSetId() + DOES_NOT_EXIST);
}
return ds;
} }
} }

View File

@@ -228,8 +228,9 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity<MgmtMetadata> getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId, public ResponseEntity<MgmtMetadata> getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) { @PathVariable("metadataKey") final String metadataKey) {
final SoftwareModuleMetadata findOne = softwareManagement.findSoftwareModuleMetadata(softwareModuleId, final SoftwareModuleMetadata findOne = softwareManagement
metadataKey); .findSoftwareModuleMetadata(softwareModuleId, metadataKey).orElseThrow(
() -> new EntityNotFoundException(SoftwareModuleMetadata.class, softwareModuleId, metadataKey));
return ResponseEntity.ok(toResponseSwMetadata(findOne)); return ResponseEntity.ok(toResponseSwMetadata(findOne));
} }
@@ -265,12 +266,11 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId, private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
final Long artifactId) { final Long artifactId) {
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId); final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
if (module == null) { .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist");
}
if (artifactId != null && !module.getArtifact(artifactId).isPresent()) { if (artifactId != null && !module.getArtifact(artifactId).isPresent()) {
throw new EntityNotFoundException("Artifact with Id {" + artifactId + "} does not exist"); throw new EntityNotFoundException(Artifact.class, artifactId);
} }
return module; return module;

View File

@@ -115,12 +115,8 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
} }
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) { private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
final SoftwareModuleType module = softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId); return softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId)
if (module == null) { .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId));
throw new EntityNotFoundException(
"SoftwareModuleType with Id {" + softwareModuleTypeId + "} does not exist");
}
return module;
} }
} }

View File

@@ -111,7 +111,6 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
@Override @Override
public ResponseEntity<Void> deleteFilter(@PathVariable("filterId") final Long filterId) { public ResponseEntity<Void> deleteFilter(@PathVariable("filterId") final Long filterId) {
findFilterWithExceptionIfNotFound(filterId);
filterManagement.deleteTargetFilterQuery(filterId); filterManagement.deleteTargetFilterQuery(filterId);
LOG.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK); LOG.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
@@ -145,11 +144,8 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
} }
private TargetFilterQuery findFilterWithExceptionIfNotFound(final Long filterId) { private TargetFilterQuery findFilterWithExceptionIfNotFound(final Long filterId) {
final TargetFilterQuery filter = filterManagement.findTargetFilterQueryById(filterId); return filterManagement.findTargetFilterQueryById(filterId)
if (filter == null) { .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, filterId));
throw new EntityNotFoundException("TargetFilterQuery with Id {" + filterId + "} does not exist");
}
return filter;
} }
} }

View File

@@ -184,7 +184,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
public ResponseEntity<MgmtAction> getAction(@PathVariable("controllerId") final String controllerId, public ResponseEntity<MgmtAction> getAction(@PathVariable("controllerId") final String controllerId,
@PathVariable("actionId") final Long actionId) { @PathVariable("actionId") final Long actionId) {
final Action action = findActionWithExceptionIfNotFound(actionId); final Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(controllerId)) { if (!action.getTarget().getControllerId().equals(controllerId)) {
LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), controllerId); LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), controllerId);
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
@@ -213,7 +214,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
public ResponseEntity<Void> cancelAction(@PathVariable("controllerId") final String controllerId, public ResponseEntity<Void> cancelAction(@PathVariable("controllerId") final String controllerId,
@PathVariable("actionId") final Long actionId, @PathVariable("actionId") final Long actionId,
@RequestParam(value = "force", required = false, defaultValue = "false") final boolean force) { @RequestParam(value = "force", required = false, defaultValue = "false") final boolean force) {
final Action action = findActionWithExceptionIfNotFound(actionId); final Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(controllerId)) { if (!action.getTarget().getControllerId().equals(controllerId)) {
LOG.warn("given action ({}) is not assigned to given target ({}).", actionId, controllerId); LOG.warn("given action ({}) is not assigned to given target ({}).", actionId, controllerId);
@@ -240,7 +242,9 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final Target target = findTargetWithExceptionIfNotFound(controllerId); final Target target = findTargetWithExceptionIfNotFound(controllerId);
final Action action = findActionWithExceptionIfNotFound(actionId); final Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getId().equals(target.getId())) { if (!action.getTarget().getId().equals(target.getId())) {
LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), target.getId()); LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), target.getId());
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
@@ -311,19 +315,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
} }
private Target findTargetWithExceptionIfNotFound(final String controllerId) { private Target findTargetWithExceptionIfNotFound(final String controllerId) {
final Target findTarget = this.targetManagement.findTargetByControllerID(controllerId); return targetManagement.findTargetByControllerID(controllerId)
if (findTarget == null) { .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
throw new EntityNotFoundException("Target with Id {" + controllerId + "} does not exist");
}
return findTarget;
}
private Action findActionWithExceptionIfNotFound(final Long actionId) {
final Action findAction = this.deploymentManagement.findAction(actionId);
if (findAction == null) {
throw new EntityNotFoundException("Action with Id {" + actionId + "} does not exist");
}
return findAction;
} }
} }

View File

@@ -173,11 +173,8 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
} }
private TargetTag findTargetTagById(final Long targetTagId) { private TargetTag findTargetTagById(final Long targetTagId) {
final TargetTag tag = this.tagManagement.findTargetTagById(targetTagId); return tagManagement.findTargetTagById(targetTagId)
if (tag == null) { .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId));
throw new EntityNotFoundException("Target Tag with Id {" + targetTagId + "} does not exist");
}
return tag;
} }
private List<String> findTargetControllerIds( private List<String> findTargetControllerIds(

View File

@@ -8,11 +8,10 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -30,7 +29,6 @@ import java.util.Set;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
@@ -42,7 +40,6 @@ import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.junit.Test; import org.junit.Test;
import org.springframework.context.annotation.Description; import org.springframework.context.annotation.Description;
@@ -54,6 +51,7 @@ import com.google.common.collect.Sets;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Stories; import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Management API") @Features("Component Tests - Management API")
@@ -427,7 +425,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.version("anotherVersion").requiredMigrationStep(true)); .version("anotherVersion").requiredMigrationStep(true));
// load also lazy stuff // load also lazy stuff
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).get();
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(1); .hasSize(1);
@@ -450,9 +448,9 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("$.content.[0].lastModifiedAt", equalTo(set.getLastModifiedAt()))) .andExpect(jsonPath("$.content.[0].lastModifiedAt", equalTo(set.getLastModifiedAt())))
.andExpect(jsonPath("$.content.[0].version", equalTo(set.getVersion()))) .andExpect(jsonPath("$.content.[0].version", equalTo(set.getVersion())))
.andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + runtimeType.getKey() + ")].id", .andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
contains(set.findFirstModuleByType(runtimeType).getId().intValue()))) contains(set.findFirstModuleByType(runtimeType).get().getId().intValue())))
.andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + appType.getKey() + ")].id", .andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + appType.getKey() + ")].id",
contains(set.findFirstModuleByType(appType).getId().intValue()))) contains(set.findFirstModuleByType(appType).get().getId().intValue())))
.andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + osType.getKey() + ")].id", .andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + osType.getKey() + ")].id",
contains(getOsModule(set).intValue()))); contains(getOsModule(set).intValue())));
} }
@@ -481,9 +479,9 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("$.lastModifiedAt", equalTo(set.getLastModifiedAt()))) .andExpect(jsonPath("$.lastModifiedAt", equalTo(set.getLastModifiedAt())))
.andExpect(jsonPath("$.version", equalTo(set.getVersion()))) .andExpect(jsonPath("$.version", equalTo(set.getVersion())))
.andExpect(jsonPath("$.modules.[?(@.type==" + runtimeType.getKey() + ")].id", .andExpect(jsonPath("$.modules.[?(@.type==" + runtimeType.getKey() + ")].id",
contains(set.findFirstModuleByType(runtimeType).getId().intValue()))) contains(set.findFirstModuleByType(runtimeType).get().getId().intValue())))
.andExpect(jsonPath("$.modules.[?(@.type==" + appType.getKey() + ")].id", .andExpect(jsonPath("$.modules.[?(@.type==" + appType.getKey() + ")].id",
contains(set.findFirstModuleByType(appType).getId().intValue()))) contains(set.findFirstModuleByType(appType).get().getId().intValue())))
.andExpect(jsonPath("$.modules.[?(@.type==" + osType.getKey() + ")].id", .andExpect(jsonPath("$.modules.[?(@.type==" + osType.getKey() + ")].id",
contains(getOsModule(set).intValue()))); contains(getOsModule(set).intValue())));
@@ -492,7 +490,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that multipe DS posted to API are created in the repository.") @Description("Ensures that multipe DS posted to API are created in the repository.")
public void createDistributionSets() throws JSONException, Exception { public void createDistributionSets() throws Exception {
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(0); .hasSize(0);
@@ -507,61 +505,16 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
DistributionSet three = testdataFactory.generateDistributionSet("three", "three", standardDsType, DistributionSet three = testdataFactory.generateDistributionSet("three", "three", standardDsType,
Lists.newArrayList(os, jvm, ah), true); Lists.newArrayList(os, jvm, ah), true);
final List<DistributionSet> sets = Lists.newArrayList(one, two, three);
final long current = System.currentTimeMillis(); final long current = System.currentTimeMillis();
final MvcResult mvcResult = mvc final MvcResult mvcResult = executeMgmtTargetPost(one, two, three);
.perform(post("/rest/v1/distributionsets/").content(JsonBuilder.distributionSets(sets))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("[0]name", equalTo(one.getName())))
.andExpect(jsonPath("[0]description", equalTo(one.getDescription())))
.andExpect(jsonPath("[0]type", equalTo(standardDsType.getKey())))
.andExpect(jsonPath("[0]createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[0]version", equalTo(one.getVersion())))
.andExpect(jsonPath("[0]complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("[0]requiredMigrationStep", equalTo(one.isRequiredMigrationStep())))
.andExpect(jsonPath("[0].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
contains(one.findFirstModuleByType(runtimeType).getId().intValue())))
.andExpect(jsonPath("[0].modules.[?(@.type==" + appType.getKey() + ")].id",
contains(one.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("[0].modules.[?(@.type==" + osType.getKey() + ")].id",
contains(one.findFirstModuleByType(osType).getId().intValue())))
.andExpect(jsonPath("[1]name", equalTo(two.getName())))
.andExpect(jsonPath("[1]description", equalTo(two.getDescription())))
.andExpect(jsonPath("[1]complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("[1]type", equalTo(standardDsType.getKey())))
.andExpect(jsonPath("[1]createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[1]version", equalTo(two.getVersion())))
.andExpect(jsonPath("[1].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
contains(two.findFirstModuleByType(runtimeType).getId().intValue())))
.andExpect(jsonPath("[1].modules.[?(@.type==" + appType.getKey() + ")].id",
contains(two.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("[1].modules.[?(@.type==" + osType.getKey() + ")].id",
contains(two.findFirstModuleByType(osType).getId().intValue())))
.andExpect(jsonPath("[1]requiredMigrationStep", equalTo(two.isRequiredMigrationStep())))
.andExpect(jsonPath("[2]name", equalTo(three.getName())))
.andExpect(jsonPath("[2]description", equalTo(three.getDescription())))
.andExpect(jsonPath("[2]complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("[2]type", equalTo(standardDsType.getKey())))
.andExpect(jsonPath("[2]createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[2]version", equalTo(three.getVersion())))
.andExpect(jsonPath("[2].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
contains(three.findFirstModuleByType(runtimeType).getId().intValue())))
.andExpect(jsonPath("[2].modules.[?(@.type==" + appType.getKey() + ")].id",
contains(three.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("[2].modules.[?(@.type==" + osType.getKey() + ")].id",
contains(three.findFirstModuleByType(osType).getId().intValue())))
.andExpect(jsonPath("[2]requiredMigrationStep", equalTo(three.isRequiredMigrationStep()))).andReturn();
one = distributionSetManagement.findDistributionSetByIdWithDetails( one = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
distributionSetManagement.findDistributionSetByNameAndVersion("one", "one").getId()); .findDistributionSetsAll("name==one", pageReq, false).getContent().get(0).getId()).get();
two = distributionSetManagement.findDistributionSetByIdWithDetails( two = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
distributionSetManagement.findDistributionSetByNameAndVersion("two", "two").getId()); .findDistributionSetsAll("name==two", pageReq, false).getContent().get(0).getId()).get();
three = distributionSetManagement.findDistributionSetByIdWithDetails( three = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
distributionSetManagement.findDistributionSetByNameAndVersion("three", "three").getId()); .findDistributionSetsAll("name==three", pageReq, false).getContent().get(0).getId()).get();
assertThat( assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
@@ -603,6 +556,56 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
assertThat(three.getCreatedAt()).isGreaterThanOrEqualTo(current); assertThat(three.getCreatedAt()).isGreaterThanOrEqualTo(current);
} }
@Step
private MvcResult executeMgmtTargetPost(final DistributionSet one, final DistributionSet two,
final DistributionSet three) throws Exception {
return mvc
.perform(post("/rest/v1/distributionsets/")
.content(JsonBuilder.distributionSets(Lists.newArrayList(one, two, three)))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("[0]name", equalTo(one.getName())))
.andExpect(jsonPath("[0]description", equalTo(one.getDescription())))
.andExpect(jsonPath("[0]type", equalTo(standardDsType.getKey())))
.andExpect(jsonPath("[0]createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[0]version", equalTo(one.getVersion())))
.andExpect(jsonPath("[0]complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("[0]requiredMigrationStep", equalTo(one.isRequiredMigrationStep())))
.andExpect(jsonPath("[0].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
contains(one.findFirstModuleByType(runtimeType).get().getId().intValue())))
.andExpect(jsonPath("[0].modules.[?(@.type==" + appType.getKey() + ")].id",
contains(one.findFirstModuleByType(appType).get().getId().intValue())))
.andExpect(jsonPath("[0].modules.[?(@.type==" + osType.getKey() + ")].id",
contains(one.findFirstModuleByType(osType).get().getId().intValue())))
.andExpect(jsonPath("[1]name", equalTo(two.getName())))
.andExpect(jsonPath("[1]description", equalTo(two.getDescription())))
.andExpect(jsonPath("[1]complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("[1]type", equalTo(standardDsType.getKey())))
.andExpect(jsonPath("[1]createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[1]version", equalTo(two.getVersion())))
.andExpect(jsonPath("[1].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
contains(two.findFirstModuleByType(runtimeType).get().getId().intValue())))
.andExpect(jsonPath("[1].modules.[?(@.type==" + appType.getKey() + ")].id",
contains(two.findFirstModuleByType(appType).get().getId().intValue())))
.andExpect(jsonPath("[1].modules.[?(@.type==" + osType.getKey() + ")].id",
contains(two.findFirstModuleByType(osType).get().getId().intValue())))
.andExpect(jsonPath("[1]requiredMigrationStep", equalTo(two.isRequiredMigrationStep())))
.andExpect(jsonPath("[2]name", equalTo(three.getName())))
.andExpect(jsonPath("[2]description", equalTo(three.getDescription())))
.andExpect(jsonPath("[2]complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("[2]type", equalTo(standardDsType.getKey())))
.andExpect(jsonPath("[2]createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[2]version", equalTo(three.getVersion())))
.andExpect(jsonPath("[2].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
contains(three.findFirstModuleByType(runtimeType).get().getId().intValue())))
.andExpect(jsonPath("[2].modules.[?(@.type==" + appType.getKey() + ")].id",
contains(three.findFirstModuleByType(appType).get().getId().intValue())))
.andExpect(jsonPath("[2].modules.[?(@.type==" + osType.getKey() + ")].id",
contains(three.findFirstModuleByType(osType).get().getId().intValue())))
.andExpect(jsonPath("[2]requiredMigrationStep", equalTo(three.isRequiredMigrationStep()))).andReturn();
}
@Test @Test
@Description("Ensures that DS deletion request to API is reflected by the repository.") @Description("Ensures that DS deletion request to API is reflected by the repository.")
public void deleteUnassignedistributionSet() throws Exception { public void deleteUnassignedistributionSet() throws Exception {
@@ -625,6 +628,13 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(0); assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(0);
} }
@Test
@Description("Ensures that DS deletion request to API on an entity that does not exist results in NOT_FOUND.")
public void deleteDistributionSetThatDoesNotExistLeadsToNotFound() throws Exception {
mvc.perform(delete("/rest/v1/distributionsets/1234")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
}
@Test @Test
@Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.") @Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.")
public void deleteAssignedDistributionSet() throws Exception { public void deleteAssignedDistributionSet() throws Exception {
@@ -667,7 +677,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
final DistributionSet setupdated = distributionSetManagement.findDistributionSetById(set.getId()); final DistributionSet setupdated = distributionSetManagement.findDistributionSetById(set.getId()).get();
assertThat(setupdated.isRequiredMigrationStep()).isEqualTo(true); assertThat(setupdated.isRequiredMigrationStep()).isEqualTo(true);
assertThat(setupdated.getVersion()).isEqualTo("anotherVersion"); assertThat(setupdated.getVersion()).isEqualTo("anotherVersion");
@@ -693,7 +703,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isForbidden()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isForbidden());
final DistributionSet setupdated = distributionSetManagement.findDistributionSetById(set.getId()); final DistributionSet setupdated = distributionSetManagement.findDistributionSetById(set.getId()).get();
assertThat(setupdated.isRequiredMigrationStep()).isEqualTo(false); assertThat(setupdated.isRequiredMigrationStep()).isEqualTo(false);
assertThat(setupdated.getVersion()).isEqualTo(set.getVersion()); assertThat(setupdated.getVersion()).isEqualTo(set.getVersion());
@@ -776,10 +786,10 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("[1]key", equalTo(knownKey2))) .andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2))); .andExpect(jsonPath("[1]value", equalTo(knownValue2)));
final DistributionSetMetadata metaKey1 = distributionSetManagement.findDistributionSetMetadata(testDS.getId(), final DistributionSetMetadata metaKey1 = distributionSetManagement
knownKey1); .findDistributionSetMetadata(testDS.getId(), knownKey1).get();
final DistributionSetMetadata metaKey2 = distributionSetManagement.findDistributionSetMetadata(testDS.getId(), final DistributionSetMetadata metaKey2 = distributionSetManagement
knownKey2); .findDistributionSetMetadata(testDS.getId(), knownKey2).get();
assertThat(metaKey1.getValue()).isEqualTo(knownValue1); assertThat(metaKey1.getValue()).isEqualTo(knownValue1);
assertThat(metaKey2.getValue()).isEqualTo(knownValue2); assertThat(metaKey2.getValue()).isEqualTo(knownValue2);
@@ -804,8 +814,8 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue))); .andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
final DistributionSetMetadata assertDS = distributionSetManagement.findDistributionSetMetadata(testDS.getId(), final DistributionSetMetadata assertDS = distributionSetManagement
knownKey); .findDistributionSetMetadata(testDS.getId(), knownKey).get();
assertThat(assertDS.getValue()).isEqualTo(updateValue); assertThat(assertDS.getValue()).isEqualTo(updateValue);
} }
@@ -823,12 +833,28 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey)) mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
try { assertThat(distributionSetManagement.findDistributionSetMetadata(testDS.getId(), knownKey).isPresent())
distributionSetManagement.findDistributionSetMetadata(testDS.getId(), knownKey); .isFalse();
fail("expected EntityNotFoundException but didn't throw"); }
} catch (final EntityNotFoundException e) {
// ok as expected @Test
} @Description("Ensures that DS metadata deletion request to API on an entity that does not exist results in NOT_FOUND.")
public void deleteMetadataThatDoesNotExistLeadsToNotFound() throws Exception {
// prepare and create metadata for deletion
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
createDistributionSetMetadata(testDS.getId(), entityFactory.generateMetadata(knownKey, knownValue));
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/XXX", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
mvc.perform(delete("/rest/v1/distributionsets/1234/metadata/{key}", knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
assertThat(distributionSetManagement.findDistributionSetMetadata(testDS.getId(), knownKey).isPresent())
.isTrue();
} }
@Test @Test

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
@@ -32,7 +32,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.junit.Test; import org.junit.Test;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@@ -138,7 +137,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.")
public void createDistributionSetTypes() throws JSONException, Exception { public void createDistributionSetTypes() throws Exception {
final List<DistributionSetType> types = createTestDistributionSetTestTypes(); final List<DistributionSetType> types = createTestDistributionSetTestTypes();
@@ -149,9 +148,9 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Step @Step
private void verifyCreatedDistributionSetTypes(final MvcResult mvcResult) throws UnsupportedEncodingException { private void verifyCreatedDistributionSetTypes(final MvcResult mvcResult) throws UnsupportedEncodingException {
final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("testKey1"); final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("testKey1").get();
final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("testKey2"); final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("testKey2").get();
final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("testKey3"); final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("testKey3").get();
assertThat(created1.getMandatoryModuleTypes()).containsOnly(osType); assertThat(created1.getMandatoryModuleTypes()).containsOnly(osType);
assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType); assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType);
@@ -231,7 +230,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.")
public void addMandatoryModuleToDistributionSetType() throws JSONException, Exception { public void addMandatoryModuleToDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement DistributionSetType testType = distributionSetManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123") .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12")); .name("TestName123").description("Desc123").colour("col12"));
@@ -241,7 +240,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()); testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester"); assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2); assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
@@ -251,7 +250,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.")
public void addOptionalModuleToDistributionSetType() throws JSONException, Exception { public void addOptionalModuleToDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement DistributionSetType testType = distributionSetManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123") .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12")); .name("TestName123").description("Desc123").colour("col12"));
@@ -261,7 +260,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()); testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester"); assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2); assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).containsExactly(osType); assertThat(testType.getOptionalModuleTypes()).containsExactly(osType);
@@ -272,7 +271,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes GET requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes GET requests.")
public void getMandatoryModulesOfDistributionSetType() throws JSONException, Exception { public void getMandatoryModulesOfDistributionSetType() throws Exception {
final DistributionSetType testType = generateTestType(); final DistributionSetType testType = generateTestType();
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId()) mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
@@ -286,7 +285,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes GET requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes GET requests.")
public void getOptionalModulesOfDistributionSetType() throws JSONException, Exception { public void getOptionalModulesOfDistributionSetType() throws Exception {
final DistributionSetType testType = generateTestType(); final DistributionSetType testType = generateTestType();
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId()) mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
@@ -301,7 +300,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} GET requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} GET requests.")
public void getMandatoryModuleOfDistributionSetType() throws JSONException, Exception { public void getMandatoryModuleOfDistributionSetType() throws Exception {
final DistributionSetType testType = generateTestType(); final DistributionSetType testType = generateTestType();
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(), mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
@@ -328,7 +327,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} GET requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} GET requests.")
public void getOptionalModuleOfDistributionSetType() throws JSONException, Exception { public void getOptionalModuleOfDistributionSetType() throws Exception {
final DistributionSetType testType = generateTestType(); final DistributionSetType testType = generateTestType();
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(), mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
@@ -345,14 +344,14 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} DELETE requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} DELETE requests.")
public void removeMandatoryModuleToDistributionSetType() throws JSONException, Exception { public void removeMandatoryModuleToDistributionSetType() throws Exception {
DistributionSetType testType = generateTestType(); DistributionSetType testType = generateTestType();
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(), mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()); .andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()); testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester"); assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2); assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType); assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
@@ -362,14 +361,14 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} DELETE requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} DELETE requests.")
public void removeOptionalModuleToDistributionSetType() throws JSONException, Exception { public void removeOptionalModuleToDistributionSetType() throws Exception {
DistributionSetType testType = generateTestType(); DistributionSetType testType = generateTestType();
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(), mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()); .andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()); testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester"); assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2); assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).isEmpty(); assertThat(testType.getOptionalModuleTypes()).isEmpty();
@@ -413,6 +412,13 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES); assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
} }
@Test
@Description("Ensures that DS type deletion request to API on an entity that does not exist results in NOT_FOUND.")
public void deleteDistributionSetTypeThatDoesNotExistLeadsToNotFound() throws Exception {
mvc.perform(delete("/rest/v1/distributionsettypes/1234")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
}
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).") @Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).")

View File

@@ -42,8 +42,8 @@ public class MgmtDownloadResourceTest extends AbstractManagementApiIntegrationTe
public void setupCache() { public void setupCache() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("Test"); final DistributionSet distributionSet = testdataFactory.createDistributionSet("Test");
final SoftwareModule softwareModule = distributionSet.getModules().stream().findFirst().get(); final SoftwareModule softwareModule = distributionSet.getModules().stream().findAny().get();
final Artifact artifact = testdataFactory.createArtifacts(softwareModule.getId()).stream().findFirst().get(); final Artifact artifact = testdataFactory.createArtifacts(softwareModule.getId()).stream().findAny().get();
downloadIdCache.put(downloadIdSha1, new DownloadArtifactCache(DownloadType.BY_SHA1, artifact.getSha1Hash())); downloadIdCache.put(downloadIdSha1, new DownloadArtifactCache(DownloadType.BY_SHA1, artifact.getSha1Hash()));
} }

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.endsWith;
@@ -937,7 +937,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
// Run here, because Scheduler is disabled during tests // Run here, because Scheduler is disabled during tests
rolloutManagement.fillRolloutGroupsWithTargets(rollout.getId()); rolloutManagement.fillRolloutGroupsWithTargets(rollout.getId());
return rolloutManagement.findRolloutById(rollout.getId()); return rolloutManagement.findRolloutById(rollout.getId()).get();
} }
protected boolean success(final Rollout result) { protected boolean success(final Rollout result) {
@@ -948,7 +948,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
} }
public Rollout getRollout(final Long rolloutId) throws Exception { public Rollout getRollout(final Long rolloutId) throws Exception {
return rolloutManagement.findRolloutById(rolloutId); return rolloutManagement.findRolloutById(rolloutId).get();
} }
} }

View File

@@ -8,13 +8,12 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -37,7 +36,6 @@ import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.Constants; import org.eclipse.hawkbit.repository.Constants;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -48,7 +46,6 @@ import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -111,7 +108,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("$.description", equalTo(updateDescription))) .andExpect(jsonPath("$.description", equalTo(updateDescription)))
.andExpect(jsonPath("$.name", equalTo(knownSWName))).andReturn(); .andExpect(jsonPath("$.name", equalTo(knownSWName))).andReturn();
sm = softwareManagement.findSoftwareModuleById(sm.getId()); sm = softwareManagement.findSoftwareModuleById(sm.getId()).get();
assertThat(sm.getName()).isEqualTo(knownSWName); assertThat(sm.getName()).isEqualTo(knownSWName);
assertThat(sm.getVendor()).isEqualTo(updateVendor); assertThat(sm.getVendor()).isEqualTo(updateVendor);
assertThat(sm.getLastModifiedBy()).isEqualTo("smUpdateTester"); assertThat(sm.getLastModifiedBy()).isEqualTo("smUpdateTester");
@@ -144,7 +141,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
// check rest of response compared to DB // check rest of response compared to DB
final MgmtArtifact artResult = ResourceUtility final MgmtArtifact artResult = ResourceUtility
.convertArtifactResponse(mvcResult.getResponse().getContentAsString()); .convertArtifactResponse(mvcResult.getResponse().getContentAsString());
final Long artId = softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts().get(0).getId(); final Long artId = softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getId();
assertThat(artResult.getArtifactId()).as("Wrong artifact id").isEqualTo(artId); assertThat(artResult.getArtifactId()).as("Wrong artifact id").isEqualTo(artId);
assertThat(JsonPath.compile("$._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) assertThat(JsonPath.compile("$._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.as("Link contains no self url") .as("Link contains no self url")
@@ -164,21 +161,21 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
// binary // binary
try (InputStream fileInputStream = artifactManagement try (InputStream fileInputStream = artifactManagement
.loadArtifactBinary( .loadArtifactBinary(
softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts().get(0).getSha1Hash()) softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getSha1Hash())
.getFileInputStream()) { .getFileInputStream()) {
assertTrue("Wrong artifact content", assertTrue("Wrong artifact content",
IOUtils.contentEquals(new ByteArrayInputStream(random), fileInputStream)); IOUtils.contentEquals(new ByteArrayInputStream(random), fileInputStream));
} }
// hashes // hashes
assertThat(artifactManagement.findArtifactByFilename("origFilename").get(0).getSha1Hash()).as("Wrong sha1 hash") assertThat(artifactManagement.findArtifactByFilename("origFilename").get().getSha1Hash()).as("Wrong sha1 hash")
.isEqualTo(HashGeneratorUtils.generateSHA1(random)); .isEqualTo(HashGeneratorUtils.generateSHA1(random));
assertThat(artifactManagement.findArtifactByFilename("origFilename").get(0).getMd5Hash()).as("Wrong md5 hash") assertThat(artifactManagement.findArtifactByFilename("origFilename").get().getMd5Hash()).as("Wrong md5 hash")
.isEqualTo(HashGeneratorUtils.generateMD5(random)); .isEqualTo(HashGeneratorUtils.generateMD5(random));
// metadata // metadata
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts().get(0).getFilename()) assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getFilename())
.as("wrong metadata of the filename").isEqualTo("origFilename"); .as("wrong metadata of the filename").isEqualTo("origFilename");
} }
@@ -240,8 +237,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
// hashes // hashes
assertThat(artifactManagement.findArtifactByFilename("customFilename")).as("Local artifact is wrong") assertThat(artifactManagement.findArtifactByFilename("customFilename").isPresent())
.hasSize(1); .as("Local artifact is wrong").isTrue();
} }
@Test @Test
@@ -661,7 +658,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Verfies that the create request actually results in the creation of the modules in the repository.") @Description("Verfies that the create request actually results in the creation of the modules in the repository.")
public void createSoftwareModules() throws JSONException, Exception { public void createSoftwareModules() throws Exception {
final SoftwareModule os = entityFactory.softwareModule().create().name("name1").type(osType).version("version1") final SoftwareModule os = entityFactory.softwareModule().create().name("name1").type(osType).version("version1")
.vendor("vendor1").description("description1").build(); .vendor("vendor1").description("description1").build();
final SoftwareModule ah = entityFactory.softwareModule().create().name("name3").type(appType) final SoftwareModule ah = entityFactory.softwareModule().create().name("name3").type(appType)
@@ -689,10 +686,10 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[1].createdAt", not(equalTo(0)))).andReturn(); .andExpect(jsonPath("[1].createdAt", not(equalTo(0)))).andReturn();
final SoftwareModule osCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name1", "version1", final SoftwareModule osCreated = softwareManagement
osType.getId()); .findSoftwareModuleByNameAndVersion("name1", "version1", osType.getId()).get();
final SoftwareModule appCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name3", "version3", final SoftwareModule appCreated = softwareManagement
appType.getId()); .findSoftwareModuleByNameAndVersion("name3", "version3", appType.getId()).get();
assertThat( assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
@@ -749,17 +746,17 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
artifactManagement.createArtifact(new ByteArrayInputStream(random), ds1.findFirstModuleByType(appType).getId(), artifactManagement.createArtifact(new ByteArrayInputStream(random),
"file1", false); ds1.findFirstModuleByType(appType).get().getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(appType).getId())) mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(appType).get().getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(runtimeType).getId())) mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(runtimeType).get().getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(osType).getId())) mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(osType).get().getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// all 3 are now marked as deleted // all 3 are now marked as deleted
@@ -784,7 +781,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
// check repo before delete // check repo before delete
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1);
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts()).hasSize(2); assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()).hasSize(2);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2);
// delete // delete
@@ -795,7 +792,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("After the sm should be marked as deleted") assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("After the sm should be marked as deleted")
.hasSize(1); .hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts()) assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts())
.as("After delete artifact should available for marked as deleted sm's").hasSize(1); .as("After delete artifact should available for marked as deleted sm's").hasSize(1);
} }
@@ -823,8 +820,10 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("[1]key", equalTo(knownKey2))) .andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2))); .andExpect(jsonPath("[1]value", equalTo(knownValue2)));
final SoftwareModuleMetadata metaKey1 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey1); final SoftwareModuleMetadata metaKey1 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey1)
final SoftwareModuleMetadata metaKey2 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey2); .get();
final SoftwareModuleMetadata metaKey2 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey2)
.get();
assertThat(metaKey1.getValue()).as("Metadata key is wrong").isEqualTo(knownValue1); assertThat(metaKey1.getValue()).as("Metadata key is wrong").isEqualTo(knownValue1);
assertThat(metaKey2.getValue()).as("Metadata key is wrong").isEqualTo(knownValue2); assertThat(metaKey2.getValue()).as("Metadata key is wrong").isEqualTo(knownValue2);
@@ -850,7 +849,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue))); .andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
final SoftwareModuleMetadata assertDS = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey); final SoftwareModuleMetadata assertDS = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey)
.get();
assertThat(assertDS.getValue()).as("Metadata is wrong").isEqualTo(updateValue); assertThat(assertDS.getValue()).as("Metadata is wrong").isEqualTo(updateValue);
} }
@@ -868,12 +868,34 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey)) mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
try { assertThat(softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey).isPresent()).isFalse();
softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey); }
fail("expected EntityNotFoundException but didn't throw");
} catch (final EntityNotFoundException e) { @Test
// ok as expected @Description("Ensures that module metadta deletion request to API on an entity that does not exist results in NOT_FOUND.")
} public void deleteModuleMetadataThatDoesNotExistLeadsToNotFound() throws Exception {
// prepare and create metadata for deletion
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
softwareManagement.createSoftwareModuleMetadata(sm.getId(),
entityFactory.generateMetadata(knownKey, knownValue));
mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/XXX", sm.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
mvc.perform(delete("/rest/v1/softwaremodules/1234/metadata/{key}", knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
assertThat(softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey).isPresent()).isTrue();
}
@Test
@Description("Ensures that module deletion request to API on an entity that does not exist results in NOT_FOUND.")
public void deleteSoftwareModuleThatDoesNotExistLeadsToNotFound() throws Exception {
mvc.perform(delete("/rest/v1/softwaremodules/1234")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
} }
@Test @Test

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
@@ -30,7 +30,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.junit.Test; import org.junit.Test;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@@ -140,7 +139,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests when max assignment is smaller than 1") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests when max assignment is smaller than 1")
public void createSoftwareModuleTypesInvalidAssignmentBadRequest() throws JSONException, Exception { public void createSoftwareModuleTypesInvalidAssignmentBadRequest() throws Exception {
final List<SoftwareModuleType> types = new ArrayList<>(); final List<SoftwareModuleType> types = new ArrayList<>();
types.add(entityFactory.softwareModuleType().create().key("test-1").name("TestName-1").maxAssignments(-1) types.add(entityFactory.softwareModuleType().create().key("test-1").name("TestName-1").maxAssignments(-1)
@@ -161,7 +160,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.")
public void createSoftwareModuleTypes() throws JSONException, Exception { public void createSoftwareModuleTypes() throws Exception {
final List<SoftwareModuleType> types = Lists.newArrayList( final List<SoftwareModuleType> types = Lists.newArrayList(
entityFactory.softwareModuleType().create().key("test1").name("TestName1").description("Desc1") entityFactory.softwareModuleType().create().key("test1").name("TestName1").description("Desc1")
@@ -190,9 +189,9 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
.andExpect(jsonPath("[2].createdAt", not(equalTo(0)))) .andExpect(jsonPath("[2].createdAt", not(equalTo(0))))
.andExpect(jsonPath("[2].maxAssignments", equalTo(3))).andReturn(); .andExpect(jsonPath("[2].maxAssignments", equalTo(3))).andReturn();
final SoftwareModuleType created1 = softwareManagement.findSoftwareModuleTypeByKey("test1"); final SoftwareModuleType created1 = softwareManagement.findSoftwareModuleTypeByKey("test1").get();
final SoftwareModuleType created2 = softwareManagement.findSoftwareModuleTypeByKey("test2"); final SoftwareModuleType created2 = softwareManagement.findSoftwareModuleTypeByKey("test2").get();
final SoftwareModuleType created3 = softwareManagement.findSoftwareModuleTypeByKey("test3"); final SoftwareModuleType created3 = softwareManagement.findSoftwareModuleTypeByKey("test3").get();
assertThat( assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
@@ -239,6 +238,13 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3); assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
} }
@Test
@Description("Ensures that module type deletion request to API on an entity that does not exist results in NOT_FOUND.")
public void deleteSoftwareModuleTypeThatDoesNotExistLeadsToNotFound() throws Exception {
mvc.perform(delete("/rest/v1/softwaremoduletypes/1234")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
}
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).")

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.hasSize;
@@ -74,8 +74,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + filterQuery.getId())) mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + filterQuery.getId()))
.andExpect(status().isOk()); .andExpect(status().isOk());
final TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryById(filterQuery.getId()); assertThat(targetFilterQueryManagement.findTargetFilterQueryById(filterQuery.getId()).isPresent()).isFalse();
assertThat(tfq).isNull();
} }
@Test @Test
@@ -113,7 +112,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
.andExpect(jsonPath("$.query", equalTo(filterQuery2))) .andExpect(jsonPath("$.query", equalTo(filterQuery2)))
.andExpect(jsonPath("$.name", equalTo(filterName))); .andExpect(jsonPath("$.name", equalTo(filterName)));
final TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()); final TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get();
assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery2); assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery2);
assertThat(tfqCheck.getName()).isEqualTo(filterName); assertThat(tfqCheck.getName()).isEqualTo(filterName);
} }
@@ -136,7 +135,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
.andExpect(jsonPath("$.query", equalTo(filterQuery))) .andExpect(jsonPath("$.query", equalTo(filterQuery)))
.andExpect(jsonPath("$.name", equalTo(filterName2))); .andExpect(jsonPath("$.name", equalTo(filterName2)));
final TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()); final TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get();
assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery); assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery);
assertThat(tfqCheck.getName()).isEqualTo(filterName2); assertThat(tfqCheck.getName()).isEqualTo(filterName2);
} }
@@ -293,8 +292,9 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet()) assertThat(
.isEqualTo(set); targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get().getAutoAssignDistributionSet())
.isEqualTo(set);
final String hrefPrefix = "http://localhost" + MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" final String hrefPrefix = "http://localhost" + MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/"
+ tfq.getId(); + tfq.getId();
@@ -319,8 +319,9 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
final TargetFilterQuery tfq = createSingleTargetFilterQuery(knownName, knownQuery); final TargetFilterQuery tfq = createSingleTargetFilterQuery(knownName, knownQuery);
targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(tfq.getId(), set.getId()); targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(tfq.getId(), set.getId());
assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet()) assertThat(
.isEqualTo(set); targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get().getAutoAssignDistributionSet())
.isEqualTo(set);
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS")) mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS"))
.andExpect(status().isOk()).andExpect(jsonPath(JSON_PATH_NAME, equalTo(dsName))); .andExpect(status().isOk()).andExpect(jsonPath(JSON_PATH_NAME, equalTo(dsName)));
@@ -328,8 +329,9 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS")) mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS"))
.andExpect(status().isNoContent()); .andExpect(status().isNoContent());
assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet()) assertThat(
.isNull(); targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get().getAutoAssignDistributionSet())
.isNull();
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS")) mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS"))
.andExpect(status().isNoContent()); .andExpect(status().isNoContent());

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
@@ -226,12 +226,12 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
tA.getControllerId(), tA.getActions().get(0).getId())).andDo(MockMvcResultPrinter.print()) tA.getControllerId(), tA.getActions().get(0).getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNoContent()); .andExpect(status().isNoContent());
final Action action = deploymentManagement.findAction(tA.getActions().get(0).getId()); final Action action = deploymentManagement.findAction(tA.getActions().get(0).getId()).get();
// still active because in "canceling" state and waiting for controller // still active because in "canceling" state and waiting for controller
// feedback // feedback
assertThat(action.isActive()).isTrue(); assertThat(action.isActive()).isTrue();
final Target queryTarget = targetManagement.findTargetByControllerID(tA.getControllerId()); final Target queryTarget = targetManagement.findTargetByControllerID(tA.getControllerId()).get();
// action has not been cancelled confirmed from controller, so DS // action has not been cancelled confirmed from controller, so DS
// remains assigned until // remains assigned until
// confirmation // confirmation
@@ -301,13 +301,12 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId))
.andExpect(status().isOk()); .andExpect(status().isOk());
final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId); assertThat(targetManagement.findTargetByControllerID(knownControllerId).isPresent()).isFalse();
assertThat(findTargetByControllerID).isNull();
} }
@Test @Test
@Description("Ensures that deletion is refused with not found if target does not exist.") @Description("Ensures that deletion is refused with not found if target does not exist.")
public void deleteTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception { public void deleteTargetWhichDoesNotExistsLeadsToNotFound() throws Exception {
final String knownControllerId = "knownControllerIdDelete"; final String knownControllerId = "knownControllerIdDelete";
mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId))
@@ -316,7 +315,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
@Test @Test
@Description("Ensures that update is refused with not found if target does not exist.") @Description("Ensures that update is refused with not found if target does not exist.")
public void updateTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception { public void updateTargetWhichDoesNotExistsLeadsToNotFound() throws Exception {
final String knownControllerId = "knownControllerIdUpdate"; final String knownControllerId = "knownControllerIdUpdate";
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content("{}") mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content("{}")
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -341,7 +340,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.andExpect(jsonPath("$.description", equalTo(knownNewDescription))) .andExpect(jsonPath("$.description", equalTo(knownNewDescription)))
.andExpect(jsonPath("$.name", equalTo(knownNameNotModiy))); .andExpect(jsonPath("$.name", equalTo(knownNameNotModiy)));
final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId); final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId).get();
assertThat(findTargetByControllerID.getDescription()).isEqualTo(knownNewDescription); assertThat(findTargetByControllerID.getDescription()).isEqualTo(knownNewDescription);
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy); assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy);
} }
@@ -364,7 +363,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.andExpect(jsonPath("$.securityToken", equalTo(knownNewToken))) .andExpect(jsonPath("$.securityToken", equalTo(knownNewToken)))
.andExpect(jsonPath("$.name", equalTo(knownNameNotModiy))); .andExpect(jsonPath("$.name", equalTo(knownNameNotModiy)));
final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId); final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId).get();
assertThat(findTargetByControllerID.getSecurityToken()).isEqualTo(knownNewToken); assertThat(findTargetByControllerID.getSecurityToken()).isEqualTo(knownNewToken);
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy); assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy);
} }
@@ -387,7 +386,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.andExpect(jsonPath("$.address", equalTo(knownNewAddress))) .andExpect(jsonPath("$.address", equalTo(knownNewAddress)))
.andExpect(jsonPath("$.name", equalTo(knownNameNotModiy))); .andExpect(jsonPath("$.name", equalTo(knownNameNotModiy)));
final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId); final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId).get();
assertThat(findTargetByControllerID.getTargetInfo().getAddress().toString()).isEqualTo(knownNewAddress); assertThat(findTargetByControllerID.getTargetInfo().getAddress().toString()).isEqualTo(knownNewAddress);
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy); assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy);
} }
@@ -572,9 +571,9 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// test // test
final SoftwareModule os = ds.findFirstModuleByType(osType); final SoftwareModule os = ds.findFirstModuleByType(osType).get();
final SoftwareModule jvm = ds.findFirstModuleByType(runtimeType); final SoftwareModule jvm = ds.findFirstModuleByType(runtimeType).get();
final SoftwareModule bApp = ds.findFirstModuleByType(appType); final SoftwareModule bApp = ds.findFirstModuleByType(appType).get();
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/assignedDS")) mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/assignedDS"))
.andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print())
.andExpect(jsonPath(JSON_PATH_ID, equalTo(ds.getId().intValue()))) .andExpect(jsonPath(JSON_PATH_ID, equalTo(ds.getId().intValue())))
@@ -747,17 +746,17 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.isEqualTo("http://localhost/rest/v1/targets/id3"); .isEqualTo("http://localhost/rest/v1/targets/id3");
assertThat(targetManagement.findTargetByControllerID("id1")).isNotNull(); assertThat(targetManagement.findTargetByControllerID("id1")).isNotNull();
assertThat(targetManagement.findTargetByControllerID("id1").getName()).isEqualTo("testname1"); assertThat(targetManagement.findTargetByControllerID("id1").get().getName()).isEqualTo("testname1");
assertThat(targetManagement.findTargetByControllerID("id1").getDescription()).isEqualTo("testid1"); assertThat(targetManagement.findTargetByControllerID("id1").get().getDescription()).isEqualTo("testid1");
assertThat(targetManagement.findTargetByControllerID("id1").getSecurityToken()).isEqualTo("token"); assertThat(targetManagement.findTargetByControllerID("id1").get().getSecurityToken()).isEqualTo("token");
assertThat(targetManagement.findTargetByControllerID("id1").getTargetInfo().getAddress().toString()) assertThat(targetManagement.findTargetByControllerID("id1").get().getTargetInfo().getAddress().toString())
.isEqualTo("amqp://test123/foobar"); .isEqualTo("amqp://test123/foobar");
assertThat(targetManagement.findTargetByControllerID("id2")).isNotNull(); assertThat(targetManagement.findTargetByControllerID("id2")).isNotNull();
assertThat(targetManagement.findTargetByControllerID("id2").getName()).isEqualTo("testname2"); assertThat(targetManagement.findTargetByControllerID("id2").get().getName()).isEqualTo("testname2");
assertThat(targetManagement.findTargetByControllerID("id2").getDescription()).isEqualTo("testid2"); assertThat(targetManagement.findTargetByControllerID("id2").get().getDescription()).isEqualTo("testid2");
assertThat(targetManagement.findTargetByControllerID("id3")).isNotNull(); assertThat(targetManagement.findTargetByControllerID("id3")).isNotNull();
assertThat(targetManagement.findTargetByControllerID("id3").getName()).isEqualTo("testname3"); assertThat(targetManagement.findTargetByControllerID("id3").get().getName()).isEqualTo("testname3");
assertThat(targetManagement.findTargetByControllerID("id3").getDescription()).isEqualTo("testid3"); assertThat(targetManagement.findTargetByControllerID("id3").get().getDescription()).isEqualTo("testid3");
} }
@Test @Test
@@ -1079,7 +1078,8 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("fsdfsd").getAssignedDistributionSet()).isEqualTo(set); assertThat(targetManagement.findTargetByControllerID("fsdfsd").get().getAssignedDistributionSet())
.isEqualTo(set);
} }
@Test @Test
@@ -1101,7 +1101,8 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
assertThat(findActiveActionsByTarget).hasSize(1); assertThat(findActiveActionsByTarget).hasSize(1);
assertThat(findActiveActionsByTarget.get(0).getActionType()).isEqualTo(ActionType.TIMEFORCED); assertThat(findActiveActionsByTarget.get(0).getActionType()).isEqualTo(ActionType.TIMEFORCED);
assertThat(findActiveActionsByTarget.get(0).getForcedTime()).isEqualTo(forceTime); assertThat(findActiveActionsByTarget.get(0).getForcedTime()).isEqualTo(forceTime);
assertThat(targetManagement.findTargetByControllerID("fsdfsd").getAssignedDistributionSet()).isEqualTo(set); assertThat(targetManagement.findTargetByControllerID("fsdfsd").get().getAssignedDistributionSet())
.isEqualTo(set);
} }
@Test @Test
@@ -1279,6 +1280,6 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// verify active action // verify active action
final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq); final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq);
assertThat(actionsByTarget.getContent()).hasSize(1); assertThat(actionsByTarget.getContent()).hasSize(1);
return targetManagement.findTargetByControllerID(tA.getControllerId()); return targetManagement.findTargetByControllerID(tA.getControllerId()).get();
} }
} }

View File

@@ -62,13 +62,8 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.easytesting</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>fest-assert-core</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@@ -9,17 +9,17 @@
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNotFoundException;
import org.eclipse.hawkbit.repository.exception.ArtifactDeleteFailedException; import org.eclipse.hawkbit.repository.exception.ArtifactDeleteFailedException;
import org.eclipse.hawkbit.repository.exception.ArtifactUploadFailedException; import org.eclipse.hawkbit.repository.exception.ArtifactUploadFailedException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNotFoundException;
import org.eclipse.hawkbit.repository.exception.InvalidMD5HashException; import org.eclipse.hawkbit.repository.exception.InvalidMD5HashException;
import org.eclipse.hawkbit.repository.exception.InvalidSHA1HashException; import org.eclipse.hawkbit.repository.exception.InvalidSHA1HashException;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
@@ -119,7 +119,8 @@ public interface ArtifactManagement {
* of the {@link Artifact} that has to be deleted. * of the {@link Artifact} that has to be deleted.
* @throws ArtifactDeleteFailedException * @throws ArtifactDeleteFailedException
* if deletion failed (MongoDB is not available) * if deletion failed (MongoDB is not available)
* * @throws EntityNotFoundException
* if artifact with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteArtifact(@NotNull Long id); void deleteArtifact(@NotNull Long id);
@@ -129,12 +130,11 @@ public interface ArtifactManagement {
* *
* @param id * @param id
* to search for * to search for
* @return found {@link Artifact} or <code>null</code> is it could not be * @return found {@link Artifact}
* found.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER) + SpringEvalExpressions.IS_CONTROLLER)
Artifact findArtifact(@NotNull Long id); Optional<Artifact> findArtifact(@NotNull Long id);
/** /**
* Find by artifact by software module id and filename. * Find by artifact by software module id and filename.
@@ -143,11 +143,11 @@ public interface ArtifactManagement {
* file name * file name
* @param softwareModuleId * @param softwareModuleId
* software module id. * software module id.
* @return Artifact if artifact present * @return found {@link Artifact}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER) + SpringEvalExpressions.IS_CONTROLLER)
List<Artifact> findByFilenameAndSoftwareModule(@NotNull String filename, @NotNull Long softwareModuleId); Optional<Artifact> findByFilenameAndSoftwareModule(@NotNull String filename, @NotNull Long softwareModuleId);
/** /**
* Find all local artifact by sha1 and return the first artifact. * Find all local artifact by sha1 and return the first artifact.
@@ -158,7 +158,7 @@ public interface ArtifactManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER) + SpringEvalExpressions.IS_CONTROLLER)
Artifact findFirstArtifactBySHA1(@NotNull String sha1); Optional<Artifact> findFirstArtifactBySHA1(@NotNull String sha1);
/** /**
* Searches for {@link Artifact} with given file name. * Searches for {@link Artifact} with given file name.
@@ -169,7 +169,7 @@ public interface ArtifactManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER) + SpringEvalExpressions.IS_CONTROLLER)
List<Artifact> findArtifactByFilename(@NotNull String filename); Optional<Artifact> findArtifactByFilename(@NotNull String filename);
/** /**
* Get local artifact for a base software module. * Get local artifact for a base software module.

View File

@@ -106,6 +106,9 @@ public interface ControllerManagement {
* @throws TooManyStatusEntriesException * @throws TooManyStatusEntriesException
* if more than the allowed number of status entries are * if more than the allowed number of status entries are
* inserted * inserted
*
* @throws EntityNotFoundException
* if action status not exist
*/ */
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action addUpdateActionStatus(@NotNull ActionStatusCreate create); Action addUpdateActionStatus(@NotNull ActionStatusCreate create);
@@ -117,9 +120,6 @@ public interface ControllerManagement {
* @param controllerId * @param controllerId
* identifies the target to retrieve the actions from * identifies the target to retrieve the actions from
* @return a list of actions assigned to given target which are active * @return a list of actions assigned to given target which are active
*
* @throws EntityNotFoundException
* if target with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Optional<Action> findOldestActiveActionByTarget(@NotNull String controllerId); Optional<Action> findOldestActiveActionByTarget(@NotNull String controllerId);
@@ -133,7 +133,7 @@ public interface ControllerManagement {
* @return the corresponding {@link Action} * @return the corresponding {@link Action}
*/ */
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action findActionWithDetails(@NotNull Long actionId); Optional<Action> findActionWithDetails(@NotNull Long actionId);
/** /**
* register new target in the repository (plug-and-play). * register new target in the repository (plug-and-play).
@@ -149,19 +149,19 @@ public interface ControllerManagement {
/** /**
* Retrieves last {@link Action} for a download of an artifact of given * Retrieves last {@link Action} for a download of an artifact of given
* module and target. * module and target if exists and is not canceled.
* *
* @param controllerId * @param controllerId
* to look for * to look for
* @param module * @param moduleId
* that should be assigned to the target * of the the {@link SoftwareModule} that should be assigned to
* the target
* @return last {@link Action} for given combination * @return last {@link Action} for given combination
* *
* @throws EntityNotFoundException
* if action for given combination could not be found
*/ */
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action getActionForDownloadByTargetAndSoftwareModule(@NotEmpty String controllerId, @NotNull SoftwareModule module); Optional<Action> getActionForDownloadByTargetAndSoftwareModule(@NotEmpty String controllerId,
@NotNull Long moduleId);
/** /**
* @return current {@link TenantConfigurationKey#POLLING_TIME_INTERVAL}. * @return current {@link TenantConfigurationKey#POLLING_TIME_INTERVAL}.
@@ -271,7 +271,7 @@ public interface ControllerManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE) + SpringEvalExpressions.IS_SYSTEM_CODE)
Target findByControllerId(@NotEmpty String controllerId); Optional<Target> findByControllerId(@NotEmpty String controllerId);
/** /**
* Finds {@link Target} based on given ID returns found Target without * Finds {@link Target} based on given ID returns found Target without
@@ -285,6 +285,6 @@ public interface ControllerManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE) + SpringEvalExpressions.IS_SYSTEM_CODE)
Target findByTargetId(@NotNull Long targetId); Optional<Target> findByTargetId(@NotNull Long targetId);
} }

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@@ -123,12 +124,11 @@ public interface DeploymentManagement {
* @param actionId * @param actionId
* to be canceled * to be canceled
* *
* @return generated {@link Action} or <code>null</code> if not active on * @return canceled {@link Action}
* given {@link Target}. *
* @throws CancelActionNotAllowedException * @throws CancelActionNotAllowedException
* in case the given action is not active or is already a cancel * in case the given action is not active or is already a cancel
* action * action
*
* @throws EntityNotFoundException * @throws EntityNotFoundException
* if action with given ID does not exist * if action with given ID does not exist
*/ */
@@ -181,9 +181,10 @@ public interface DeploymentManagement {
* @param actionId * @param actionId
* to be id of the action * to be id of the action
* @return the corresponding {@link Action} * @return the corresponding {@link Action}
*
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Action findAction(@NotNull Long actionId); Optional<Action> findAction(@NotNull Long actionId);
/** /**
* Retrieves all {@link Action}s from repository. * Retrieves all {@link Action}s from repository.
@@ -242,6 +243,7 @@ public interface DeploymentManagement {
* @param pageable * @param pageable
* the pageable request to limit, sort the actions * the pageable request to limit, sort the actions
* @return a slice of actions found for a specific target * @return a slice of actions found for a specific target
*
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Action> findActionsByTarget(@NotEmpty String controllerId, @NotNull Pageable pageable); Slice<Action> findActionsByTarget(@NotEmpty String controllerId, @NotNull Pageable pageable);
@@ -255,6 +257,9 @@ public interface DeploymentManagement {
* @param actionId * @param actionId
* to be filtered on * to be filtered on
* @return the corresponding {@link Page} of {@link ActionStatus} * @return the corresponding {@link Page} of {@link ActionStatus}
*
* @throws EntityNotFoundException
* if action with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<ActionStatus> findActionStatusByAction(@NotNull Pageable pageReq, @NotNull Long actionId); Page<ActionStatus> findActionStatusByAction(@NotNull Pageable pageReq, @NotNull Long actionId);
@@ -268,6 +273,9 @@ public interface DeploymentManagement {
* @param actionId * @param actionId
* the {@link Action} to retrieve the {@link ActionStatus} from * the {@link Action} to retrieve the {@link ActionStatus} from
* @return a page of {@link ActionStatus} by a speciifc {@link Action} * @return a page of {@link ActionStatus} by a speciifc {@link Action}
*
* @throws EntityNotFoundException
* if action with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<ActionStatus> findActionStatusByActionWithMessages(@NotNull Pageable pageable, @NotNull Long actionId); Page<ActionStatus> findActionStatusByActionWithMessages(@NotNull Pageable pageable, @NotNull Long actionId);
@@ -292,7 +300,7 @@ public interface DeploymentManagement {
* @return the corresponding {@link Action} * @return the corresponding {@link Action}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Action findActionWithDetails(@NotNull Long actionId); Optional<Action> findActionWithDetails(@NotNull Long actionId);
/** /**
* Retrieves all active {@link Action}s of a specific target ordered by * Retrieves all active {@link Action}s of a specific target ordered by
@@ -325,8 +333,8 @@ public interface DeploymentManagement {
* @param actionId * @param actionId
* to be canceled * to be canceled
* *
* @return generated {@link Action} or <code>null</code> if not active on * @return quite {@link Action}
* {@link Target}. *
* @throws CancelActionNotAllowedException * @throws CancelActionNotAllowedException
* in case the given action is not active * in case the given action is not active
* *
@@ -343,6 +351,9 @@ public interface DeploymentManagement {
* @param actionId * @param actionId
* the ID of the action * the ID of the action
* @return the updated or the found {@link Action} * @return the updated or the found {@link Action}
*
* @throws EntityNotFoundException
* if action with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
Action forceTargetAction(@NotNull Long actionId); Action forceTargetAction(@NotNull Long actionId);

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@@ -60,7 +61,7 @@ public interface DistributionSetManagement {
* @return the updated {@link DistributionSet}. * @return the updated {@link DistributionSet}.
* *
* @throws EntityNotFoundException * @throws EntityNotFoundException
* if given module does not exist * if (at least one) given module does not exist
* *
* @throws EntityReadOnlyException * @throws EntityReadOnlyException
* if use tries to change the {@link DistributionSet} s while * if use tries to change the {@link DistributionSet} s while
@@ -86,7 +87,8 @@ public interface DistributionSetManagement {
* @return list of assigned ds * @return list of assigned ds
* *
* @throws EntityNotFoundException * @throws EntityNotFoundException
* if tag with given ID does not exist * if tag with given ID does not exist or (at least one) of the
* distribution sets.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List<DistributionSet> assignTag(@NotEmpty Collection<Long> dsIds, @NotNull Long tagId); List<DistributionSet> assignTag(@NotEmpty Collection<Long> dsIds, @NotNull Long tagId);
@@ -108,6 +110,9 @@ public interface DistributionSetManagement {
* to look for * to look for
* *
* @return number of {@link DistributionSet}s * @return number of {@link DistributionSet}s
*
* @throws EntityNotFoundException
* if type with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetsByType(@NotNull Long typeId); Long countDistributionSetsByType(@NotNull Long typeId);
@@ -214,9 +219,13 @@ public interface DistributionSetManagement {
* result means that they cannot be assigned anymore to any targets. (define * result means that they cannot be assigned anymore to any targets. (define
* e.g. findByDeletedFalse()) * e.g. findByDeletedFalse())
* </p> * </p>
* *
* @param setId * @param setId
* to delete * to delete
*
* @throws EntityNotFoundException
* if given {@link DistributionSet} does not exist
*
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSet(@NotNull Long setId); void deleteDistributionSet(@NotNull Long setId);
@@ -228,6 +237,9 @@ public interface DistributionSetManagement {
* *
* @param dsIds * @param dsIds
* to be deleted * to be deleted
*
* @throws EntityNotFoundException
* if (at least one) given distribution set does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSet(@NotEmpty Collection<Long> dsIds); void deleteDistributionSet(@NotEmpty Collection<Long> dsIds);
@@ -264,9 +276,12 @@ public interface DistributionSetManagement {
* @param actionId * @param actionId
* the action associated with the distribution set * the action associated with the distribution set
* @return the distribution set which is associated with the action * @return the distribution set which is associated with the action
*
* @throws EntityNotFoundException
* if action with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSet findDistributionSetByAction(@NotNull Long actionId); Optional<DistributionSet> findDistributionSetByAction(@NotNull Long actionId);
/** /**
* Find {@link DistributionSet} based on given ID without details, e.g. * Find {@link DistributionSet} based on given ID without details, e.g.
@@ -274,10 +289,11 @@ public interface DistributionSetManagement {
* *
* @param distid * @param distid
* to look for. * to look for.
* @return {@link DistributionSet} or <code>null</code> if it does not exist * @return {@link DistributionSet}
*
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSet findDistributionSetById(@NotNull Long distid); Optional<DistributionSet> findDistributionSetById(@NotNull Long distid);
/** /**
* Find {@link DistributionSet} based on given ID including (lazy loaded) * Find {@link DistributionSet} based on given ID including (lazy loaded)
@@ -288,10 +304,10 @@ public interface DistributionSetManagement {
* *
* @param distid * @param distid
* to look for. * to look for.
* @return {@link DistributionSet} or <code>null</code> if it does not exist * @return {@link DistributionSet}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSet findDistributionSetByIdWithDetails(@NotNull Long distid); Optional<DistributionSet> findDistributionSetByIdWithDetails(@NotNull Long distid);
/** /**
* Find distribution set by name and version. * Find distribution set by name and version.
@@ -303,7 +319,8 @@ public interface DistributionSetManagement {
* @return the page with the found {@link DistributionSet} * @return the page with the found {@link DistributionSet}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSet findDistributionSetByNameAndVersion(@NotEmpty String distributionName, @NotEmpty String version); Optional<DistributionSet> findDistributionSetByNameAndVersion(@NotEmpty String distributionName,
@NotEmpty String version);
/** /**
* finds all meta data by the given distribution set id. * finds all meta data by the given distribution set id.
@@ -314,21 +331,14 @@ public interface DistributionSetManagement {
* the page request to page the result * the page request to page the result
* @return a paged result of all meta data entries for a given distribution * @return a paged result of all meta data entries for a given distribution
* set id * set id
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId, Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId,
@NotNull Pageable pageable); @NotNull Pageable pageable);
/**
* Finds all meta data by the given distribution set id.
*
* @param distributionSetId
* the distribution set id to retrieve the meta data from
* @return list of distributionSetMetadata for a given distribution set Id.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId);
/** /**
* finds all meta data by the given distribution set id. * finds all meta data by the given distribution set id.
* *
@@ -346,6 +356,9 @@ public interface DistributionSetManagement {
* given {@code fieldNameProvider} * given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException * @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong * if the RSQL syntax is wrong
*
* @throws EntityNotFoundException
* of distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId, Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId,
@@ -449,27 +462,27 @@ public interface DistributionSetManagement {
/** /**
* @param id * @param id
* as {@link DistributionSetType#getId()} * as {@link DistributionSetType#getId()}
* @return {@link DistributionSetType} if found or <code>null</code> if not * @return {@link DistributionSetType}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetType findDistributionSetTypeById(@NotNull Long id); Optional<DistributionSetType> findDistributionSetTypeById(@NotNull Long id);
/** /**
* @param key * @param key
* as {@link DistributionSetType#getKey()} * as {@link DistributionSetType#getKey()}
* @return {@link DistributionSetType} if found or <code>null</code> if not * @return {@link DistributionSetType}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetType findDistributionSetTypeByKey(@NotEmpty String key); Optional<DistributionSetType> findDistributionSetTypeByKey(@NotEmpty String key);
/** /**
* @param name * @param name
* as {@link DistributionSetType#getName()} * as {@link DistributionSetType#getName()}
* @return {@link DistributionSetType} if found or <code>null</code> if not * @return {@link DistributionSetType}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetType findDistributionSetTypeByName(@NotEmpty String name); Optional<DistributionSetType> findDistributionSetTypeByName(@NotEmpty String name);
/** /**
* @param pageable * @param pageable
@@ -506,11 +519,9 @@ public interface DistributionSetManagement {
* @param key * @param key
* of the meta data element * of the meta data element
* @return the found DistributionSetMetadata or {@code null} if not exits * @return the found DistributionSetMetadata or {@code null} if not exits
* @throws EntityNotFoundException
* in case the meta data does not exists for the given key
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetMetadata findDistributionSetMetadata(@NotNull Long setId, @NotEmpty String key); Optional<DistributionSetMetadata> findDistributionSetMetadata(@NotNull Long setId, @NotEmpty String key);
/** /**
* Checks if a {@link DistributionSet} is currently in use by a target in * Checks if a {@link DistributionSet} is currently in use by a target in
@@ -536,6 +547,9 @@ public interface DistributionSetManagement {
* to toggle * to toggle
* @return {@link DistributionSetTagAssignmentResult} with all meta data of * @return {@link DistributionSetTagAssignmentResult} with all meta data of
* the assignment outcome. * the assignment outcome.
*
* @throws EntityNotFoundException
* if given tag does not exist or (at least one) module
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<Long> dsIds, @NotNull String tagName); DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<Long> dsIds, @NotNull String tagName);
@@ -715,6 +729,6 @@ public interface DistributionSetManagement {
* @return the found {@link DistributionSet}s * @return the found {@link DistributionSet}s
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<DistributionSet> findDistributionSetAllById(@NotNull Collection<Long> ids); List<DistributionSet> findDistributionSetAllById(@NotEmpty Collection<Long> ids);
} }

View File

@@ -8,6 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
@@ -67,9 +69,10 @@ public interface RolloutGroupManagement {
* the ID of the rollout group to find * the ID of the rollout group to find
* @return the found {@link RolloutGroup} by its ID or {@code null} if it * @return the found {@link RolloutGroup} by its ID or {@code null} if it
* does not exists * does not exists
*
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
RolloutGroup findRolloutGroupById(@NotNull Long rolloutGroupId); Optional<RolloutGroup> findRolloutGroupById(@NotNull Long rolloutGroupId);
/** /**
* Retrieves a page of {@link RolloutGroup}s filtered by a given * Retrieves a page of {@link RolloutGroup}s filtered by a given
@@ -151,9 +154,10 @@ public interface RolloutGroupManagement {
* @param rolloutGroupId * @param rolloutGroupId
* rollout group id * rollout group id
* @return rolloutGroup with details of targets count for different statuses * @return rolloutGroup with details of targets count for different statuses
*
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
RolloutGroup findRolloutGroupWithDetailedStatus(@NotNull Long rolloutGroupId); Optional<RolloutGroup> findRolloutGroupWithDetailedStatus(@NotNull Long rolloutGroupId);
/** /**
* Count targets of rollout group. * Count targets of rollout group.

View File

@@ -9,7 +9,7 @@
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.util.List; import java.util.List;
import java.util.concurrent.Future; import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@@ -45,8 +45,8 @@ public interface RolloutManagement {
/** /**
* Checking running rollouts. Rollouts which are checked updating the * Checking running rollouts. Rollouts which are checked updating the
* lastCheck to indicate that the current instance * lastCheck to indicate that the current instance is handling the specific
* is handling the specific rollout. This code should run as system-code. * rollout. This code should run as system-code.
* *
* <pre> * <pre>
* {@code * {@code
@@ -58,9 +58,8 @@ public interface RolloutManagement {
* } * }
* </pre> * </pre>
* *
* This method is intended to be called by a scheduler. * This method is intended to be called by a scheduler. And must be running
* And must be running in an transaction so it's * in an transaction so it's splitted from the scheduler.
* splitted from the scheduler.
* *
* Rollouts which are currently running are investigated, by means the * Rollouts which are currently running are investigated, by means the
* error- and finish condition of running groups in this rollout are * error- and finish condition of running groups in this rollout are
@@ -292,7 +291,7 @@ public interface RolloutManagement {
* not exists * not exists
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Rollout findRolloutById(@NotNull Long rolloutId); Optional<Rollout> findRolloutById(@NotNull Long rolloutId);
/** /**
* Retrieves a specific rollout by its name. * Retrieves a specific rollout by its name.
@@ -303,7 +302,7 @@ public interface RolloutManagement {
* does not exists * does not exists
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Rollout findRolloutByName(@NotNull String rolloutName); Optional<Rollout> findRolloutByName(@NotEmpty String rolloutName);
/** /**
* Get count of targets in different status in rollout. * Get count of targets in different status in rollout.
@@ -311,10 +310,21 @@ public interface RolloutManagement {
* @param rolloutId * @param rolloutId
* rollout id * rollout id
* @return rollout details of targets count for different statuses * @return rollout details of targets count for different statuses
*
* *
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Rollout findRolloutWithDetailedStatus(@NotNull Long rolloutId); Optional<Rollout> findRolloutWithDetailedStatus(@NotNull Long rolloutId);
/**
* Checks if rollout with given ID exists.
*
* @param rolloutId
* rollout id
*
* @return <code>true</code> if rollout exists
*/
boolean exists(@NotNull Long rolloutId);
/*** /***
* Get finished percentage details for a specified group which is in running * Get finished percentage details for a specified group which is in running
@@ -378,7 +388,7 @@ public interface RolloutManagement {
* all actions are created and the first group is started. The rollout * all actions are created and the first group is started. The rollout
* itself will be then also in {@link RolloutStatus#RUNNING}. * itself will be then also in {@link RolloutStatus#RUNNING}.
* *
* @param rollout * @param rolloutId
* the rollout to be started * the rollout to be started
* *
* @return started rollout * @return started rollout
@@ -390,7 +400,7 @@ public interface RolloutManagement {
* ready rollouts can be started. * ready rollouts can be started.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
Rollout startRollout(@NotNull Long rollout); Rollout startRollout(@NotNull Long rolloutId);
/** /**
* Update rollout details. * Update rollout details.
@@ -399,6 +409,10 @@ public interface RolloutManagement {
* rollout to be updated * rollout to be updated
* *
* @return Rollout updated rollout * @return Rollout updated rollout
*
* @throws EntityNotFoundException
* if rollout or DS with given IDs do not exist
*
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
Rollout updateRollout(@NotNull RolloutUpdate update); Rollout updateRollout(@NotNull RolloutUpdate update);

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@@ -50,6 +51,9 @@ public interface SoftwareManagement {
* @param typeId * @param typeId
* to filter the result by type * to filter the result by type
* @return number of found {@link SoftwareModule}s * @return number of found {@link SoftwareModule}s
*
* @throws EntityNotFoundException
* if software module type with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countSoftwareModuleByFilters(String searchText, Long typeId); Long countSoftwareModuleByFilters(String searchText, Long typeId);
@@ -77,6 +81,9 @@ public interface SoftwareManagement {
* @return SoftwareModule * @return SoftwareModule
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
* if a given entity already exists * if a given entity already exists
*
* @throws EntityNotFoundException
* of given software module type does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<SoftwareModule> createSoftwareModule(@NotNull Collection<SoftwareModuleCreate> creates); List<SoftwareModule> createSoftwareModule(@NotNull Collection<SoftwareModuleCreate> creates);
@@ -88,6 +95,9 @@ public interface SoftwareManagement {
* @return SoftwareModule * @return SoftwareModule
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
* if a given entity already exists * if a given entity already exists
*
* @throws EntityNotFoundException
* of given software module type does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
SoftwareModule createSoftwareModule(@NotNull SoftwareModuleCreate create); SoftwareModule createSoftwareModule(@NotNull SoftwareModuleCreate create);
@@ -103,6 +113,8 @@ public interface SoftwareManagement {
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
* in case one of the meta data entry already exists for the * in case one of the meta data entry already exists for the
* specific key * specific key
* @throws EntityNotFoundException
* if software module with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List<SoftwareModuleMetadata> createSoftwareModuleMetadata(@NotNull Long moduleId, List<SoftwareModuleMetadata> createSoftwareModuleMetadata(@NotNull Long moduleId,
@@ -119,6 +131,8 @@ public interface SoftwareManagement {
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
* in case the meta data entry already exists for the specific * in case the meta data entry already exists for the specific
* key * key
* @throws EntityNotFoundException
* if software module with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull Long moduleId, @NotNull MetaData metadata); SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull Long moduleId, @NotNull MetaData metadata);
@@ -159,6 +173,9 @@ public interface SoftwareManagement {
* where meta data has to be deleted * where meta data has to be deleted
* @param key * @param key
* of the metda data element * of the metda data element
*
* @throws EntityNotFoundException
* of module or metadata entry does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
void deleteSoftwareModuleMetadata(@NotNull Long moduleId, @NotEmpty String key); void deleteSoftwareModuleMetadata(@NotNull Long moduleId, @NotEmpty String key);
@@ -168,6 +185,9 @@ public interface SoftwareManagement {
* *
* @param moduleIds * @param moduleIds
* of the Software Modules to be deleted * of the Software Modules to be deleted
*
* @throws EntityNotFoundException
* if (at least one) module with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModules(@NotNull Collection<Long> moduleIds); void deleteSoftwareModules(@NotNull Collection<Long> moduleIds);
@@ -179,7 +199,7 @@ public interface SoftwareManagement {
* to delete * to delete
* *
* @throws EntityNotFoundException * @throws EntityNotFoundException
* not found is type with giben ID does not exist * not found is type with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModuleType(@NotNull Long typeId); void deleteSoftwareModuleType(@NotNull Long typeId);
@@ -191,6 +211,9 @@ public interface SoftwareManagement {
* to search for * to search for
* @return all {@link SoftwareModule}s that are assigned to given * @return all {@link SoftwareModule}s that are assigned to given
* {@link DistributionSet}. * {@link DistributionSet}.
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModule> findSoftwareModuleByAssignedTo(@NotNull Pageable pageable, @NotNull Long setId); Page<SoftwareModule> findSoftwareModuleByAssignedTo(@NotNull Pageable pageable, @NotNull Long setId);
@@ -207,6 +230,9 @@ public interface SoftwareManagement {
* @param typeId * @param typeId
* to be filtered as "like" on {@link SoftwareModule#getType()} * to be filtered as "like" on {@link SoftwareModule#getType()}
* @return the page of found {@link SoftwareModule} * @return the page of found {@link SoftwareModule}
*
* @throws EntityNotFoundException
* if given software module type does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice<SoftwareModule> findSoftwareModuleByFilters(@NotNull Pageable pageable, String searchText, Long typeId); Slice<SoftwareModule> findSoftwareModuleByFilters(@NotNull Pageable pageable, String searchText, Long typeId);
@@ -227,12 +253,12 @@ public interface SoftwareManagement {
* *
* @param id * @param id
* to search for * to search for
* @return the found {@link SoftwareModule}s or <code>null</code> if not * @return the found {@link SoftwareModule}s
* found. *
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER) + SpringEvalExpressions.IS_CONTROLLER)
SoftwareModule findSoftwareModuleById(@NotNull Long id); Optional<SoftwareModule> findSoftwareModuleById(@NotNull Long id);
/** /**
* retrieves {@link SoftwareModule} by their name AND version AND type.. * retrieves {@link SoftwareModule} by their name AND version AND type..
@@ -243,10 +269,13 @@ public interface SoftwareManagement {
* of the {@link SoftwareModule} * of the {@link SoftwareModule}
* @param typeId * @param typeId
* of the {@link SoftwareModule} * of the {@link SoftwareModule}
* @return the found {@link SoftwareModule} or <code>null</code> * @return the found {@link SoftwareModule}
*
* @throws EntityNotFoundException
* if software module type with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModule findSoftwareModuleByNameAndVersion(@NotEmpty String name, @NotEmpty String version, Optional<SoftwareModule> findSoftwareModuleByNameAndVersion(@NotEmpty String name, @NotEmpty String version,
@NotNull Long typeId); @NotNull Long typeId);
/** /**
@@ -257,11 +286,9 @@ public interface SoftwareManagement {
* @param key * @param key
* of the meta data element * of the meta data element
* @return the found SoftwareModuleMetadata or {@code null} if not exits * @return the found SoftwareModuleMetadata or {@code null} if not exits
* @throws EntityNotFoundException
* in case the meta data does not exists for the given key
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModuleMetadata findSoftwareModuleMetadata(@NotNull Long moduleId, @NotEmpty String key); Optional<SoftwareModuleMetadata> findSoftwareModuleMetadata(@NotNull Long moduleId, @NotEmpty String key);
/** /**
* finds all meta data by the given software module id. * finds all meta data by the given software module id.
@@ -272,6 +299,9 @@ public interface SoftwareManagement {
* the page request to page the result * the page request to page the result
* @return a paged result of all meta data entries for a given software * @return a paged result of all meta data entries for a given software
* module id * module id
*
* @throws EntityNotFoundException
* if software module with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long swId, Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long swId,
@@ -294,6 +324,8 @@ public interface SoftwareManagement {
* given {@code fieldNameProvider} * given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException * @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong * if the RSQL syntax is wrong
* @throws EntityNotFoundException
* if software module with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long moduleId, Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long moduleId,
@@ -318,6 +350,9 @@ public interface SoftwareManagement {
* @param typeId * @param typeId
* filtered as "equal" on {@link SoftwareModule#getType()} * filtered as "equal" on {@link SoftwareModule#getType()}
* @return the page of found {@link SoftwareModule} * @return the page of found {@link SoftwareModule}
*
* @throws EntityNotFoundException
* if given software module type does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice<AssignedSoftwareModule> findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc( Slice<AssignedSoftwareModule> findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(
@@ -371,6 +406,9 @@ public interface SoftwareManagement {
* @param typeId * @param typeId
* to be filtered on * to be filtered on
* @return the found {@link SoftwareModule}s * @return the found {@link SoftwareModule}s
*
* @throws EntityNotFoundException
* if software module type with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice<SoftwareModule> findSoftwareModulesByType(@NotNull Pageable pageable, @NotNull Long typeId); Slice<SoftwareModule> findSoftwareModulesByType(@NotNull Pageable pageable, @NotNull Long typeId);
@@ -383,7 +421,7 @@ public interface SoftwareManagement {
* {@link SoftwareModuleType#getId()} * {@link SoftwareModuleType#getId()}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModuleType findSoftwareModuleTypeById(@NotNull Long id); Optional<SoftwareModuleType> findSoftwareModuleTypeById(@NotNull Long id);
/** /**
* *
@@ -393,7 +431,7 @@ public interface SoftwareManagement {
* {@link SoftwareModuleType#getKey()} * {@link SoftwareModuleType#getKey()}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModuleType findSoftwareModuleTypeByKey(@NotEmpty String key); Optional<SoftwareModuleType> findSoftwareModuleTypeByKey(@NotEmpty String key);
/** /**
* *
@@ -403,7 +441,7 @@ public interface SoftwareManagement {
* {@link SoftwareModuleType#getName()} * {@link SoftwareModuleType#getName()}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModuleType findSoftwareModuleTypeByName(@NotNull String name); Optional<SoftwareModuleType> findSoftwareModuleTypeByName(@NotNull String name);
/** /**
* @param pageable * @param pageable
@@ -443,6 +481,9 @@ public interface SoftwareManagement {
* if given module does not exist * if given module does not exist
* *
* @return the saved Entity. * @return the saved Entity.
*
* @throws EntityNotFoundException
* if fiven {@link SoftwareModule} does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModule updateSoftwareModule(@NotNull SoftwareModuleUpdate update); SoftwareModule updateSoftwareModule(@NotNull SoftwareModuleUpdate update);
@@ -455,8 +496,8 @@ public interface SoftwareManagement {
* @param metadata * @param metadata
* the meta data entry to be updated * the meta data entry to be updated
* *
*
* @return the updated meta data entry * @return the updated meta data entry
*
* @throws EntityNotFoundException * @throws EntityNotFoundException
* in case the meta data entry does not exists and cannot be * in case the meta data entry does not exists and cannot be
* updated * updated
@@ -492,6 +533,9 @@ public interface SoftwareManagement {
* @throws RSQLParameterSyntaxException * @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong * if the RSQL syntax is wrong
* @return result of all meta data entries for a given software module id. * @return result of all meta data entries for a given software module id.
*
* @throws EntityNotFoundException
* of software module with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long moduleId); List<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long moduleId);

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@@ -102,6 +103,9 @@ public interface TagManagement {
* *
* @param tagName * @param tagName
* to be deleted * to be deleted
*
* @throws EntityNotFoundException
* if tag with given name does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSetTag(@NotEmpty String tagName); void deleteDistributionSetTag(@NotEmpty String tagName);
@@ -111,6 +115,9 @@ public interface TagManagement {
* *
* @param targetTagName * @param targetTagName
* tag name of the {@link TargetTag} to be deleted * tag name of the {@link TargetTag} to be deleted
*
* @throws EntityNotFoundException
* if tag with given name does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargetTag(@NotEmpty String targetTagName); void deleteTargetTag(@NotEmpty String targetTagName);
@@ -150,12 +157,6 @@ public interface TagManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetTag> findAllDistributionSetTags(@NotNull String rsqlParam, @NotNull Pageable pageable); Page<DistributionSetTag> findAllDistributionSetTags(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* @return all {@link TargetTag}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<TargetTag> findAllTargetTags();
/** /**
* returns all {@link TargetTag}s. * returns all {@link TargetTag}s.
* *
@@ -190,41 +191,40 @@ public interface TagManagement {
* *
* @param name * @param name
* to look for. * to look for.
* @return {@link DistributionSet} or <code>null</code> if it does not exist * @return {@link DistributionSet}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetTag findDistributionSetTag(@NotEmpty String name); Optional<DistributionSetTag> findDistributionSetTag(@NotEmpty String name);
/** /**
* Finds {@link DistributionSetTag} by given id. * Finds {@link DistributionSetTag} by given id.
* *
* @param id * @param id
* to search for * to search for
* @return the found {@link DistributionSetTag}s or <code>null</code> if not * @return the found {@link DistributionSetTag}
* found.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetTag findDistributionSetTagById(@NotNull Long id); Optional<DistributionSetTag> findDistributionSetTagById(@NotNull Long id);
/** /**
* Find {@link TargetTag} based on given Name. * Find {@link TargetTag} based on given Name.
* *
* @param name * @param name
* to look for. * to look for.
* @return {@link TargetTag} or <code>null</code> if it does not exist * @return {@link TargetTag}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
TargetTag findTargetTag(@NotEmpty String name); Optional<TargetTag> findTargetTag(@NotEmpty String name);
/** /**
* Finds {@link TargetTag} by given id. * Finds {@link TargetTag} by given id.
* *
* @param id * @param id
* to search for * to search for
* @return the found {@link TargetTag}s or <code>null</code> if not found. * @return the found {@link TargetTag}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
TargetTag findTargetTagById(@NotNull Long id); Optional<TargetTag> findTargetTagById(@NotNull Long id);
/** /**
* Updates an existing {@link DistributionSetTag}. * Updates an existing {@link DistributionSetTag}.

View File

@@ -8,6 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
@@ -42,6 +44,9 @@ public interface TargetFilterQueryManagement {
* *
* @param targetFilterQueryId * @param targetFilterQueryId
* IDs of target filter query to be deleted * IDs of target filter query to be deleted
*
* @throws EntityNotFoundException
* if filter with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargetFilterQuery(@NotNull Long targetFilterQueryId); void deleteTargetFilterQuery(@NotNull Long targetFilterQueryId);
@@ -118,7 +123,7 @@ public interface TargetFilterQueryManagement {
* @return the page with the found {@link TargetFilterQuery} * @return the page with the found {@link TargetFilterQuery}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<TargetFilterQuery> findTargetFilterQueryByQuery(@NotNull Pageable pageable, String query); Page<TargetFilterQuery> findTargetFilterQueryByQuery(@NotNull Pageable pageable, @NotNull String query);
/** /**
* Retrieves all target filter query which {@link TargetFilterQuery}. * Retrieves all target filter query which {@link TargetFilterQuery}.
@@ -159,7 +164,7 @@ public interface TargetFilterQueryManagement {
* *
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
TargetFilterQuery findTargetFilterQueryById(@NotNull Long targetFilterQueryId); Optional<TargetFilterQuery> findTargetFilterQueryById(@NotNull Long targetFilterQueryId);
/** /**
* Find target filter query by name. * Find target filter query by name.
@@ -170,7 +175,7 @@ public interface TargetFilterQueryManagement {
* *
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
TargetFilterQuery findTargetFilterQueryByName(@NotNull String targetFilterQueryName); Optional<TargetFilterQuery> findTargetFilterQueryByName(@NotNull String targetFilterQueryName);
/** /**
* updates the {@link TargetFilterQuery}. * updates the {@link TargetFilterQuery}.

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@@ -64,6 +65,9 @@ public interface TargetManagement {
* to search for * to search for
* *
* @return number of found {@link Target}s. * @return number of found {@link Target}s.
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) + SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
@@ -94,6 +98,9 @@ public interface TargetManagement {
* flag to select targets with no tag assigned * flag to select targets with no tag assigned
* *
* @return the found number {@link Target}s * @return the found number {@link Target}s
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetByFilters(Collection<TargetUpdateStatus> status, Boolean overdueState, String searchText, Long countTargetByFilters(Collection<TargetUpdateStatus> status, Boolean overdueState, String searchText,
@@ -106,6 +113,9 @@ public interface TargetManagement {
* @param distId * @param distId
* to search for * to search for
* @return number of found {@link Target}s. * @return number of found {@link Target}s.
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) + SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
@@ -175,10 +185,13 @@ public interface TargetManagement {
* *
* @param targetIDs * @param targetIDs
* the IDs of the targets to be deleted * the IDs of the targets to be deleted
*
* @throws EntityNotFoundException
* if (at least one) of the given target IDs does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargets(@NotEmpty Collection<Long> targetIDs); void deleteTargets(@NotEmpty Collection<Long> targetIDs);
/** /**
* Deletes target with the given IDs. * Deletes target with the given IDs.
* *
@@ -203,10 +216,13 @@ public interface TargetManagement {
* @param rsqlParam * @param rsqlParam
* filter definition in RSQL syntax * filter definition in RSQL syntax
* @return a page of the found {@link Target}s * @return a page of the found {@link Target}s
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<Target> findAllTargetsByTargetFilterQueryAndNonDS(@NotNull Pageable pageRequest, Long distributionSetId, Page<Target> findAllTargetsByTargetFilterQueryAndNonDS(@NotNull Pageable pageRequest,
@NotNull String rsqlParam); @NotNull Long distributionSetId, @NotNull String rsqlParam);
/** /**
* Counts all targets for all the given parameter {@link TargetFilterQuery} * Counts all targets for all the given parameter {@link TargetFilterQuery}
@@ -218,6 +234,9 @@ public interface TargetManagement {
* @param rsqlParam * @param rsqlParam
* filter definition in RSQL syntax * filter definition in RSQL syntax
* @return the count of found {@link Target}s * @return the count of found {@link Target}s
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetsByTargetFilterQueryAndNonDS(@NotNull Long distributionSetId, @NotNull String rsqlParam); Long countTargetsByTargetFilterQueryAndNonDS(@NotNull Long distributionSetId, @NotNull String rsqlParam);
@@ -261,6 +280,9 @@ public interface TargetManagement {
* @param group * @param group
* the {@link RolloutGroup} * the {@link RolloutGroup}
* @return the found {@link Target}s * @return the found {@link Target}s
*
* @throws EntityNotFoundException
* if rollout group with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<Target> findAllTargetsInRolloutGroupWithoutAction(@NotNull Pageable pageRequest, @NotNull Long group); Page<Target> findAllTargetsInRolloutGroupWithoutAction(@NotNull Pageable pageRequest, @NotNull Long group);
@@ -276,6 +298,9 @@ public interface TargetManagement {
* @param pageReq * @param pageReq
* page parameter * page parameter
* @return the found {@link Target}s * @return the found {@link Target}s
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page<Target> findTargetByAssignedDistributionSet(@NotNull Long distributionSetID, @NotNull Pageable pageReq); Page<Target> findTargetByAssignedDistributionSet(@NotNull Long distributionSetID, @NotNull Pageable pageReq);
@@ -297,7 +322,8 @@ public interface TargetManagement {
* given {@code fieldNameProvider} * given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException * @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong * if the RSQL syntax is wrong
* * @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page<Target> findTargetByAssignedDistributionSet(@NotNull Long distributionSetID, @NotNull String rsqlParam, Page<Target> findTargetByAssignedDistributionSet(@NotNull Long distributionSetID, @NotNull String rsqlParam,
@@ -322,10 +348,10 @@ public interface TargetManagement {
* *
* @param controllerId * @param controllerId
* to look for. * to look for.
* @return {@link Target} or <code>null</code> if it does not exist * @return {@link Target}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Target findTargetByControllerID(@NotEmpty String controllerId); Optional<Target> findTargetByControllerID(@NotEmpty String controllerId);
/** /**
* Find {@link Target} based on given ID returns found Target with details, * Find {@link Target} based on given ID returns found Target with details,
@@ -337,10 +363,10 @@ public interface TargetManagement {
* *
* @param controllerId * @param controllerId
* to look for. * to look for.
* @return {@link Target} or <code>null</code> if it does not exist * @return {@link Target}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Target findTargetByControllerIDWithDetails(@NotEmpty String controllerId); Optional<Target> findTargetByControllerIDWithDetails(@NotEmpty String controllerId);
/** /**
* Filter {@link Target}s for all the given parameters. If all parameters * Filter {@link Target}s for all the given parameters. If all parameters
@@ -369,6 +395,9 @@ public interface TargetManagement {
* flag to select targets with no tag assigned * flag to select targets with no tag assigned
* *
* @return the found {@link Target}s * @return the found {@link Target}s
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Target> findTargetByFilters(@NotNull Pageable pageable, Collection<TargetUpdateStatus> status, Slice<Target> findTargetByFilters(@NotNull Pageable pageable, Collection<TargetUpdateStatus> status,
@@ -385,6 +414,9 @@ public interface TargetManagement {
* @param pageReq * @param pageReq
* page parameter * page parameter
* @return the found {@link Target}s * @return the found {@link Target}s
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page<Target> findTargetByInstalledDistributionSet(@NotNull Long distributionSetID, @NotNull Pageable pageReq); Page<Target> findTargetByInstalledDistributionSet(@NotNull Long distributionSetID, @NotNull Pageable pageReq);
@@ -407,6 +439,9 @@ public interface TargetManagement {
* given {@code fieldNameProvider} * given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException * @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong * if the RSQL syntax is wrong
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page<Target> findTargetByInstalledDistributionSet(@NotNull Long distributionSetId, @NotNull String rsqlParam, Page<Target> findTargetByInstalledDistributionSet(@NotNull Long distributionSetId, @NotNull String rsqlParam,
@@ -506,6 +541,9 @@ public interface TargetManagement {
* non-null value; filters are AND-gated * non-null value; filters are AND-gated
* @return a paged result {@link Page} of the {@link Target}s in a defined * @return a paged result {@link Page} of the {@link Target}s in a defined
* order. * order.
*
* @throws EntityNotFoundException
* if distribution set with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Target> findTargetsAllOrderByLinkedDistributionSet(@NotNull Pageable pageable, Slice<Target> findTargetsAllOrderByLinkedDistributionSet(@NotNull Pageable pageable,
@@ -546,6 +584,9 @@ public interface TargetManagement {
* @param tagName * @param tagName
* to toggle * to toggle
* @return TagAssigmentResult with all meta data of the assignment outcome. * @return TagAssigmentResult with all meta data of the assignment outcome.
*
* @throws EntityNotFoundException
* if tag with given name does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
TargetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<String> targetIds, @NotEmpty String tagName); TargetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<String> targetIds, @NotEmpty String tagName);
@@ -600,10 +641,10 @@ public interface TargetManagement {
* *
* @param id * @param id
* to look for * to look for
* @return {@link Target} or <code>null</code> if it does not exist * @return {@link Target}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Target findTargetById(Long id); Optional<Target> findTargetById(Long id);
/** /**
* Retrieves all targets without details, i.e. NO {@link Target#getTags()} * Retrieves all targets without details, i.e. NO {@link Target#getTags()}

View File

@@ -8,15 +8,17 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import java.util.Collection;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.eclipse.hawkbit.repository.model.MetaData;
/** /**
* the {@link EntityNotFoundException} is thrown when a entity is tried find but * the {@link EntityNotFoundException} is thrown when a entity queried but not
* not found. * found.
*
*
*
*/ */
public class EntityNotFoundException extends AbstractServerRtException { public class EntityNotFoundException extends AbstractServerRtException {
@@ -58,7 +60,51 @@ public class EntityNotFoundException extends AbstractServerRtException {
* @param message * @param message
* of the exception * of the exception
*/ */
public EntityNotFoundException(final String message) { protected EntityNotFoundException(final String message) {
super(message, THIS_ERROR); super(message, THIS_ERROR);
} }
/**
* Parameterized constructor for {@link BaseEntity} not found.
*
* @param type
* of the entity that was not found
*
* @param enityId
* of the {@link BaseEntity}
*/
public EntityNotFoundException(final Class<? extends BaseEntity> type, final Object enityId) {
this(type.getSimpleName() + " with given identifier {" + enityId + "} does not exist.");
}
/**
* Parameterized constructor for {@link MetaData} not found.
*
* @param type
* of the entity that was not found
* @param enityId
* of the {@link BaseEntity} the {@link MetaData} was for
* @param key
* for the {@link MetaData} entry
*/
public EntityNotFoundException(final Class<? extends MetaData> type, final Long enityId, final String key) {
this(type.getSimpleName() + " for given entity {" + enityId + "} and with key {" + key + "} does not exist.");
}
/**
* Parameterized constructor for a list of {@link BaseEntity}s not found.
*
* @param type
* of the entity that was not found
*
* @param expected
* collection of the {@link BaseEntity#getId()}s
* @param found
* collection of the {@link BaseEntity#getId()}s
*/
public EntityNotFoundException(final Class<? extends BaseEntity> type, final Collection<Long> expected,
final Collection<Long> found) {
this(type.getSimpleName() + "s with given identifiers {" + expected.stream().filter(id -> !found.contains(id))
.map(String::valueOf).collect(Collectors.joining(",")) + "} do not exist.");
}
} }

View File

@@ -0,0 +1,39 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository.exception;
import java.lang.annotation.Target;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
/**
* the {@link SoftwareModuleNotAssignedToTargetException} is thrown when a
* {@link SoftwareModule} is requested as part of an {@link Action} that has
* however never been assigned to the {@link Target}.
*/
public class SoftwareModuleNotAssignedToTargetException extends EntityNotFoundException {
private static final long serialVersionUID = 1L;
/**
* Constructor
*
* @param moduleId
* thats is not assigned to given {@link Target}
* @param controllerId
* of the {@link Target} where given {@link SoftwareModule} is
* not part of
*/
public SoftwareModuleNotAssignedToTargetException(final Long moduleId, final String controllerId) {
super("No assignment found for " + SoftwareModule.class.getSimpleName() + " with id {" + moduleId + "} to "
+ Target.class.getSimpleName() + " with id {" + controllerId + "}.");
}
}

View File

@@ -0,0 +1,40 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
/**
* the {@link SoftwareModuleTypeNotInDistributionSetTypeException} is thrown
* when a {@link SoftwareModuleType} is requested as part of a
* {@link DistributionSetType} but actually neither
* {@link DistributionSetType#getMandatoryModuleTypes()} or
* {@link DistributionSetType#getOptionalModuleTypes()}.
*/
public class SoftwareModuleTypeNotInDistributionSetTypeException extends EntityNotFoundException {
private static final long serialVersionUID = 1L;
/**
* Constructor
*
* @param moduleTypeId
* thats is not part of given {@link DistributionSetType}
* @param distributionSetTypeId
* of the {@link DistributionSetType} where given
* {@link SoftwareModuleType} is not part of
*/
public SoftwareModuleTypeNotInDistributionSetTypeException(final Long moduleTypeId,
final Long distributionSetTypeId) {
super(SoftwareModuleType.class.getSimpleName() + " with id {" + moduleTypeId + "} is not part of "
+ DistributionSetType.class.getSimpleName() + " with id {" + distributionSetTypeId + "}.");
}
}

View File

@@ -12,10 +12,7 @@ import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* Operations to be executed by the target. Usually a software update. Other * Update operations to be executed by the target.
* supported actions are the cancellation of a running update action or a
* refresh request for target attributes.
*
*/ */
public interface Action extends TenantAwareBaseEntity { public interface Action extends TenantAwareBaseEntity {

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.model; package org.eclipse.hawkbit.repository.model;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
/** /**
@@ -57,10 +58,10 @@ public interface DistributionSet extends NamedVersionedEntity {
* *
* @param type * @param type
* to search for * to search for
* @return SoftwareModule of given type or <code>null</code> if not found. * @return SoftwareModule of given type
*/ */
default SoftwareModule findFirstModuleByType(final SoftwareModuleType type) { default Optional<SoftwareModule> findFirstModuleByType(final SoftwareModuleType type) {
return getModules().stream().filter(module -> module.getType().equals(type)).findFirst().orElse(null); return getModules().stream().filter(module -> module.getType().equals(type)).findAny();
} }
/** /**

View File

@@ -73,7 +73,7 @@ public interface DistributionSetType extends NamedEntity {
*/ */
default boolean containsMandatoryModuleType(final Long softwareModuleTypeId) { default boolean containsMandatoryModuleType(final Long softwareModuleTypeId) {
return getMandatoryModuleTypes().stream().filter(element -> element.getId().equals(softwareModuleTypeId)) return getMandatoryModuleTypes().stream().filter(element -> element.getId().equals(softwareModuleTypeId))
.findFirst().isPresent(); .findAny().isPresent();
} }
/** /**
@@ -98,7 +98,7 @@ public interface DistributionSetType extends NamedEntity {
*/ */
default boolean containsOptionalModuleType(final Long softwareModuleTypeId) { default boolean containsOptionalModuleType(final Long softwareModuleTypeId) {
return getOptionalModuleTypes().stream().filter(element -> element.getId().equals(softwareModuleTypeId)) return getOptionalModuleTypes().stream().filter(element -> element.getId().equals(softwareModuleTypeId))
.findFirst().isPresent(); .findAny().isPresent();
} }
/** /**

View File

@@ -23,11 +23,7 @@ public interface SoftwareModule extends NamedVersionedEntity {
* @return found {@link Artifact} * @return found {@link Artifact}
*/ */
default Optional<Artifact> getArtifact(final Long artifactId) { default Optional<Artifact> getArtifact(final Long artifactId) {
if (getArtifacts().isEmpty()) { return getArtifacts().stream().filter(artifact -> artifact.getId().equals(artifactId)).findAny();
return Optional.empty();
}
return getArtifacts().stream().filter(artifact -> artifact.getId().equals(artifactId)).findFirst();
} }
/** /**
@@ -36,12 +32,8 @@ public interface SoftwareModule extends NamedVersionedEntity {
* @return found {@link Artifact} * @return found {@link Artifact}
*/ */
default Optional<Artifact> getArtifactByFilename(final String fileName) { default Optional<Artifact> getArtifactByFilename(final String fileName) {
if (getArtifacts().isEmpty()) {
return Optional.empty();
}
return getArtifacts().stream().filter(artifact -> artifact.getFilename().equalsIgnoreCase(fileName.trim())) return getArtifacts().stream().filter(artifact -> artifact.getFilename().equalsIgnoreCase(fileName.trim()))
.findFirst(); .findAny();
} }
/** /**

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import static org.fest.assertions.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;

View File

@@ -37,23 +37,8 @@
<!-- TEST --> <!-- TEST -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>junit</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>

View File

@@ -137,7 +137,7 @@ public class EventType {
*/ */
public static EventType from(final Class<?> clazz) { public static EventType from(final Class<?> clazz) {
final Optional<Integer> foundEventType = TYPES.entrySet().stream() final Optional<Integer> foundEventType = TYPES.entrySet().stream()
.filter(entry -> entry.getValue().equals(clazz)).map(entry -> entry.getKey()).findFirst(); .filter(entry -> entry.getValue().equals(clazz)).map(entry -> entry.getKey()).findAny();
if (!foundEventType.isPresent()) { if (!foundEventType.isPresent()) {
return null; return null;
} }

View File

@@ -8,15 +8,15 @@
*/ */
package org.eclipse.hawkbit.event; package org.eclipse.hawkbit.event;
import static org.fest.assertions.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.HashMap; import java.util.HashMap;
import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.repository.event.remote.entity.RemoteEntityEvent; import org.eclipse.hawkbit.repository.event.remote.entity.RemoteEntityEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.fest.assertions.api.Assertions;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;

View File

@@ -109,16 +109,6 @@
<artifactId>allure-junit-adaptor</artifactId> <artifactId>allure-junit-adaptor</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId> <artifactId>powermock-module-junit4</artifactId>

View File

@@ -16,7 +16,6 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; import org.eclipse.hawkbit.repository.jpa.model.JpaRollout;
import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
@@ -53,7 +52,7 @@ public interface ActionRepository extends BaseEntityRepository<JpaAction, Long>,
* @return the found {@link Action} * @return the found {@link Action}
*/ */
@EntityGraph(value = "Action.all", type = EntityGraphType.LOAD) @EntityGraph(value = "Action.all", type = EntityGraphType.LOAD)
JpaAction findById(Long actionId); Optional<Action> getById(Long actionId);
/** /**
* Retrieves all {@link Action}s which are referring the given * Retrieves all {@link Action}s which are referring the given
@@ -113,14 +112,14 @@ public interface ActionRepository extends BaseEntityRepository<JpaAction, Long>,
* *
* @param targetId * @param targetId
* to search for * to search for
* @param module * @param moduleId
* to search for * to search for
* @return action if there is one with assigned target and module is part of * @return action if there is one with assigned target and module is part of
* assigned {@link DistributionSet}. * assigned {@link DistributionSet}.
*/ */
@Query("Select a from JpaAction a join a.distributionSet ds join ds.modules modul where a.target.controllerId = :target and modul = :module order by a.id desc") @Query("Select a from JpaAction a join a.distributionSet ds join ds.modules modul where a.target.controllerId = :target and modul.id = :module order by a.id desc")
List<Action> findActionByTargetAndSoftwareModule(@Param("target") final String targetId, List<Action> findActionByTargetAndSoftwareModule(@Param("target") final String targetId,
@Param("module") JpaSoftwareModule module); @Param("module") Long moduleId);
/** /**
* Retrieves all {@link Action}s which are referring the given * Retrieves all {@link Action}s which are referring the given

View File

@@ -9,8 +9,10 @@
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.io.Serializable; import java.io.Serializable;
import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaTenantAwareBaseEntity; import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaTenantAwareBaseEntity;
import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.NoRepositoryBean;
@@ -41,4 +43,13 @@ public interface BaseEntityRepository<T extends AbstractJpaTenantAwareBaseEntity
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
void deleteByTenantIgnoreCase(String tenant); void deleteByTenantIgnoreCase(String tenant);
/**
* Retrieves an {@link BaseEntity} by its id.
*
* @param id
* to search for
* @return {@link BaseEntity}
*/
Optional<T> findById(I id);
} }

View File

@@ -12,10 +12,10 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.Tag;
@@ -42,7 +42,7 @@ public interface DistributionSetRepository
* @return list of found {@link DistributionSet}s * @return list of found {@link DistributionSet}s
*/ */
@Query(value = "Select Distinct ds from JpaDistributionSet ds join ds.tags dst where dst = :tag") @Query(value = "Select Distinct ds from JpaDistributionSet ds join ds.tags dst where dst = :tag")
List<JpaDistributionSet> findByTag(@Param("tag") final JpaDistributionSetTag tag); List<JpaDistributionSet> findByTag(@Param("tag") final DistributionSetTag tag);
/** /**
* deletes the {@link DistributionSet}s with the given IDs. * deletes the {@link DistributionSet}s with the given IDs.

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -44,7 +45,7 @@ public interface DistributionSetTagRepository
* to filter on * to filter on
* @return the {@link DistributionSetTag} if found, otherwise null * @return the {@link DistributionSetTag} if found, otherwise null
*/ */
JpaDistributionSetTag findByNameEquals(final String tagName); Optional<DistributionSetTag> findByNameEquals(final String tagName);
/** /**
* Returns all instances of the type. * Returns all instances of the type.

View File

@@ -9,7 +9,6 @@
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.io.InputStream; import java.io.InputStream;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository; import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
@@ -105,9 +104,9 @@ public class JpaArtifactManagement implements ArtifactManagement {
@Override @Override
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public boolean clearArtifactBinary(final Long existing) { public boolean clearArtifactBinary(final Long artifactId) {
return clearArtifactBinary(Optional.ofNullable(localArtifactRepository.findOne(existing)) return clearArtifactBinary(localArtifactRepository.findById(artifactId)
.orElseThrow(() -> new EntityNotFoundException("Artifact with given ID" + existing + " not found."))); .orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId)));
} }
private boolean clearArtifactBinary(final JpaArtifact existing) { private boolean clearArtifactBinary(final JpaArtifact existing) {
@@ -132,11 +131,8 @@ public class JpaArtifactManagement implements ArtifactManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteArtifact(final Long id) { public void deleteArtifact(final Long id) {
final JpaArtifact existing = localArtifactRepository.findOne(id); final JpaArtifact existing = (JpaArtifact) findArtifact(id)
.orElseThrow(() -> new EntityNotFoundException(Artifact.class, id));
if (null == existing) {
return;
}
clearArtifactBinary(existing); clearArtifactBinary(existing);
@@ -146,23 +142,23 @@ public class JpaArtifactManagement implements ArtifactManagement {
} }
@Override @Override
public Artifact findArtifact(final Long id) { public Optional<Artifact> findArtifact(final Long id) {
return localArtifactRepository.findOne(id); return Optional.ofNullable(localArtifactRepository.findOne(id));
} }
@Override @Override
public List<Artifact> findByFilenameAndSoftwareModule(final String filename, final Long softwareModuleId) { public Optional<Artifact> findByFilenameAndSoftwareModule(final String filename, final Long softwareModuleId) {
return localArtifactRepository.findByFilenameAndSoftwareModuleId(filename, softwareModuleId); return localArtifactRepository.findFirstByFilenameAndSoftwareModuleId(filename, softwareModuleId);
} }
@Override @Override
public Artifact findFirstArtifactBySHA1(final String sha1Hash) { public Optional<Artifact> findFirstArtifactBySHA1(final String sha1Hash) {
return localArtifactRepository.findFirstBySha1Hash(sha1Hash); return localArtifactRepository.findFirstBySha1Hash(sha1Hash);
} }
@Override @Override
public List<Artifact> findArtifactByFilename(final String filename) { public Optional<Artifact> findArtifactByFilename(final String filename) {
return localArtifactRepository.findByFilename(filename); return localArtifactRepository.findFirstByFilename(filename);
} }
@Override @Override
@@ -208,7 +204,7 @@ public class JpaArtifactManagement implements ArtifactManagement {
if (softwareModule == null) { if (softwareModule == null) {
LOG.debug("no software module with ID {} exists", moduleId); LOG.debug("no software module with ID {} exists", moduleId);
throw new EntityNotFoundException("Software Module: " + moduleId); throw new EntityNotFoundException(SoftwareModule.class, moduleId);
} }
return softwareModule; return softwareModule;
} }

View File

@@ -39,7 +39,6 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus_; import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus_;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction_; import org.eclipse.hawkbit.repository.jpa.model.JpaAction_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_;
@@ -47,7 +46,6 @@ import org.eclipse.hawkbit.repository.jpa.specifications.ActionSpecifications;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
@@ -133,33 +131,31 @@ public class JpaControllerManagement implements ControllerManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public Target updateLastTargetQuery(final String controllerId, final URI address) { public Target updateLastTargetQuery(final String controllerId, final URI address) {
final Target target = Optional.ofNullable(targetRepository.findByControllerId(controllerId)) final Target target = targetRepository.findByControllerId(controllerId)
.orElseThrow(() -> new EntityNotFoundException("Target with given ID " + controllerId + " not found")); .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
return updateTargetStatus(target.getTargetInfo(), null, System.currentTimeMillis(), address).getTarget(); return updateTargetStatus(target.getTargetInfo(), null, System.currentTimeMillis(), address).getTarget();
} }
@Override @Override
public Action getActionForDownloadByTargetAndSoftwareModule(final String controllerId, public Optional<Action> getActionForDownloadByTargetAndSoftwareModule(final String controllerId,
final SoftwareModule module) { final Long moduleId) {
final List<Action> action = actionRepository.findActionByTargetAndSoftwareModule(controllerId, final List<Action> action = actionRepository.findActionByTargetAndSoftwareModule(controllerId, moduleId);
(JpaSoftwareModule) module);
if (action.isEmpty() || action.get(0).isCancelingOrCanceled()) { if (action.isEmpty() || action.get(0).isCancelingOrCanceled()) {
throw new EntityNotFoundException( return Optional.empty();
"No assigment found for module " + module.getId() + " to target " + controllerId);
} }
return action.get(0); return Optional.ofNullable(action.get(0));
} }
@Override @Override
public boolean hasTargetArtifactAssigned(final String controllerId, final String sha1Hash) { public boolean hasTargetArtifactAssigned(final String controllerId, final String sha1Hash) {
final Target target = targetRepository.findByControllerId(controllerId); final Optional<Target> target = targetRepository.findByControllerId(controllerId);
if (target == null) { if (!target.isPresent()) {
return false; return false;
} }
return actionRepository.count(ActionSpecifications.hasTargetAssignedArtifact(target, sha1Hash)) > 0; return actionRepository.count(ActionSpecifications.hasTargetAssignedArtifact(target.get(), sha1Hash)) > 0;
} }
@Override @Override
@@ -180,8 +176,8 @@ public class JpaControllerManagement implements ControllerManagement {
} }
@Override @Override
public Action findActionWithDetails(final Long actionId) { public Optional<Action> findActionWithDetails(final Long actionId) {
return getActionAndThrowExceptionIfNotFound(actionId); return actionRepository.getById(actionId);
} }
@Override @Override
@@ -388,11 +384,8 @@ public class JpaControllerManagement implements ControllerManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public Target updateControllerAttributes(final String controllerId, final Map<String, String> data) { public Target updateControllerAttributes(final String controllerId, final Map<String, String> data) {
final JpaTarget target = targetRepository.findByControllerId(controllerId); final JpaTarget target = (JpaTarget) targetRepository.findByControllerId(controllerId)
.orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
if (target == null) {
throw new EntityNotFoundException(controllerId);
}
final JpaTargetInfo targetInfo = (JpaTargetInfo) target.getTargetInfo(); final JpaTargetInfo targetInfo = (JpaTargetInfo) target.getTargetInfo();
targetInfo.getControllerAttributes().putAll(data); targetInfo.getControllerAttributes().putAll(data);
@@ -435,8 +428,7 @@ public class JpaControllerManagement implements ControllerManagement {
* {@link Status#RETRIEVED} * {@link Status#RETRIEVED}
*/ */
private Action handleRegisterRetrieved(final Long actionId, final String message) { private Action handleRegisterRetrieved(final Long actionId, final String message) {
final JpaAction action = Optional.ofNullable(actionRepository.findById(actionId)).orElseThrow( final JpaAction action = getActionAndThrowExceptionIfNotFound(actionId);
() -> new EntityNotFoundException("Actionw ith given ID " + actionId + " doesn not exist."));
// do a manual query with CriteriaBuilder to avoid unnecessary field // do a manual query with CriteriaBuilder to avoid unnecessary field
// queries and an extra // queries and an extra
// count query made by spring-data when using pageable requests, we // count query made by spring-data when using pageable requests, we
@@ -492,8 +484,8 @@ public class JpaControllerManagement implements ControllerManagement {
} }
private JpaAction getActionAndThrowExceptionIfNotFound(final Long actionId) { private JpaAction getActionAndThrowExceptionIfNotFound(final Long actionId) {
return Optional.ofNullable(actionRepository.findById(actionId)) return actionRepository.findById(actionId)
.orElseThrow(() -> new EntityNotFoundException("Action with ID " + actionId + " not found!")); .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
} }
@Override @Override
@@ -504,13 +496,13 @@ public class JpaControllerManagement implements ControllerManagement {
} }
@Override @Override
public Target findByControllerId(final String controllerId) { public Optional<Target> findByControllerId(final String controllerId) {
return targetRepository.findByControllerId(controllerId); return targetRepository.findByControllerId(controllerId);
} }
@Override @Override
public Target findByTargetId(final Long targetId) { public Optional<Target> findByTargetId(final Long targetId) {
return targetRepository.findOne(targetId); return Optional.ofNullable(targetRepository.findOne(targetId));
} }
} }

View File

@@ -174,8 +174,7 @@ public class JpaDeploymentManagement implements DeploymentManagement {
final Collection<TargetWithActionType> targets, final String actionMessage) { final Collection<TargetWithActionType> targets, final String actionMessage) {
final JpaDistributionSet set = distributoinSetRepository.findOne(dsID); final JpaDistributionSet set = distributoinSetRepository.findOne(dsID);
if (set == null) { if (set == null) {
throw new EntityNotFoundException( throw new EntityNotFoundException(DistributionSet.class, dsID);
String.format("no %s with id %d found", DistributionSet.class.getSimpleName(), dsID));
} }
return assignDistributionSetToTargets(set, targets, null, null, actionMessage); return assignDistributionSetToTargets(set, targets, null, null, actionMessage);
@@ -365,8 +364,8 @@ public class JpaDeploymentManagement implements DeploymentManagement {
public Action cancelAction(final Long actionId) { public Action cancelAction(final Long actionId) {
LOG.debug("cancelAction({})", actionId); LOG.debug("cancelAction({})", actionId);
final JpaAction action = Optional.ofNullable(actionRepository.findOne(actionId)) final JpaAction action = actionRepository.findById(actionId)
.orElseThrow(() -> new EntityNotFoundException("Action with given ID " + actionId + " not found")); .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (action.isCancelingOrCanceled()) { if (action.isCancelingOrCanceled()) {
throw new CancelActionNotAllowedException("Actions in canceling or canceled state cannot be canceled"); throw new CancelActionNotAllowedException("Actions in canceling or canceled state cannot be canceled");
@@ -412,8 +411,8 @@ public class JpaDeploymentManagement implements DeploymentManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_COMMITTED) @Transactional(isolation = Isolation.READ_COMMITTED)
public Action forceQuitAction(final Long actionId) { public Action forceQuitAction(final Long actionId) {
final JpaAction action = Optional.ofNullable(actionRepository.findOne(actionId)) final JpaAction action = actionRepository.findById(actionId)
.orElseThrow(() -> new EntityNotFoundException("Action with given ID " + actionId + " not found")); .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.isCancelingOrCanceled()) { if (!action.isCancelingOrCanceled()) {
throw new ForceQuitActionNotAllowedException( throw new ForceQuitActionNotAllowedException(
@@ -542,13 +541,13 @@ public class JpaDeploymentManagement implements DeploymentManagement {
} }
@Override @Override
public Action findAction(final Long actionId) { public Optional<Action> findAction(final Long actionId) {
return actionRepository.findOne(actionId); return Optional.ofNullable(actionRepository.findOne(actionId));
} }
@Override @Override
public Action findActionWithDetails(final Long actionId) { public Optional<Action> findActionWithDetails(final Long actionId) {
return actionRepository.findById(actionId); return actionRepository.getById(actionId);
} }
@Override @Override
@@ -622,8 +621,10 @@ public class JpaDeploymentManagement implements DeploymentManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public Action forceTargetAction(final Long actionId) { public Action forceTargetAction(final Long actionId) {
final JpaAction action = actionRepository.findOne(actionId); final JpaAction action = actionRepository.findById(actionId)
if (action != null && !action.isForced()) { .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.isForced()) {
action.setActionType(ActionType.FORCED); action.setActionType(ActionType.FORCED);
return actionRepository.save(action); return actionRepository.save(action);
} }
@@ -632,11 +633,19 @@ public class JpaDeploymentManagement implements DeploymentManagement {
@Override @Override
public Page<ActionStatus> findActionStatusByAction(final Pageable pageReq, final Long actionId) { public Page<ActionStatus> findActionStatusByAction(final Pageable pageReq, final Long actionId) {
if (!actionRepository.exists(actionId)) {
throw new EntityNotFoundException(Action.class, actionId);
}
return actionStatusRepository.findByActionId(pageReq, actionId); return actionStatusRepository.findByActionId(pageReq, actionId);
} }
@Override @Override
public Page<ActionStatus> findActionStatusByActionWithMessages(final Pageable pageReq, final Long actionId) { public Page<ActionStatus> findActionStatusByActionWithMessages(final Pageable pageReq, final Long actionId) {
if (!actionRepository.exists(actionId)) {
throw new EntityNotFoundException(Action.class, actionId);
}
return actionStatusRepository.getByActionId(pageReq, actionId); return actionStatusRepository.getByActionId(pageReq, actionId);
} }

View File

@@ -48,6 +48,7 @@ import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetSpecification; import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetSpecification;
import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetTypeSpecification; import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetTypeSpecification;
import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter; import org.eclipse.hawkbit.repository.model.DistributionSetFilter;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter.DistributionSetFilterBuilder; import org.eclipse.hawkbit.repository.model.DistributionSetFilter.DistributionSetFilterBuilder;
@@ -56,6 +57,8 @@ import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.MetaData; import org.eclipse.hawkbit.repository.model.MetaData;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer;
import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.TenantAware;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -125,22 +128,28 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
private SoftwareModuleTypeRepository softwareModuleTypeRepository; private SoftwareModuleTypeRepository softwareModuleTypeRepository;
@Override @Override
public DistributionSet findDistributionSetByIdWithDetails(final Long distid) { public Optional<DistributionSet> findDistributionSetByIdWithDetails(final Long distid) {
return distributionSetRepository.findOne(DistributionSetSpecification.byId(distid)); return Optional.ofNullable(distributionSetRepository.findOne(DistributionSetSpecification.byId(distid)));
} }
@Override @Override
public DistributionSet findDistributionSetById(final Long distid) { public Optional<DistributionSet> findDistributionSetById(final Long distid) {
return distributionSetRepository.findOne(distid); return Optional.ofNullable(distributionSetRepository.findOne(distid));
} }
@Override @Override
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public DistributionSetTagAssignmentResult toggleTagAssignment(final Collection<Long> dsIds, final String tagName) { public DistributionSetTagAssignmentResult toggleTagAssignment(final Collection<Long> dsIds, final String tagName) {
final List<JpaDistributionSet> sets = findDistributionSetListWithDetails(dsIds); final List<JpaDistributionSet> sets = findDistributionSetListWithDetails(dsIds);
final DistributionSetTag myTag = tagManagement.findDistributionSetTag(tagName);
if (sets.size() < dsIds.size()) {
throw new EntityNotFoundException(DistributionSet.class, dsIds,
sets.stream().map(DistributionSet::getId).collect(Collectors.toList()));
}
final DistributionSetTag myTag = tagManagement.findDistributionSetTag(tagName)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, tagName));
DistributionSetTagAssignmentResult result; DistributionSetTagAssignmentResult result;
@@ -207,46 +216,37 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
} }
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) { private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) {
return findDistributionSetTypeByKey(distributionSetTypekey)
final DistributionSetType module = findDistributionSetTypeByKey(distributionSetTypekey); .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypekey));
if (module == null) {
throw new EntityNotFoundException(
"DistributionSetType with key {" + distributionSetTypekey + "} does not exist");
}
return module;
} }
private JpaDistributionSetType findDistributionSetTypeAndThrowExceptionIfNotFound(final Long setId) { private JpaDistributionSetType findDistributionSetTypeAndThrowExceptionIfNotFound(final Long setId) {
final JpaDistributionSetType set = (JpaDistributionSetType) findDistributionSetTypeById(setId); return (JpaDistributionSetType) findDistributionSetTypeById(setId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, setId));
if (set == null) {
throw new EntityNotFoundException("Distribution set type cannot be updated as it does not exixt" + setId);
}
return set;
} }
private JpaDistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) { private JpaDistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) {
final JpaDistributionSet set = (JpaDistributionSet) findDistributionSetById(setId); return (JpaDistributionSet) findDistributionSetById(setId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, setId));
if (set == null) {
throw new EntityNotFoundException("Distribution set cannot be updated as it does not exixt" + setId);
}
return set;
} }
private JpaSoftwareModule findSoftwareModuleAndThrowExceptionIfNotFound(final Long moduleId) { private JpaSoftwareModule findSoftwareModuleAndThrowExceptionIfNotFound(final Long moduleId) {
final JpaSoftwareModule module = softwareModuleRepository.findOne(moduleId); return Optional.ofNullable(softwareModuleRepository.findOne(moduleId))
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, moduleId));
if (module == null) {
throw new EntityNotFoundException("Distribution set cannot be updated as it does not exixt" + moduleId);
}
return module;
} }
@Override @Override
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteDistributionSet(final Collection<Long> distributionSetIDs) { public void deleteDistributionSet(final Collection<Long> distributionSetIDs) {
final List<DistributionSet> setsFound = findDistributionSetAllById(distributionSetIDs);
if (setsFound.size() < distributionSetIDs.size()) {
throw new EntityNotFoundException(DistributionSet.class, distributionSetIDs,
setsFound.stream().map(DistributionSet::getId).collect(Collectors.toList()));
}
final List<Long> assigned = distributionSetRepository final List<Long> assigned = distributionSetRepository
.findAssignedToTargetDistributionSetsById(distributionSetIDs); .findAssignedToTargetDistributionSetsById(distributionSetIDs);
assigned.addAll(distributionSetRepository.findAssignedToRolloutDistributionSetsById(distributionSetIDs)); assigned.addAll(distributionSetRepository.findAssignedToRolloutDistributionSetsById(distributionSetIDs));
@@ -303,15 +303,17 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public DistributionSet assignSoftwareModules(final Long setId, final Collection<Long> moduleIds) { public DistributionSet assignSoftwareModules(final Long setId, final Collection<Long> moduleIds) {
final JpaDistributionSet set = findDistributionSetAndThrowExceptionIfNotFound(setId);
final Collection<JpaSoftwareModule> modules = softwareModuleRepository.findByIdIn(moduleIds); final Collection<JpaSoftwareModule> modules = softwareModuleRepository.findByIdIn(moduleIds);
if (modules.size() < moduleIds.size()) { if (modules.size() < moduleIds.size()) {
throw new EntityNotFoundException("Not all given software modules where found."); throw new EntityNotFoundException(SoftwareModule.class, moduleIds,
modules.stream().map(SoftwareModule::getId).collect(Collectors.toList()));
} }
checkDistributionSetIsAssignedToTargets(setId); checkDistributionSetIsAssignedToTargets(setId);
final JpaDistributionSet set = findDistributionSetAndThrowExceptionIfNotFound(setId);
modules.forEach(set::addModule); modules.forEach(set::addModule);
return distributionSetRepository.save(set); return distributionSetRepository.save(set);
@@ -363,15 +365,15 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public DistributionSetType assignMandatorySoftwareModuleTypes(final Long dsTypeId, public DistributionSetType assignMandatorySoftwareModuleTypes(final Long dsTypeId,
final Collection<Long> softwareModulesTypeIds) { final Collection<Long> softwareModulesTypeIds) {
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
final Collection<JpaSoftwareModuleType> modules = softwareModuleTypeRepository final Collection<JpaSoftwareModuleType> modules = softwareModuleTypeRepository
.findByIdIn(softwareModulesTypeIds); .findByIdIn(softwareModulesTypeIds);
if (modules.size() < softwareModulesTypeIds.size()) { if (modules.size() < softwareModulesTypeIds.size()) {
throw new EntityNotFoundException("Not all given software module types where found."); throw new EntityNotFoundException(SoftwareModuleType.class, softwareModulesTypeIds,
modules.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()));
} }
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId); checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
modules.forEach(type::addMandatoryModuleType); modules.forEach(type::addMandatoryModuleType);
@@ -384,17 +386,17 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public DistributionSetType assignOptionalSoftwareModuleTypes(final Long dsTypeId, public DistributionSetType assignOptionalSoftwareModuleTypes(final Long dsTypeId,
final Collection<Long> softwareModulesTypeIds) { final Collection<Long> softwareModulesTypeIds) {
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
final Collection<JpaSoftwareModuleType> modules = softwareModuleTypeRepository final Collection<JpaSoftwareModuleType> modules = softwareModuleTypeRepository
.findByIdIn(softwareModulesTypeIds); .findByIdIn(softwareModulesTypeIds);
if (modules.size() < softwareModulesTypeIds.size()) { if (modules.size() < softwareModulesTypeIds.size()) {
throw new EntityNotFoundException("Not all given software module types where found."); throw new EntityNotFoundException(SoftwareModuleType.class, softwareModulesTypeIds,
modules.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()));
} }
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId); checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
modules.forEach(type::addOptionalModuleType); modules.forEach(type::addOptionalModuleType);
return distributionSetTypeRepository.save(type); return distributionSetTypeRepository.save(type);
@@ -545,10 +547,11 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
} }
@Override @Override
public DistributionSet findDistributionSetByNameAndVersion(final String distributionName, final String version) { public Optional<DistributionSet> findDistributionSetByNameAndVersion(final String distributionName,
final String version) {
final Specification<JpaDistributionSet> spec = DistributionSetSpecification final Specification<JpaDistributionSet> spec = DistributionSetSpecification
.equalsNameAndVersionIgnoreCase(distributionName, version); .equalsNameAndVersionIgnoreCase(distributionName, version);
return distributionSetRepository.findOne(spec); return Optional.ofNullable(distributionSetRepository.findOne(spec));
} }
@@ -571,18 +574,20 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
} }
@Override @Override
public DistributionSetType findDistributionSetTypeByName(final String name) { public Optional<DistributionSetType> findDistributionSetTypeByName(final String name) {
return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name)); return Optional
.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name)));
} }
@Override @Override
public DistributionSetType findDistributionSetTypeById(final Long id) { public Optional<DistributionSetType> findDistributionSetTypeById(final Long typeId) {
return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(id)); return Optional
.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(typeId)));
} }
@Override @Override
public DistributionSetType findDistributionSetTypeByKey(final String key) { public Optional<DistributionSetType> findDistributionSetTypeByKey(final String key) {
return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key)); return Optional.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key)));
} }
@Override @Override
@@ -599,9 +604,8 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteDistributionSetType(final Long typeId) { public void deleteDistributionSetType(final Long typeId) {
final JpaDistributionSetType toDelete = Optional.ofNullable(distributionSetTypeRepository.findOne(typeId)) final JpaDistributionSetType toDelete = distributionSetTypeRepository.findById(typeId)
.orElseThrow(() -> new EntityNotFoundException( .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, typeId));
"DistributionSet Type with given ID " + typeId + " does not exist"));
if (distributionSetRepository.countByTypeId(typeId) > 0) { if (distributionSetRepository.countByTypeId(typeId) > 0) {
toDelete.setDeleted(true); toDelete.setDeleted(true);
@@ -634,7 +638,8 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
// check if exists otherwise throw entity not found exception // check if exists otherwise throw entity not found exception
final JpaDistributionSetMetadata toUpdate = (JpaDistributionSetMetadata) findDistributionSetMetadata(dsId, final JpaDistributionSetMetadata toUpdate = (JpaDistributionSetMetadata) findDistributionSetMetadata(dsId,
md.getKey()); md.getKey()).orElseThrow(
() -> new EntityNotFoundException(DistributionSetMetadata.class, dsId, md.getKey()));
toUpdate.setValue(md.getValue()); toUpdate.setValue(md.getValue());
// touch it to update the lock revision because we are modifying the // touch it to update the lock revision because we are modifying the
// DS indirectly // DS indirectly
@@ -645,9 +650,32 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Override @Override
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying @Modifying
public void deleteDistributionSetMetadata(final Long distributionSet, final String key) { public void deleteDistributionSetMetadata(final Long distributionSetId, final String key) {
touch(distributionSet); final JpaDistributionSetMetadata metadata = (JpaDistributionSetMetadata) findDistributionSetMetadata(
distributionSetMetadataRepository.delete(new DsMetadataCompositeKey(distributionSet, key)); distributionSetId, key).orElseThrow(
() -> new EntityNotFoundException(DistributionSetMetadata.class, distributionSetId, key));
touch(metadata.getDistributionSet());
distributionSetMetadataRepository.delete(metadata.getId());
}
/**
* Method to get the latest distribution set based on DS ID after the
* metadata changes for that distribution set.
*
* @param ds
* is the DS to touch
*/
private JpaDistributionSet touch(final DistributionSet ds) {
// merge base distribution set so optLockRevision gets updated and audit
// log written because
// modifying metadata is modifying the base distribution set itself for
// auditing purposes.
final JpaDistributionSet result = entityManager.merge((JpaDistributionSet) ds);
result.setLastModifiedAt(0L);
return result;
} }
/** /**
@@ -655,24 +683,20 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
* metadata changes for that distribution set. * metadata changes for that distribution set.
* *
* @param distId * @param distId
* Distribution set * of the DS to touch
*/ */
private JpaDistributionSet touch(final Long distId) { private JpaDistributionSet touch(final Long distId) {
final DistributionSet latestDistributionSet = findDistributionSetAndThrowExceptionIfNotFound(distId); return touch(findDistributionSetById(distId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, distId)));
// merge base distribution set so optLockRevision gets updated and audit
// log written because
// modifying metadata is modifying the base distribution set itself for
// auditing purposes.
final JpaDistributionSet result = entityManager.merge((JpaDistributionSet) latestDistributionSet);
result.setLastModifiedAt(0L);
return result;
} }
@Override @Override
public Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(final Long distributionSetId, public Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(final Long distributionSetId,
final Pageable pageable) { final Pageable pageable) {
if (!distributionSetRepository.exists(distributionSetId)) {
throw new EntityNotFoundException(DistributionSet.class, distributionSetId);
}
return convertMdPage(distributionSetMetadataRepository return convertMdPage(distributionSetMetadataRepository
.findAll((Specification<JpaDistributionSetMetadata>) (root, query, cb) -> cb.equal( .findAll((Specification<JpaDistributionSetMetadata>) (root, query, cb) -> cb.equal(
root.get(JpaDistributionSetMetadata_.distributionSet).get(JpaDistributionSet_.id), root.get(JpaDistributionSetMetadata_.distributionSet).get(JpaDistributionSet_.id),
@@ -680,18 +704,14 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
pageable); pageable);
} }
@Override
public List<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(final Long distributionSetId) {
return Collections.unmodifiableList(distributionSetMetadataRepository
.findAll((Specification<JpaDistributionSetMetadata>) (root, query, cb) -> cb.equal(
root.get(JpaDistributionSetMetadata_.distributionSet).get(JpaDistributionSet_.id),
distributionSetId)));
}
@Override @Override
public Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(final Long distributionSetId, public Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(final Long distributionSetId,
final String rsqlParam, final Pageable pageable) { final String rsqlParam, final Pageable pageable) {
if (!distributionSetRepository.exists(distributionSetId)) {
throw new EntityNotFoundException(DistributionSet.class, distributionSetId);
}
final Specification<JpaDistributionSetMetadata> spec = RSQLUtility.parse(rsqlParam, final Specification<JpaDistributionSetMetadata> spec = RSQLUtility.parse(rsqlParam,
DistributionSetMetadataFields.class, virtualPropertyReplacer); DistributionSetMetadataFields.class, virtualPropertyReplacer);
@@ -710,18 +730,18 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
} }
@Override @Override
public DistributionSetMetadata findDistributionSetMetadata(final Long distributionSet, final String key) { public Optional<DistributionSetMetadata> findDistributionSetMetadata(final Long distributionSet, final String key) {
final DistributionSetMetadata findOne = distributionSetMetadataRepository return Optional.ofNullable(
.findOne(new DsMetadataCompositeKey(distributionSet, key)); distributionSetMetadataRepository.findOne(new DsMetadataCompositeKey(distributionSet, key)));
if (findOne == null) {
throw new EntityNotFoundException("Metadata with key '" + key + "' does not exist");
}
return findOne;
} }
@Override @Override
public DistributionSet findDistributionSetByAction(final Long actionId) { public Optional<DistributionSet> findDistributionSetByAction(final Long actionId) {
return distributionSetRepository.findByActionId(actionId); if (!actionRepository.exists(actionId)) {
throw new EntityNotFoundException(Action.class, actionId);
}
return Optional.ofNullable(distributionSetRepository.findByActionId(actionId));
} }
@Override @Override
@@ -819,10 +839,13 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
public List<DistributionSet> assignTag(final Collection<Long> dsIds, final Long dsTagId) { public List<DistributionSet> assignTag(final Collection<Long> dsIds, final Long dsTagId) {
final List<JpaDistributionSet> allDs = findDistributionSetListWithDetails(dsIds); final List<JpaDistributionSet> allDs = findDistributionSetListWithDetails(dsIds);
final DistributionSetTag distributionSetTag = Optional if (allDs.size() < dsIds.size()) {
.ofNullable(tagManagement.findDistributionSetTagById(dsTagId)) throw new EntityNotFoundException(DistributionSet.class, dsIds,
.orElseThrow(() -> new EntityNotFoundException( allDs.stream().map(DistributionSet::getId).collect(Collectors.toList()));
"DistributionSet Tag with given ID " + dsTagId + " not found.")); }
final DistributionSetTag distributionSetTag = tagManagement.findDistributionSetTagById(dsTagId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, dsTagId));
allDs.forEach(ds -> ds.addTag(distributionSetTag)); allDs.forEach(ds -> ds.addTag(distributionSetTag));
@@ -835,10 +858,8 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public List<DistributionSet> unAssignAllDistributionSetsByTag(final Long dsTagId) { public List<DistributionSet> unAssignAllDistributionSetsByTag(final Long dsTagId) {
final DistributionSetTag distributionSetTag = Optional final DistributionSetTag distributionSetTag = tagManagement.findDistributionSetTagById(dsTagId)
.ofNullable(tagManagement.findDistributionSetTagById(dsTagId)) .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, dsTagId));
.orElseThrow(() -> new EntityNotFoundException(
"DistributionSet Tag with given ID " + dsTagId + " not found."));
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
final Collection<JpaDistributionSet> distributionSets = (Collection) distributionSetTag final Collection<JpaDistributionSet> distributionSets = (Collection) distributionSetTag
@@ -854,13 +875,11 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
final List<JpaDistributionSet> allDs = findDistributionSetListWithDetails(Arrays.asList(dsId)); final List<JpaDistributionSet> allDs = findDistributionSetListWithDetails(Arrays.asList(dsId));
if (allDs.isEmpty()) { if (allDs.isEmpty()) {
throw new EntityNotFoundException("DistributionSet with given ID " + dsId + " not found."); throw new EntityNotFoundException(DistributionSet.class, dsId);
} }
final DistributionSetTag distributionSetTag = Optional final DistributionSetTag distributionSetTag = tagManagement.findDistributionSetTagById(dsTagId)
.ofNullable(tagManagement.findDistributionSetTagById(dsTagId)) .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, dsTagId));
.orElseThrow(() -> new EntityNotFoundException(
"DistributionSet Tag with given ID " + dsTagId + " not found."));
final List<JpaDistributionSet> unAssignTag = unAssignTag(allDs, distributionSetTag); final List<JpaDistributionSet> unAssignTag = unAssignTag(allDs, distributionSetTag);
return unAssignTag.isEmpty() ? null : unAssignTag.get(0); return unAssignTag.isEmpty() ? null : unAssignTag.get(0);
} }
@@ -885,7 +904,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteDistributionSet(final Long setId) { public void deleteDistributionSet(final Long setId) {
if (!distributionSetRepository.exists(setId)) { if (!distributionSetRepository.exists(setId)) {
throw new EntityNotFoundException("DistributionSet with given ID " + setId + " does not exist."); throw new EntityNotFoundException(DistributionSet.class, setId);
} }
deleteDistributionSet(Lists.newArrayList(setId)); deleteDistributionSet(Lists.newArrayList(setId));
@@ -893,6 +912,10 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Override @Override
public Long countDistributionSetsByType(final Long typeId) { public Long countDistributionSetsByType(final Long typeId) {
if (!distributionSetTypeRepository.exists(typeId)) {
throw new EntityNotFoundException(DistributionSetType.class, typeId);
}
return distributionSetRepository.countByTypeId(typeId); return distributionSetRepository.countByTypeId(typeId);
} }

View File

@@ -78,8 +78,8 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
private VirtualPropertyReplacer virtualPropertyReplacer; private VirtualPropertyReplacer virtualPropertyReplacer;
@Override @Override
public RolloutGroup findRolloutGroupById(final Long rolloutGroupId) { public Optional<RolloutGroup> findRolloutGroupById(final Long rolloutGroupId) {
return rolloutGroupRepository.findOne(rolloutGroupId); return Optional.ofNullable(rolloutGroupRepository.findOne(rolloutGroupId));
} }
@Override @Override
@@ -131,14 +131,21 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
} }
@Override @Override
public RolloutGroup findRolloutGroupWithDetailedStatus(final Long rolloutGroupId) { public Optional<RolloutGroup> findRolloutGroupWithDetailedStatus(final Long rolloutGroupId) {
final JpaRolloutGroup rolloutGroup = (JpaRolloutGroup) findRolloutGroupById(rolloutGroupId); final Optional<RolloutGroup> rolloutGroup = findRolloutGroupById(rolloutGroupId);
if (!rolloutGroup.isPresent()) {
return rolloutGroup;
}
final JpaRolloutGroup jpaRolloutGroup = (JpaRolloutGroup) rolloutGroup.get();
final List<TotalTargetCountActionStatus> rolloutStatusCountItems = actionRepository final List<TotalTargetCountActionStatus> rolloutStatusCountItems = actionRepository
.getStatusCountByRolloutGroupId(rolloutGroupId); .getStatusCountByRolloutGroupId(rolloutGroupId);
final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(rolloutStatusCountItems, final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(rolloutStatusCountItems,
Long.valueOf(rolloutGroup.getTotalTargets())); Long.valueOf(jpaRolloutGroup.getTotalTargets()));
rolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus); jpaRolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus);
return rolloutGroup; return rolloutGroup;
} }
@@ -168,9 +175,8 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
@Override @Override
public Page<Target> findRolloutGroupTargets(final Long rolloutGroupId, final Pageable page) { public Page<Target> findRolloutGroupTargets(final Long rolloutGroupId, final Pageable page) {
final JpaRolloutGroup rolloutGroup = Optional.ofNullable(rolloutGroupRepository.findOne(rolloutGroupId)) final JpaRolloutGroup rolloutGroup = rolloutGroupRepository.findById(rolloutGroupId)
.orElseThrow(() -> new EntityNotFoundException( .orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutGroupId));
"Rollout Group with given ID " + rolloutGroupId + " not found."));
if (isRolloutStatusReady(rolloutGroup)) { if (isRolloutStatusReady(rolloutGroup)) {
// in case of status ready the action has not been created yet and // in case of status ready the action has not been created yet and

View File

@@ -17,7 +17,6 @@ import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.persistence.EntityNotFoundException;
import javax.validation.ConstraintDeclarationException; import javax.validation.ConstraintDeclarationException;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@@ -34,6 +33,7 @@ import org.eclipse.hawkbit.repository.builder.RolloutUpdate;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupCreatedEvent;
import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; import org.eclipse.hawkbit.repository.exception.ConstraintViolationException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException; import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException;
import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
@@ -147,7 +147,6 @@ public class JpaRolloutManagement implements RolloutManagement {
@Override @Override
public Page<Rollout> findAllByPredicate(final String rsqlParam, final Pageable pageable) { public Page<Rollout> findAllByPredicate(final String rsqlParam, final Pageable pageable) {
final Specification<JpaRollout> specification = RSQLUtility.parse(rsqlParam, RolloutFields.class, final Specification<JpaRollout> specification = RSQLUtility.parse(rsqlParam, RolloutFields.class,
virtualPropertyReplacer); virtualPropertyReplacer);
@@ -156,8 +155,8 @@ public class JpaRolloutManagement implements RolloutManagement {
} }
@Override @Override
public Rollout findRolloutById(final Long rolloutId) { public Optional<Rollout> findRolloutById(final Long rolloutId) {
return rolloutRepository.findOne(rolloutId); return Optional.ofNullable(rolloutRepository.findOne(rolloutId));
} }
@Override @Override
@@ -181,9 +180,9 @@ public class JpaRolloutManagement implements RolloutManagement {
} }
private JpaRollout createRollout(final JpaRollout rollout) { private JpaRollout createRollout(final JpaRollout rollout) {
final JpaRollout existingRollout = rolloutRepository.findByName(rollout.getName()); final Optional<Rollout> existingRollout = rolloutRepository.findByName(rollout.getName());
if (existingRollout != null) { if (existingRollout.isPresent()) {
throw new EntityAlreadyExistsException(existingRollout.getName()); throw new EntityAlreadyExistsException(existingRollout.get().getName());
} }
final Long totalTargets = targetManagement.countTargetByTargetFilterQuery(rollout.getTargetFilterQuery()); final Long totalTargets = targetManagement.countTargetByTargetFilterQuery(rollout.getTargetFilterQuery());
@@ -294,8 +293,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying @Modifying
public void fillRolloutGroupsWithTargets(final Long rolloutId) { public void fillRolloutGroupsWithTargets(final Long rolloutId) {
final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(rolloutId)) final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(rolloutId);
.orElseThrow(() -> new EntityNotFoundException("Rollout with id " + rolloutId + " not found."));
RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.CREATING); RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.CREATING);
@@ -409,7 +407,7 @@ public class JpaRolloutManagement implements RolloutManagement {
throw new ConstraintDeclarationException("Rollout target filter does not match any targets"); throw new ConstraintDeclarationException("Rollout target filter does not match any targets");
} }
RolloutGroupsValidation validation = validateTargetsInGroups(groups, baseFilter, totalTargets); final RolloutGroupsValidation validation = validateTargetsInGroups(groups, baseFilter, totalTargets);
return totalTargets - validation.getTargetsInGroups(); return totalTargets - validation.getTargetsInGroups();
} }
@@ -433,14 +431,14 @@ public class JpaRolloutManagement implements RolloutManagement {
final long totalTargets) { final long totalTargets) {
final List<Long> groupTargetCounts = new ArrayList<>(groups.size()); final List<Long> groupTargetCounts = new ArrayList<>(groups.size());
final Map<String, Long> targetFilterCounts = groups.stream() final Map<String, Long> targetFilterCounts = groups.stream()
.map(group -> RolloutHelper.getGroupTargetFilter(baseFilter, group)).distinct().collect(Collectors .map(group -> RolloutHelper.getGroupTargetFilter(baseFilter, group)).distinct()
.toMap(Function.identity(), filter -> targetManagement.countTargetByTargetFilterQuery(filter))); .collect(Collectors.toMap(Function.identity(), targetManagement::countTargetByTargetFilterQuery));
long unusedTargetsCount = 0; long unusedTargetsCount = 0;
for (int i = 0; i < groups.size(); i++) { for (int i = 0; i < groups.size(); i++) {
final RolloutGroup group = groups.get(i); final RolloutGroup group = groups.get(i);
String groupTargetFilter = RolloutHelper.getGroupTargetFilter(baseFilter, group); final String groupTargetFilter = RolloutHelper.getGroupTargetFilter(baseFilter, group);
RolloutHelper.verifyRolloutGroupTargetPercentage(group.getTargetPercentage()); RolloutHelper.verifyRolloutGroupTargetPercentage(group.getTargetPercentage());
final long targetsInGroupFilter = targetFilterCounts.get(groupTargetFilter); final long targetsInGroupFilter = targetFilterCounts.get(groupTargetFilter);
@@ -474,8 +472,8 @@ public class JpaRolloutManagement implements RolloutManagement {
return 0; return 0;
} }
final List<RolloutGroup> previousGroups = groups.subList(0, groupIndex); final List<RolloutGroup> previousGroups = groups.subList(0, groupIndex);
String overlappingTargetsFilter = RolloutHelper.getOverlappingWithGroupsTargetFilter(baseFilter, previousGroups, final String overlappingTargetsFilter = RolloutHelper.getOverlappingWithGroupsTargetFilter(baseFilter,
group); previousGroups, group);
if (targetFilterCounts.containsKey(overlappingTargetsFilter)) { if (targetFilterCounts.containsKey(overlappingTargetsFilter)) {
return targetFilterCounts.get(overlappingTargetsFilter); return targetFilterCounts.get(overlappingTargetsFilter);
@@ -490,8 +488,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying @Modifying
public Rollout startRollout(final Long rolloutId) { public Rollout startRollout(final Long rolloutId) {
final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(rolloutId)) final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(rolloutId);
.orElseThrow(() -> new EntityNotFoundException("Rollout with id " + rolloutId + " not found."));
RolloutHelper.checkIfRolloutCanStarted(rollout, rollout); RolloutHelper.checkIfRolloutCanStarted(rollout, rollout);
rollout.setStatus(RolloutStatus.STARTING); rollout.setStatus(RolloutStatus.STARTING);
rollout.setLastCheck(0); rollout.setLastCheck(0);
@@ -516,7 +513,6 @@ public class JpaRolloutManagement implements RolloutManagement {
jpaRollout.setStatus(RolloutStatus.RUNNING); jpaRollout.setStatus(RolloutStatus.RUNNING);
jpaRollout.setLastCheck(0); jpaRollout.setLastCheck(0);
rolloutRepository.save(jpaRollout); rolloutRepository.save(jpaRollout);
} }
private boolean ensureAllGroupsAreScheduled(final Rollout rollout) { private boolean ensureAllGroupsAreScheduled(final Rollout rollout) {
@@ -534,12 +530,6 @@ public class JpaRolloutManagement implements RolloutManagement {
/** /**
* Schedules a group of the rollout. Scheduled Actions are created to * Schedules a group of the rollout. Scheduled Actions are created to
* achieve this. The creation of those Actions is allowed to fail. * achieve this. The creation of those Actions is allowed to fail.
*
* @param rollout
* the Rollout
* @param group
* the RolloutGroup
* @return whether the complete group was scheduled
*/ */
private boolean scheduleRolloutGroup(final JpaRollout rollout, final JpaRolloutGroup group) { private boolean scheduleRolloutGroup(final JpaRollout rollout, final JpaRolloutGroup group) {
final long targetsInGroup = rolloutTargetGroupRepository.countByRolloutGroup(group); final long targetsInGroup = rolloutTargetGroupRepository.countByRolloutGroup(group);
@@ -599,19 +589,6 @@ public class JpaRolloutManagement implements RolloutManagement {
* Creates an action entry into the action repository. In case of existing * Creates an action entry into the action repository. In case of existing
* scheduled actions the scheduled actions gets canceled. A scheduled action * scheduled actions the scheduled actions gets canceled. A scheduled action
* is created in-active. * is created in-active.
*
* @param targets
* the targets to create scheduled actions for
* @param distributionSet
* the distribution set for the actions
* @param actionType
* the action type for the action
* @param forcedTime
* the forcedTime of the action
* @param rollout
* the roll out for this action
* @param rolloutGroup
* the roll out group for this action
*/ */
private void createScheduledAction(final Collection<Target> targets, final DistributionSet distributionSet, private void createScheduledAction(final Collection<Target> targets, final DistributionSet distributionSet,
final ActionType actionType, final Long forcedTime, final Rollout rollout, final ActionType actionType, final Long forcedTime, final Rollout rollout,
@@ -620,7 +597,7 @@ public class JpaRolloutManagement implements RolloutManagement {
// is already scheduled and a next action is created then cancel the // is already scheduled and a next action is created then cancel the
// current scheduled action to cancel. E.g. a new scheduled action is // current scheduled action to cancel. E.g. a new scheduled action is
// created. // created.
final List<Long> targetIds = targets.stream().map(t -> t.getId()).collect(Collectors.toList()); final List<Long> targetIds = targets.stream().map(Target::getId).collect(Collectors.toList());
actionRepository.switchStatus(Action.Status.CANCELED, targetIds, false, Action.Status.SCHEDULED); actionRepository.switchStatus(Action.Status.CANCELED, targetIds, false, Action.Status.SCHEDULED);
targets.forEach(target -> { targets.forEach(target -> {
final JpaAction action = new JpaAction(); final JpaAction action = new JpaAction();
@@ -640,8 +617,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying @Modifying
public void pauseRollout(final Long rolloutId) { public void pauseRollout(final Long rolloutId) {
final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(rolloutId)) final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(rolloutId);
.orElseThrow(() -> new EntityNotFoundException("Rollout with id " + rolloutId + " not found."));
if (rollout.getStatus() != RolloutStatus.RUNNING) { if (rollout.getStatus() != RolloutStatus.RUNNING) {
throw new RolloutIllegalStateException("Rollout can only be paused in state running but current state is " throw new RolloutIllegalStateException("Rollout can only be paused in state running but current state is "
+ rollout.getStatus().name().toLowerCase()); + rollout.getStatus().name().toLowerCase());
@@ -659,8 +635,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying @Modifying
public void resumeRollout(final Long rolloutId) { public void resumeRollout(final Long rolloutId) {
final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(rolloutId)) final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(rolloutId);
.orElseThrow(() -> new EntityNotFoundException("Rollout with id " + rolloutId + " not found."));
if (!(RolloutStatus.PAUSED.equals(rollout.getStatus()))) { if (!(RolloutStatus.PAUSED.equals(rollout.getStatus()))) {
throw new RolloutIllegalStateException("Rollout can only be resumed in state paused but current state is " throw new RolloutIllegalStateException("Rollout can only be resumed in state paused but current state is "
+ rollout.getStatus().name().toLowerCase()); + rollout.getStatus().name().toLowerCase());
@@ -855,7 +830,6 @@ public class JpaRolloutManagement implements RolloutManagement {
startFirstRolloutGroup(rollout); startFirstRolloutGroup(rollout);
} }
}); });
} }
@Override @Override
@@ -876,7 +850,6 @@ public class JpaRolloutManagement implements RolloutManagement {
startRollout(rollout.getId()); startRollout(rollout.getId());
} }
}); });
} }
private List<JpaRollout> getRolloutsToCheckForStatus(final long delayBetweenChecks, final RolloutStatus status) { private List<JpaRollout> getRolloutsToCheckForStatus(final long delayBetweenChecks, final RolloutStatus status) {
@@ -891,7 +864,6 @@ public class JpaRolloutManagement implements RolloutManagement {
} }
return rolloutRepository.findByLastCheckAndStatus(lastCheck, status); return rolloutRepository.findByLastCheckAndStatus(lastCheck, status);
} }
@Override @Override
@@ -913,7 +885,7 @@ public class JpaRolloutManagement implements RolloutManagement {
} }
@Override @Override
public Rollout findRolloutByName(final String rolloutName) { public Optional<Rollout> findRolloutByName(final String rolloutName) {
return rolloutRepository.findByName(rolloutName); return rolloutRepository.findByName(rolloutName);
} }
@@ -922,8 +894,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Modifying @Modifying
public Rollout updateRollout(final RolloutUpdate u) { public Rollout updateRollout(final RolloutUpdate u) {
final GenericRolloutUpdate update = (GenericRolloutUpdate) u; final GenericRolloutUpdate update = (GenericRolloutUpdate) u;
final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(update.getId())) final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(update.getId());
.orElseThrow(() -> new EntityNotFoundException("Rollout with id " + update.getId() + " not found."));
update.getName().ifPresent(rollout::setName); update.getName().ifPresent(rollout::setName);
update.getDescription().ifPresent(rollout::setDescription); update.getDescription().ifPresent(rollout::setDescription);
@@ -931,32 +902,40 @@ public class JpaRolloutManagement implements RolloutManagement {
update.getForcedTime().ifPresent(rollout::setForcedTime); update.getForcedTime().ifPresent(rollout::setForcedTime);
update.getStartAt().ifPresent(rollout::setStartAt); update.getStartAt().ifPresent(rollout::setStartAt);
update.getSet().ifPresent(setId -> { update.getSet().ifPresent(setId -> {
final DistributionSet set = distributionSetManagement.findDistributionSetById(setId); final DistributionSet set = distributionSetManagement.findDistributionSetById(setId)
if (set == null) { .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, setId));
throw new EntityNotFoundException("Distribution set cannot be set as it does not exists" + setId);
}
rollout.setDistributionSet(set); rollout.setDistributionSet(set);
}); });
return rolloutRepository.save(rollout); return rolloutRepository.save(rollout);
} }
private JpaRollout getRolloutAndThrowExceptionIfNotFound(final Long rolloutId) {
return rolloutRepository.findById(rolloutId)
.orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId));
}
@Override @Override
public Page<Rollout> findAllRolloutsWithDetailedStatus(final Pageable pageable) { public Page<Rollout> findAllRolloutsWithDetailedStatus(final Pageable pageable) {
final Page<JpaRollout> rollouts = rolloutRepository.findAll(pageable); final Page<JpaRollout> rollouts = rolloutRepository.findAll(pageable);
setRolloutStatusDetails(rollouts); setRolloutStatusDetails(rollouts);
return RolloutHelper.convertPage(rollouts, pageable); return RolloutHelper.convertPage(rollouts, pageable);
} }
@Override @Override
public Rollout findRolloutWithDetailedStatus(final Long rolloutId) { public Optional<Rollout> findRolloutWithDetailedStatus(final Long rolloutId) {
final Rollout rollout = findRolloutById(rolloutId); final Optional<Rollout> rollout = findRolloutById(rolloutId);
if (!rollout.isPresent()) {
return rollout;
}
final List<TotalTargetCountActionStatus> rolloutStatusCountItems = actionRepository final List<TotalTargetCountActionStatus> rolloutStatusCountItems = actionRepository
.getStatusCountByRolloutId(rolloutId); .getStatusCountByRolloutId(rolloutId);
final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(rolloutStatusCountItems, final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(rolloutStatusCountItems,
rollout.getTotalTargets()); rollout.get().getTotalTargets());
((JpaRollout) rollout).setTotalTargetCountStatus(totalTargetCountStatus); ((JpaRollout) rollout.get()).setTotalTargetCountStatus(totalTargetCountStatus);
return rollout; return rollout;
} }
@@ -966,8 +945,7 @@ public class JpaRolloutManagement implements RolloutManagement {
} }
private void setRolloutStatusDetails(final Slice<JpaRollout> rollouts) { private void setRolloutStatusDetails(final Slice<JpaRollout> rollouts) {
final List<Long> rolloutIds = rollouts.getContent().stream().map(rollout -> rollout.getId()) final List<Long> rolloutIds = rollouts.getContent().stream().map(Rollout::getId).collect(Collectors.toList());
.collect(Collectors.toList());
final Map<Long, List<TotalTargetCountActionStatus>> allStatesForRollout = getStatusCountItemForRollout( final Map<Long, List<TotalTargetCountActionStatus>> allStatesForRollout = getStatusCountItemForRollout(
rolloutIds); rolloutIds);
@@ -980,20 +958,24 @@ public class JpaRolloutManagement implements RolloutManagement {
@Override @Override
public float getFinishedPercentForRunningGroup(final Long rolloutId, final Long rolloutGroupId) { public float getFinishedPercentForRunningGroup(final Long rolloutId, final Long rolloutGroupId) {
final RolloutGroup rolloutGroup = Optional.ofNullable(rolloutGroupRepository.findOne(rolloutGroupId)) final RolloutGroup rolloutGroup = rolloutGroupRepository.findById(rolloutGroupId)
.orElseThrow(() -> new EntityNotFoundException( .orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutGroupId));
"Rollout group with given ID " + rolloutGroupId + " not found."));
final long totalGroup = rolloutGroup.getTotalTargets(); final long totalGroup = rolloutGroup.getTotalTargets();
final Long finished = actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rolloutId,
rolloutGroup.getId(), Action.Status.FINISHED);
if (totalGroup == 0) { if (totalGroup == 0) {
// in case e.g. targets has been deleted we don't have any actions // in case e.g. targets has been deleted we don't have any actions
// left for this group, so the group is finished // left for this group, so the group is finished
return 100; return 100;
} }
final Long finished = actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rolloutId,
rolloutGroup.getId(), Action.Status.FINISHED);
// calculate threshold // calculate threshold
return ((float) finished / (float) totalGroup) * 100; return ((float) finished / (float) totalGroup) * 100;
} }
@Override
public boolean exists(final Long rolloutId) {
return rolloutRepository.exists(rolloutId);
}
} }

View File

@@ -55,6 +55,7 @@ import org.eclipse.hawkbit.repository.jpa.specifications.SoftwareModuleSpecifica
import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule; import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.MetaData; import org.eclipse.hawkbit.repository.model.MetaData;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
@@ -122,9 +123,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
public SoftwareModule updateSoftwareModule(final SoftwareModuleUpdate u) { public SoftwareModule updateSoftwareModule(final SoftwareModuleUpdate u) {
final GenericSoftwareModuleUpdate update = (GenericSoftwareModuleUpdate) u; final GenericSoftwareModuleUpdate update = (GenericSoftwareModuleUpdate) u;
final JpaSoftwareModule module = Optional.ofNullable(softwareModuleRepository.findOne(update.getId())) final JpaSoftwareModule module = softwareModuleRepository.findById(update.getId())
.orElseThrow(() -> new EntityNotFoundException( .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, update.getId()));
"Software module cannot be updated as it does not exixt" + update.getId()));
update.getDescription().ifPresent(module::setDescription); update.getDescription().ifPresent(module::setDescription);
update.getVendor().ifPresent(module::setVendor); update.getVendor().ifPresent(module::setVendor);
@@ -138,7 +138,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
public SoftwareModuleType updateSoftwareModuleType(final SoftwareModuleTypeUpdate u) { public SoftwareModuleType updateSoftwareModuleType(final SoftwareModuleTypeUpdate u) {
final GenericSoftwareModuleTypeUpdate update = (GenericSoftwareModuleTypeUpdate) u; final GenericSoftwareModuleTypeUpdate update = (GenericSoftwareModuleTypeUpdate) u;
final JpaSoftwareModuleType type = findSoftwareModuleTypeAndThrowExceptionIfNotFound(update.getId()); final JpaSoftwareModuleType type = (JpaSoftwareModuleType) findSoftwareModuleTypeById(update.getId())
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, update.getId()));
update.getDescription().ifPresent(type::setDescription); update.getDescription().ifPresent(type::setDescription);
update.getColour().ifPresent(type::setColour); update.getColour().ifPresent(type::setColour);
@@ -146,15 +147,6 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return softwareModuleTypeRepository.save(type); return softwareModuleTypeRepository.save(type);
} }
private JpaSoftwareModuleType findSoftwareModuleTypeAndThrowExceptionIfNotFound(final Long smTypeid) {
final JpaSoftwareModuleType set = softwareModuleTypeRepository.findOne(smTypeid);
if (set == null) {
throw new EntityNotFoundException("Software module type cannot be updated as it does not exixt" + smTypeid);
}
return set;
}
@Override @Override
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
@@ -173,6 +165,7 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Override @Override
public Slice<SoftwareModule> findSoftwareModulesByType(final Pageable pageable, final Long typeId) { public Slice<SoftwareModule> findSoftwareModulesByType(final Pageable pageable, final Long typeId) {
throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
final List<Specification<JpaSoftwareModule>> specList = Lists.newArrayListWithExpectedSize(2); final List<Specification<JpaSoftwareModule>> specList = Lists.newArrayListWithExpectedSize(2);
@@ -182,6 +175,12 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return convertSmPage(findSwModuleByCriteriaAPI(pageable, specList), pageable); return convertSmPage(findSwModuleByCriteriaAPI(pageable, specList), pageable);
} }
private void throwExceptionIfSoftwareModuleTypeDoesNotExist(final Long typeId) {
if (!softwareModuleTypeRepository.exists(typeId)) {
throw new EntityNotFoundException(SoftwareModuleType.class, typeId);
}
}
private static Slice<SoftwareModule> convertSmPage(final Slice<JpaSoftwareModule> findAll, private static Slice<SoftwareModule> convertSmPage(final Slice<JpaSoftwareModule> findAll,
final Pageable pageable) { final Pageable pageable) {
return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, 0); return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, 0);
@@ -197,14 +196,16 @@ public class JpaSoftwareManagement implements SoftwareManagement {
} }
@Override @Override
public SoftwareModule findSoftwareModuleById(final Long id) { public Optional<SoftwareModule> findSoftwareModuleById(final Long id) {
return softwareModuleRepository.findOne(id); return Optional.ofNullable(softwareModuleRepository.findOne(id));
} }
@Override @Override
public SoftwareModule findSoftwareModuleByNameAndVersion(final String name, final String version, public Optional<SoftwareModule> findSoftwareModuleByNameAndVersion(final String name, final String version,
final Long typeId) { final Long typeId) {
throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
return softwareModuleRepository.findOneByNameAndVersionAndTypeId(name, version, typeId); return softwareModuleRepository.findOneByNameAndVersionAndTypeId(name, version, typeId);
} }
@@ -233,6 +234,12 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteSoftwareModules(final Collection<Long> ids) { public void deleteSoftwareModules(final Collection<Long> ids) {
final List<JpaSoftwareModule> swModulesToDelete = softwareModuleRepository.findByIdIn(ids); final List<JpaSoftwareModule> swModulesToDelete = softwareModuleRepository.findByIdIn(ids);
if (swModulesToDelete.size() < ids.size()) {
throw new EntityNotFoundException(SoftwareModule.class, ids,
swModulesToDelete.stream().map(SoftwareModule::getId).collect(Collectors.toList()));
}
final Set<Long> assignedModuleIds = new HashSet<>(); final Set<Long> assignedModuleIds = new HashSet<>();
swModulesToDelete.forEach(swModule -> { swModulesToDelete.forEach(swModule -> {
@@ -329,6 +336,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
} }
if (null != typeId) { if (null != typeId) {
throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
spec = SoftwareModuleSpecification.equalType(typeId); spec = SoftwareModuleSpecification.equalType(typeId);
specList.add(spec); specList.add(spec);
} }
@@ -393,8 +402,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
Predicate[] unassignedSpec; Predicate[] unassignedSpec;
if (!assignedSoftwareModules.isEmpty()) { if (!assignedSoftwareModules.isEmpty()) {
unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot, unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot,
unassignedQuery, cb, cb.not(unassignedRoot.get(JpaSoftwareModule_.id) unassignedQuery, cb, cb.not(unassignedRoot.get(JpaSoftwareModule_.id).in(
.in(assignedSoftwareModules.stream().map(sw -> sw.getId()).collect(Collectors.toList())))); assignedSoftwareModules.stream().map(SoftwareModule::getId).collect(Collectors.toList()))));
} else { } else {
unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot, unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot,
unassignedQuery, cb); unassignedQuery, cb);
@@ -412,13 +421,14 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return new SliceImpl<>(resultList); return new SliceImpl<>(resultList);
} }
private static List<Specification<JpaSoftwareModule>> buildSpecificationList(final String searchText, private List<Specification<JpaSoftwareModule>> buildSpecificationList(final String searchText, final Long typeId) {
final Long typeId) {
final List<Specification<JpaSoftwareModule>> specList = Lists.newArrayListWithExpectedSize(3); final List<Specification<JpaSoftwareModule>> specList = Lists.newArrayListWithExpectedSize(3);
if (!Strings.isNullOrEmpty(searchText)) { if (!Strings.isNullOrEmpty(searchText)) {
specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText)); specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText));
} }
if (typeId != null) { if (typeId != null) {
throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
specList.add(SoftwareModuleSpecification.equalType(typeId)); specList.add(SoftwareModuleSpecification.equalType(typeId));
} }
specList.add(SoftwareModuleSpecification.isDeletedFalse()); specList.add(SoftwareModuleSpecification.isDeletedFalse());
@@ -447,6 +457,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
} }
if (null != typeId) { if (null != typeId) {
throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
spec = SoftwareModuleSpecification.equalType(typeId); spec = SoftwareModuleSpecification.equalType(typeId);
specList.add(spec); specList.add(spec);
} }
@@ -465,17 +477,17 @@ public class JpaSoftwareManagement implements SoftwareManagement {
} }
@Override @Override
public SoftwareModuleType findSoftwareModuleTypeByKey(final String key) { public Optional<SoftwareModuleType> findSoftwareModuleTypeByKey(final String key) {
return softwareModuleTypeRepository.findByKey(key); return softwareModuleTypeRepository.findByKey(key);
} }
@Override @Override
public SoftwareModuleType findSoftwareModuleTypeById(final Long id) { public Optional<SoftwareModuleType> findSoftwareModuleTypeById(final Long smTypeId) {
return softwareModuleTypeRepository.findOne(id); return Optional.ofNullable(softwareModuleTypeRepository.findOne(smTypeId));
} }
@Override @Override
public SoftwareModuleType findSoftwareModuleTypeByName(final String name) { public Optional<SoftwareModuleType> findSoftwareModuleTypeByName(final String name) {
return softwareModuleTypeRepository.findByName(name); return softwareModuleTypeRepository.findByName(name);
} }
@@ -492,9 +504,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteSoftwareModuleType(final Long typeId) { public void deleteSoftwareModuleType(final Long typeId) {
final JpaSoftwareModuleType toDelete = Optional.ofNullable(softwareModuleTypeRepository.findOne(typeId)) final JpaSoftwareModuleType toDelete = softwareModuleTypeRepository.findById(typeId)
.orElseThrow(() -> new EntityNotFoundException( .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, typeId));
"Software Module Type with giben ID " + typeId + " does not exist."));
if (softwareModuleRepository.countByType(toDelete) > 0 if (softwareModuleRepository.countByType(toDelete) > 0
|| distributionSetTypeRepository.countByElementsSmType(toDelete) > 0) { || distributionSetTypeRepository.countByElementsSmType(toDelete) > 0) {
@@ -507,6 +518,10 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Override @Override
public Page<SoftwareModule> findSoftwareModuleByAssignedTo(final Pageable pageable, final Long setId) { public Page<SoftwareModule> findSoftwareModuleByAssignedTo(final Pageable pageable, final Long setId) {
if (!distributionSetRepository.exists(setId)) {
throw new EntityNotFoundException(DistributionSet.class, setId);
}
return softwareModuleRepository.findByAssignedToId(pageable, setId); return softwareModuleRepository.findByAssignedToId(pageable, setId);
} }
@@ -548,11 +563,12 @@ public class JpaSoftwareManagement implements SoftwareManagement {
public SoftwareModuleMetadata updateSoftwareModuleMetadata(final Long moduleId, final MetaData md) { public SoftwareModuleMetadata updateSoftwareModuleMetadata(final Long moduleId, final MetaData md) {
// check if exists otherwise throw entity not found exception // check if exists otherwise throw entity not found exception
final JpaSoftwareModuleMetadata metadata = findSoftwareModuleMetadata( final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) findSoftwareModuleMetadata(moduleId,
new SwMetadataCompositeKey(moduleId, md.getKey())); md.getKey()).orElseThrow(
() -> new EntityNotFoundException(SoftwareModuleMetadata.class, moduleId, md.getKey()));
metadata.setValue(md.getValue()); metadata.setValue(md.getValue());
touch(moduleId); touch(metadata.getSoftwareModule());
return softwareModuleMetadataRepository.save(metadata); return softwareModuleMetadataRepository.save(metadata);
} }
@@ -560,40 +576,63 @@ public class JpaSoftwareManagement implements SoftwareManagement {
* Method to get the latest module based on ID after the metadata changes * Method to get the latest module based on ID after the metadata changes
* for that module. * for that module.
* *
* @param distributionSet * @param latestModule
* Distribution set * module to touch
*/ */
private JpaSoftwareModule touch(final Long moduleId) { private JpaSoftwareModule touch(final SoftwareModule latestModule) {
final JpaSoftwareModule latestModule = softwareModuleRepository.findOne(moduleId);
// merge base distribution set so optLockRevision gets updated and audit // merge base distribution set so optLockRevision gets updated and audit
// log written because // log written because
// modifying metadata is modifying the base distribution set itself for // modifying metadata is modifying the base distribution set itself for
// auditing purposes. // auditing purposes.
final JpaSoftwareModule result = entityManager.merge(latestModule); final JpaSoftwareModule result = entityManager.merge((JpaSoftwareModule) latestModule);
result.setLastModifiedAt(0L); result.setLastModifiedAt(0L);
return result; return result;
} }
/**
* Method to get the latest module based on ID after the metadata changes
* for that module.
*
* @param moduleId
* of the module to touch
*/
private JpaSoftwareModule touch(final Long moduleId) {
return touch(findSoftwareModuleById(moduleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, moduleId)));
}
@Override @Override
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying @Modifying
public void deleteSoftwareModuleMetadata(final Long moduleId, final String key) { public void deleteSoftwareModuleMetadata(final Long moduleId, final String key) {
touch(moduleId); final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) findSoftwareModuleMetadata(moduleId, key)
softwareModuleMetadataRepository.delete(new SwMetadataCompositeKey(moduleId, key)); .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleMetadata.class, moduleId, key));
touch(metadata.getSoftwareModule());
softwareModuleMetadataRepository.delete(metadata.getId());
} }
@Override @Override
public Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Long swId, public Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Long swId,
final Pageable pageable) { final Pageable pageable) {
throwExceptionIfSoftwareModuleDoesNotExist(swId);
return softwareModuleMetadataRepository.findBySoftwareModuleId(swId, pageable); return softwareModuleMetadataRepository.findBySoftwareModuleId(swId, pageable);
} }
private void throwExceptionIfSoftwareModuleDoesNotExist(final Long swId) {
if (!softwareModuleRepository.exists(swId)) {
throw new EntityNotFoundException(SoftwareModule.class, swId);
}
}
@Override @Override
public Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId, public Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId,
final String rsqlParam, final Pageable pageable) { final String rsqlParam, final Pageable pageable) {
throwExceptionIfSoftwareModuleDoesNotExist(softwareModuleId);
final Specification<JpaSoftwareModuleMetadata> spec = RSQLUtility.parse(rsqlParam, final Specification<JpaSoftwareModuleMetadata> spec = RSQLUtility.parse(rsqlParam,
SoftwareModuleMetadataFields.class, virtualPropertyReplacer); SoftwareModuleMetadataFields.class, virtualPropertyReplacer);
return convertSmMdPage( return convertSmMdPage(
@@ -609,6 +648,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Override @Override
public List<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId) { public List<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId) {
throwExceptionIfSoftwareModuleDoesNotExist(softwareModuleId);
return Collections.unmodifiableList(softwareModuleMetadataRepository return Collections.unmodifiableList(softwareModuleMetadataRepository
.findAll((Specification<JpaSoftwareModuleMetadata>) (root, query, cb) -> cb .findAll((Specification<JpaSoftwareModuleMetadata>) (root, query, cb) -> cb
.and(cb.equal(root.get(JpaSoftwareModuleMetadata_.softwareModule).get(JpaSoftwareModule_.id), .and(cb.equal(root.get(JpaSoftwareModuleMetadata_.softwareModule).get(JpaSoftwareModule_.id),
@@ -616,16 +657,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
} }
@Override @Override
public SoftwareModuleMetadata findSoftwareModuleMetadata(final Long moduleId, final String key) { public Optional<SoftwareModuleMetadata> findSoftwareModuleMetadata(final Long moduleId, final String key) {
return findSoftwareModuleMetadata(new SwMetadataCompositeKey(moduleId, key)); return Optional.ofNullable(softwareModuleMetadataRepository.findOne(new SwMetadataCompositeKey(moduleId, key)));
}
private JpaSoftwareModuleMetadata findSoftwareModuleMetadata(final SwMetadataCompositeKey id) {
final JpaSoftwareModuleMetadata findOne = softwareModuleMetadataRepository.findOne(id);
if (findOne == null) {
throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist");
}
return findOne;
} }
private void checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(final SwMetadataCompositeKey metadataId) { private void checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(final SwMetadataCompositeKey metadataId) {

View File

@@ -62,7 +62,7 @@ public class JpaTagManagement implements TagManagement {
private VirtualPropertyReplacer virtualPropertyReplacer; private VirtualPropertyReplacer virtualPropertyReplacer;
@Override @Override
public TargetTag findTargetTag(final String name) { public Optional<TargetTag> findTargetTag(final String name) {
return targetTagRepository.findByNameEquals(name); return targetTagRepository.findByNameEquals(name);
} }
@@ -73,7 +73,7 @@ public class JpaTagManagement implements TagManagement {
final JpaTargetTag targetTag = create.buildTargetTag(); final JpaTargetTag targetTag = create.buildTargetTag();
if (findTargetTag(targetTag.getName()) != null) { if (findTargetTag(targetTag.getName()).isPresent()) {
throw new EntityAlreadyExistsException(); throw new EntityAlreadyExistsException();
} }
@@ -95,7 +95,8 @@ public class JpaTagManagement implements TagManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteTargetTag(final String targetTagName) { public void deleteTargetTag(final String targetTagName) {
final JpaTargetTag tag = targetTagRepository.findByNameEquals(targetTagName); final TargetTag tag = targetTagRepository.findByNameEquals(targetTagName)
.orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagName));
targetRepository.findByTag(tag.getId()).forEach(set -> { targetRepository.findByTag(tag.getId()).forEach(set -> {
set.removeTag(tag); set.removeTag(tag);
@@ -107,11 +108,6 @@ public class JpaTagManagement implements TagManagement {
} }
@Override
public List<TargetTag> findAllTargetTags() {
return Collections.unmodifiableList(targetTagRepository.findAll());
}
@Override @Override
public Page<TargetTag> findAllTargetTags(final String rsqlParam, final Pageable pageable) { public Page<TargetTag> findAllTargetTags(final String rsqlParam, final Pageable pageable) {
@@ -139,8 +135,8 @@ public class JpaTagManagement implements TagManagement {
public TargetTag updateTargetTag(final TagUpdate u) { public TargetTag updateTargetTag(final TagUpdate u) {
final GenericTagUpdate update = (GenericTagUpdate) u; final GenericTagUpdate update = (GenericTagUpdate) u;
final JpaTargetTag tag = Optional.ofNullable(targetTagRepository.findOne(update.getId())) final JpaTargetTag tag = targetTagRepository.findById(update.getId())
.orElseThrow(() -> new EntityNotFoundException("Target tag with ID " + update.getId() + " not found")); .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, update.getId()));
update.getName().ifPresent(tag::setName); update.getName().ifPresent(tag::setName);
update.getDescription().ifPresent(tag::setDescription); update.getDescription().ifPresent(tag::setDescription);
@@ -155,9 +151,8 @@ public class JpaTagManagement implements TagManagement {
public DistributionSetTag updateDistributionSetTag(final TagUpdate u) { public DistributionSetTag updateDistributionSetTag(final TagUpdate u) {
final GenericTagUpdate update = (GenericTagUpdate) u; final GenericTagUpdate update = (GenericTagUpdate) u;
final JpaDistributionSetTag tag = Optional.ofNullable(distributionSetTagRepository.findOne(update.getId())) final JpaDistributionSetTag tag = distributionSetTagRepository.findById(update.getId())
.orElseThrow(() -> new EntityNotFoundException( .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, update.getId()));
"Distribution set tag with ID " + update.getId() + " not found"));
update.getName().ifPresent(tag::setName); update.getName().ifPresent(tag::setName);
update.getDescription().ifPresent(tag::setDescription); update.getDescription().ifPresent(tag::setDescription);
@@ -167,7 +162,7 @@ public class JpaTagManagement implements TagManagement {
} }
@Override @Override
public DistributionSetTag findDistributionSetTag(final String name) { public Optional<DistributionSetTag> findDistributionSetTag(final String name) {
return distributionSetTagRepository.findByNameEquals(name); return distributionSetTagRepository.findByNameEquals(name);
} }
@@ -179,7 +174,7 @@ public class JpaTagManagement implements TagManagement {
final JpaDistributionSetTag distributionSetTag = create.buildDistributionSetTag(); final JpaDistributionSetTag distributionSetTag = create.buildDistributionSetTag();
if (distributionSetTagRepository.findByNameEquals(distributionSetTag.getName()) != null) { if (distributionSetTagRepository.findByNameEquals(distributionSetTag.getName()).isPresent()) {
throw new EntityAlreadyExistsException(); throw new EntityAlreadyExistsException();
} }
@@ -203,7 +198,8 @@ public class JpaTagManagement implements TagManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteDistributionSetTag(final String tagName) { public void deleteDistributionSetTag(final String tagName) {
final JpaDistributionSetTag tag = distributionSetTagRepository.findByNameEquals(tagName); final DistributionSetTag tag = distributionSetTagRepository.findByNameEquals(tagName)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, tagName));
distributionSetRepository.findByTag(tag).forEach(set -> { distributionSetRepository.findByTag(tag).forEach(set -> {
set.removeTag(tag); set.removeTag(tag);
@@ -219,13 +215,13 @@ public class JpaTagManagement implements TagManagement {
} }
@Override @Override
public TargetTag findTargetTagById(final Long id) { public Optional<TargetTag> findTargetTagById(final Long id) {
return targetTagRepository.findOne(id); return Optional.ofNullable(targetTagRepository.findOne(id));
} }
@Override @Override
public DistributionSetTag findDistributionSetTagById(final Long id) { public Optional<DistributionSetTag> findDistributionSetTagById(final Long id) {
return distributionSetTagRepository.findOne(id); return Optional.ofNullable(distributionSetTagRepository.findOne(id));
} }
@Override @Override

View File

@@ -76,7 +76,7 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
final JpaTargetFilterQuery query = create.build(); final JpaTargetFilterQuery query = create.build();
if (targetFilterQueryRepository.findByName(query.getName()) != null) { if (targetFilterQueryRepository.findByName(query.getName()).isPresent()) {
throw new EntityAlreadyExistsException(query.getName()); throw new EntityAlreadyExistsException(query.getName());
} }
return targetFilterQueryRepository.save(query); return targetFilterQueryRepository.save(query);
@@ -86,6 +86,9 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteTargetFilterQuery(final Long targetFilterQueryId) { public void deleteTargetFilterQuery(final Long targetFilterQueryId) {
findTargetFilterQueryById(targetFilterQueryId)
.orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, targetFilterQueryId));
targetFilterQueryRepository.delete(targetFilterQueryId); targetFilterQueryRepository.delete(targetFilterQueryId);
} }
@@ -165,13 +168,13 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
} }
@Override @Override
public TargetFilterQuery findTargetFilterQueryByName(final String targetFilterQueryName) { public Optional<TargetFilterQuery> findTargetFilterQueryByName(final String targetFilterQueryName) {
return targetFilterQueryRepository.findByName(targetFilterQueryName); return targetFilterQueryRepository.findByName(targetFilterQueryName);
} }
@Override @Override
public TargetFilterQuery findTargetFilterQueryById(final Long targetFilterQueryId) { public Optional<TargetFilterQuery> findTargetFilterQueryById(final Long targetFilterQueryId) {
return targetFilterQueryRepository.findOne(targetFilterQueryId); return Optional.ofNullable(targetFilterQueryRepository.findOne(targetFilterQueryId));
} }
@Override @Override
@@ -201,18 +204,13 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
} }
private JpaDistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) { private JpaDistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) {
final JpaDistributionSet set = (JpaDistributionSet) distributionSetManagement return (JpaDistributionSet) distributionSetManagement.findDistributionSetByIdWithDetails(setId)
.findDistributionSetByIdWithDetails(setId); .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, setId));
if (set == null) {
throw new EntityNotFoundException("Distribution set cannot be updated as it does not exixt" + setId);
}
return set;
} }
private JpaTargetFilterQuery findTargetFilterQueryOrThrowExceptionIfNotFound(final Long queryId) { private JpaTargetFilterQuery findTargetFilterQueryOrThrowExceptionIfNotFound(final Long queryId) {
return Optional.ofNullable(targetFilterQueryRepository.findOne(queryId)).orElseThrow( return targetFilterQueryRepository.findById(queryId)
() -> new EntityNotFoundException("TargetFilterQuery with given ID " + queryId + " not found!")); .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, queryId));
} }
@Override @Override

View File

@@ -48,6 +48,8 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_;
import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder;
import org.eclipse.hawkbit.repository.jpa.specifications.TargetSpecifications; import org.eclipse.hawkbit.repository.jpa.specifications.TargetSpecifications;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetTag;
@@ -85,6 +87,12 @@ public class JpaTargetManagement implements TargetManagement {
@Autowired @Autowired
private TargetRepository targetRepository; private TargetRepository targetRepository;
@Autowired
private RolloutGroupRepository rolloutGroupRepository;
@Autowired
private DistributionSetRepository distributionSetRepository;
@Autowired @Autowired
private TargetFilterQueryRepository targetFilterQueryRepository; private TargetFilterQueryRepository targetFilterQueryRepository;
@@ -110,25 +118,29 @@ public class JpaTargetManagement implements TargetManagement {
private VirtualPropertyReplacer virtualPropertyReplacer; private VirtualPropertyReplacer virtualPropertyReplacer;
@Override @Override
public Target findTargetByControllerID(final String controllerId) { public Optional<Target> findTargetByControllerID(final String controllerId) {
return targetRepository.findByControllerId(controllerId); return targetRepository.findByControllerId(controllerId);
} }
@Override @Override
public Target findTargetByControllerIDWithDetails(final String controllerId) { public Optional<Target> findTargetByControllerIDWithDetails(final String controllerId) {
final Target result = targetRepository.findByControllerId(controllerId); final Optional<Target> result = targetRepository.findByControllerId(controllerId);
// load lazy relations // load lazy relations
if (result != null) { if (!result.isPresent()) {
result.getTargetInfo().getControllerAttributes().size(); return result;
if (result.getTargetInfo() != null && result.getTargetInfo().getInstalledDistributionSet() != null) {
result.getTargetInfo().getInstalledDistributionSet().getName();
result.getTargetInfo().getInstalledDistributionSet().getModules().size();
}
if (result.getAssignedDistributionSet() != null) {
result.getAssignedDistributionSet().getName();
result.getAssignedDistributionSet().getModules().size();
}
} }
result.get().getTargetInfo().getControllerAttributes().size();
if (result.get().getTargetInfo() != null
&& result.get().getTargetInfo().getInstalledDistributionSet() != null) {
result.get().getTargetInfo().getInstalledDistributionSet().getName();
result.get().getTargetInfo().getInstalledDistributionSet().getModules().size();
}
if (result.get().getAssignedDistributionSet() != null) {
result.get().getAssignedDistributionSet().getName();
result.get().getAssignedDistributionSet().getModules().size();
}
return result; return result;
} }
@@ -159,10 +171,8 @@ public class JpaTargetManagement implements TargetManagement {
@Override @Override
public Slice<Target> findTargetsByTargetFilterQuery(final Long targetFilterQueryId, final Pageable pageable) { public Slice<Target> findTargetsByTargetFilterQuery(final Long targetFilterQueryId, final Pageable pageable) {
final TargetFilterQuery targetFilterQuery = Optional final TargetFilterQuery targetFilterQuery = targetFilterQueryRepository.findById(targetFilterQueryId)
.ofNullable(targetFilterQueryRepository.findOne(targetFilterQueryId)) .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, targetFilterQueryId));
.orElseThrow(() -> new EntityNotFoundException(
"TargetFilterQuery with given ID" + targetFilterQueryId + " not found"));
return findTargetsBySpec( return findTargetsBySpec(
RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class, virtualPropertyReplacer), pageable); RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class, virtualPropertyReplacer), pageable);
@@ -192,9 +202,8 @@ public class JpaTargetManagement implements TargetManagement {
public Target updateTarget(final TargetUpdate u) { public Target updateTarget(final TargetUpdate u) {
final JpaTargetUpdate update = (JpaTargetUpdate) u; final JpaTargetUpdate update = (JpaTargetUpdate) u;
final JpaTarget target = Optional.ofNullable(targetRepository.findByControllerId(update.getControllerId())) final JpaTarget target = (JpaTarget) targetRepository.findByControllerId(update.getControllerId())
.orElseThrow(() -> new EntityNotFoundException( .orElseThrow(() -> new EntityNotFoundException(Target.class, update.getControllerId()));
"Target with ID " + update.getControllerId() + " not found."));
target.setNew(false); target.setNew(false);
@@ -210,6 +219,13 @@ public class JpaTargetManagement implements TargetManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteTargets(final Collection<Long> targetIDs) { public void deleteTargets(final Collection<Long> targetIDs) {
final List<JpaTarget> targets = targetRepository.findAll(targetIDs);
if (targets.size() < targetIDs.size()) {
throw new EntityNotFoundException(Target.class, targetIDs,
targets.stream().map(Target::getId).collect(Collectors.toList()));
}
targetRepository.deleteByIdIn(targetIDs); targetRepository.deleteByIdIn(targetIDs);
targetIDs.forEach(targetId -> eventPublisher.publishEvent(new TargetDeletedEvent(tenantAware.getCurrentTenant(), targetIDs.forEach(targetId -> eventPublisher.publishEvent(new TargetDeletedEvent(tenantAware.getCurrentTenant(),
@@ -220,22 +236,23 @@ public class JpaTargetManagement implements TargetManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteTarget(final String controllerID) { public void deleteTarget(final String controllerID) {
final Long targetId = Optional.ofNullable(targetRepository.findByControllerId(controllerID)) final Target target = targetRepository.findByControllerId(controllerID)
.orElseThrow( .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerID));
() -> new EntityNotFoundException("Target with given ID " + controllerID + " does not exist."))
.getId();
targetRepository.delete(targetId); targetRepository.delete(target.getId());
} }
@Override @Override
public Page<Target> findTargetByAssignedDistributionSet(final Long distributionSetID, final Pageable pageReq) { public Page<Target> findTargetByAssignedDistributionSet(final Long distributionSetID, final Pageable pageReq) {
throwEntityNotFoundIfDsDoesNotExist(distributionSetID);
return targetRepository.findByAssignedDistributionSetId(pageReq, distributionSetID); return targetRepository.findByAssignedDistributionSetId(pageReq, distributionSetID);
} }
@Override @Override
public Page<Target> findTargetByAssignedDistributionSet(final Long distributionSetID, final String rsqlParam, public Page<Target> findTargetByAssignedDistributionSet(final Long distributionSetID, final String rsqlParam,
final Pageable pageReq) { final Pageable pageReq) {
throwEntityNotFoundIfDsDoesNotExist(distributionSetID);
final Specification<JpaTarget> spec = RSQLUtility.parse(rsqlParam, TargetFields.class, virtualPropertyReplacer); final Specification<JpaTarget> spec = RSQLUtility.parse(rsqlParam, TargetFields.class, virtualPropertyReplacer);
@@ -248,6 +265,12 @@ public class JpaTargetManagement implements TargetManagement {
pageReq); pageReq);
} }
private void throwEntityNotFoundIfDsDoesNotExist(final Long distributionSetID) {
if (!distributionSetRepository.exists(distributionSetID)) {
throw new EntityNotFoundException(DistributionSet.class, distributionSetID);
}
}
private static Page<Target> convertPage(final Page<JpaTarget> findAll, final Pageable pageable) { private static Page<Target> convertPage(final Page<JpaTarget> findAll, final Pageable pageable) {
return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements());
} }
@@ -258,12 +281,14 @@ public class JpaTargetManagement implements TargetManagement {
@Override @Override
public Page<Target> findTargetByInstalledDistributionSet(final Long distributionSetID, final Pageable pageReq) { public Page<Target> findTargetByInstalledDistributionSet(final Long distributionSetID, final Pageable pageReq) {
throwEntityNotFoundIfDsDoesNotExist(distributionSetID);
return targetRepository.findByTargetInfoInstalledDistributionSetId(pageReq, distributionSetID); return targetRepository.findByTargetInfoInstalledDistributionSetId(pageReq, distributionSetID);
} }
@Override @Override
public Page<Target> findTargetByInstalledDistributionSet(final Long distributionSetId, final String rsqlParam, public Page<Target> findTargetByInstalledDistributionSet(final Long distributionSetId, final String rsqlParam,
final Pageable pageable) { final Pageable pageable) {
throwEntityNotFoundIfDsDoesNotExist(distributionSetId);
final Specification<JpaTarget> spec = RSQLUtility.parse(rsqlParam, TargetFields.class, virtualPropertyReplacer); final Specification<JpaTarget> spec = RSQLUtility.parse(rsqlParam, TargetFields.class, virtualPropertyReplacer);
@@ -303,7 +328,7 @@ public class JpaTargetManagement implements TargetManagement {
return countByCriteriaAPI(specList); return countByCriteriaAPI(specList);
} }
private static List<Specification<JpaTarget>> buildSpecificationList(final FilterParams filterParams, private List<Specification<JpaTarget>> buildSpecificationList(final FilterParams filterParams,
final boolean fetch) { final boolean fetch) {
final List<Specification<JpaTarget>> specList = new ArrayList<>(); final List<Specification<JpaTarget>> specList = new ArrayList<>();
if (filterParams.getFilterByStatus() != null && !filterParams.getFilterByStatus().isEmpty()) { if (filterParams.getFilterByStatus() != null && !filterParams.getFilterByStatus().isEmpty()) {
@@ -313,6 +338,8 @@ public class JpaTargetManagement implements TargetManagement {
specList.add(TargetSpecifications.isOverdue(TimestampCalculator.calculateOverdueTimestamp())); specList.add(TargetSpecifications.isOverdue(TimestampCalculator.calculateOverdueTimestamp()));
} }
if (filterParams.getFilterByDistributionId() != null) { if (filterParams.getFilterByDistributionId() != null) {
throwEntityNotFoundIfDsDoesNotExist(filterParams.getFilterByDistributionId());
specList.add(TargetSpecifications specList.add(TargetSpecifications
.hasInstalledOrAssignedDistributionSet(filterParams.getFilterByDistributionId())); .hasInstalledOrAssignedDistributionSet(filterParams.getFilterByDistributionId()));
} }
@@ -352,7 +379,8 @@ public class JpaTargetManagement implements TargetManagement {
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public TargetTagAssignmentResult toggleTagAssignment(final Collection<String> targetIds, final String tagName) { public TargetTagAssignmentResult toggleTagAssignment(final Collection<String> targetIds, final String tagName) {
final TargetTag tag = targetTagRepository.findByNameEquals(tagName); final TargetTag tag = targetTagRepository.findByNameEquals(tagName)
.orElseThrow(() -> new EntityNotFoundException(TargetTag.class, tagName));
final List<JpaTarget> alreadyAssignedTargets = targetRepository.findByTagNameAndControllerIdIn(tagName, final List<JpaTarget> alreadyAssignedTargets = targetRepository.findByTagNameAndControllerIdIn(tagName,
targetIds); targetIds);
final List<JpaTarget> allTargets = targetRepository final List<JpaTarget> allTargets = targetRepository
@@ -388,8 +416,8 @@ public class JpaTargetManagement implements TargetManagement {
final List<JpaTarget> allTargets = targetRepository final List<JpaTarget> allTargets = targetRepository
.findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(controllerIds)); .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(controllerIds));
final JpaTargetTag tag = Optional.ofNullable(targetTagRepository.findOne(tagId)) final JpaTargetTag tag = targetTagRepository.findById(tagId)
.orElseThrow(() -> new EntityNotFoundException("Tag with given ID " + tagId + "does not exist")); .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, tagId));
allTargets.forEach(target -> target.addTag(tag)); allTargets.forEach(target -> target.addTag(tag));
return Collections return Collections
@@ -411,8 +439,8 @@ public class JpaTargetManagement implements TargetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED) @Transactional(isolation = Isolation.READ_UNCOMMITTED)
public List<Target> unAssignAllTargetsByTag(final Long targetTagId) { public List<Target> unAssignAllTargetsByTag(final Long targetTagId) {
final TargetTag tag = Optional.ofNullable(targetTagRepository.findOne(targetTagId)).orElseThrow( final TargetTag tag = targetTagRepository.findById(targetTagId)
() -> new EntityNotFoundException("TargetTag with given ID " + targetTagId + " does not exist.")); .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId));
if (tag.getAssignedToTargets().isEmpty()) { if (tag.getAssignedToTargets().isEmpty()) {
return Collections.emptyList(); return Collections.emptyList();
@@ -428,8 +456,8 @@ public class JpaTargetManagement implements TargetManagement {
final List<Target> allTargets = Collections.unmodifiableList(targetRepository final List<Target> allTargets = Collections.unmodifiableList(targetRepository
.findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(Arrays.asList(controllerID)))); .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(Arrays.asList(controllerID))));
final TargetTag tag = Optional.ofNullable(targetTagRepository.findOne(targetTagId)).orElseThrow( final TargetTag tag = targetTagRepository.findById(targetTagId)
() -> new EntityNotFoundException("TargetTag with given ID " + targetTagId + " does not exist.")); .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId));
final List<Target> unAssignTag = unAssignTag(allTargets, tag); final List<Target> unAssignTag = unAssignTag(allTargets, tag);
return unAssignTag.isEmpty() ? null : unAssignTag.get(0); return unAssignTag.isEmpty() ? null : unAssignTag.get(0);
@@ -438,7 +466,6 @@ public class JpaTargetManagement implements TargetManagement {
@Override @Override
public Slice<Target> findTargetsAllOrderByLinkedDistributionSet(final Pageable pageable, public Slice<Target> findTargetsAllOrderByLinkedDistributionSet(final Pageable pageable,
final Long orderByDistributionId, final FilterParams filterParams) { final Long orderByDistributionId, final FilterParams filterParams) {
final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<JpaTarget> query = cb.createQuery(JpaTarget.class); final CriteriaQuery<JpaTarget> query = cb.createQuery(JpaTarget.class);
final Root<JpaTarget> targetRoot = query.from(JpaTarget.class); final Root<JpaTarget> targetRoot = query.from(JpaTarget.class);
@@ -496,17 +523,22 @@ public class JpaTargetManagement implements TargetManagement {
@Override @Override
public Long countTargetByAssignedDistributionSet(final Long distId) { public Long countTargetByAssignedDistributionSet(final Long distId) {
throwEntityNotFoundIfDsDoesNotExist(distId);
return targetRepository.countByAssignedDistributionSetId(distId); return targetRepository.countByAssignedDistributionSetId(distId);
} }
@Override @Override
public Long countTargetByInstalledDistributionSet(final Long distId) { public Long countTargetByInstalledDistributionSet(final Long distId) {
throwEntityNotFoundIfDsDoesNotExist(distId);
return targetRepository.countByTargetInfoInstalledDistributionSetId(distId); return targetRepository.countByTargetInfoInstalledDistributionSetId(distId);
} }
@Override @Override
public Page<Target> findAllTargetsByTargetFilterQueryAndNonDS(@NotNull final Pageable pageRequest, public Page<Target> findAllTargetsByTargetFilterQueryAndNonDS(final Pageable pageRequest,
final Long distributionSetId, @NotNull final String targetFilterQuery) { final Long distributionSetId, final String targetFilterQuery) {
throwEntityNotFoundIfDsDoesNotExist(distributionSetId);
final Specification<JpaTarget> spec = RSQLUtility.parse(targetFilterQuery, TargetFields.class, final Specification<JpaTarget> spec = RSQLUtility.parse(targetFilterQuery, TargetFields.class,
virtualPropertyReplacer); virtualPropertyReplacer);
@@ -534,6 +566,10 @@ public class JpaTargetManagement implements TargetManagement {
@Override @Override
public Page<Target> findAllTargetsInRolloutGroupWithoutAction(@NotNull final Pageable pageRequest, public Page<Target> findAllTargetsInRolloutGroupWithoutAction(@NotNull final Pageable pageRequest,
@NotNull final Long group) { @NotNull final Long group) {
if (!rolloutGroupRepository.exists(group)) {
throw new EntityNotFoundException(RolloutGroup.class, group);
}
return findTargetsBySpec( return findTargetsBySpec(
(root, cq, cb) -> TargetSpecifications.hasNoActionInRolloutGroup(group).toPredicate(root, cq, cb), (root, cq, cb) -> TargetSpecifications.hasNoActionInRolloutGroup(group).toPredicate(root, cq, cb),
pageRequest); pageRequest);
@@ -552,6 +588,8 @@ public class JpaTargetManagement implements TargetManagement {
@Override @Override
public Long countTargetsByTargetFilterQueryAndNonDS(final Long distributionSetId, final String targetFilterQuery) { public Long countTargetsByTargetFilterQueryAndNonDS(final Long distributionSetId, final String targetFilterQuery) {
throwEntityNotFoundIfDsDoesNotExist(distributionSetId);
final Specification<JpaTarget> spec = RSQLUtility.parse(targetFilterQuery, TargetFields.class, final Specification<JpaTarget> spec = RSQLUtility.parse(targetFilterQuery, TargetFields.class,
virtualPropertyReplacer); virtualPropertyReplacer);
final List<Specification<JpaTarget>> specList = new ArrayList<>(2); final List<Specification<JpaTarget>> specList = new ArrayList<>(2);
@@ -569,7 +607,7 @@ public class JpaTargetManagement implements TargetManagement {
final JpaTarget target = create.build(); final JpaTarget target = create.build();
if (targetRepository.findByControllerId(target.getControllerId()) != null) { if (targetRepository.findByControllerId(target.getControllerId()).isPresent()) {
throw new EntityAlreadyExistsException(); throw new EntityAlreadyExistsException();
} }
@@ -592,16 +630,18 @@ public class JpaTargetManagement implements TargetManagement {
@Override @Override
public List<Target> findTargetsByTag(final String tagName) { public List<Target> findTargetsByTag(final String tagName) {
final JpaTargetTag tag = targetTagRepository.findByNameEquals(tagName); final Optional<TargetTag> tag = targetTagRepository.findByNameEquals(tagName);
return Collections.unmodifiableList(targetRepository.findByTag(tag.getId())); if (!tag.isPresent()) {
return Collections.emptyList();
}
return Collections.unmodifiableList(targetRepository.findByTag(tag.get().getId()));
} }
@Override @Override
public Long countTargetByTargetFilterQuery(final Long targetFilterQueryId) { public Long countTargetByTargetFilterQuery(final Long targetFilterQueryId) {
final TargetFilterQuery targetFilterQuery = Optional final TargetFilterQuery targetFilterQuery = targetFilterQueryRepository.findById(targetFilterQueryId)
.ofNullable(targetFilterQueryRepository.findOne(targetFilterQueryId)) .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, targetFilterQueryId));
.orElseThrow(() -> new EntityNotFoundException(
"TargetFilterQuery with given ID" + targetFilterQueryId + " not found"));
final Specification<JpaTarget> specs = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class, final Specification<JpaTarget> specs = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class,
virtualPropertyReplacer); virtualPropertyReplacer);
@@ -619,8 +659,8 @@ public class JpaTargetManagement implements TargetManagement {
} }
@Override @Override
public Target findTargetById(final Long id) { public Optional<Target> findTargetById(final Long id) {
return targetRepository.findOne(id); return Optional.ofNullable(targetRepository.findOne(id));
} }
@Override @Override

View File

@@ -61,7 +61,7 @@ public interface LocalArtifactRepository extends BaseEntityRepository<JpaArtifac
* to search * to search
* @return {@link Artifact} the first in the result list * @return {@link Artifact} the first in the result list
*/ */
JpaArtifact findFirstBySha1Hash(String sha1Hash); Optional<Artifact> findFirstBySha1Hash(String sha1Hash);
/** /**
* Searches for a {@link Artifact} based user provided filename at upload. * Searches for a {@link Artifact} based user provided filename at upload.
@@ -70,7 +70,7 @@ public interface LocalArtifactRepository extends BaseEntityRepository<JpaArtifac
* to search * to search
* @return list of {@link Artifact}. * @return list of {@link Artifact}.
*/ */
List<Artifact> findByFilename(String filename); Optional<Artifact> findFirstByFilename(String filename);
/** /**
* Searches for local artifact for a base software module. * Searches for local artifact for a base software module.
@@ -94,6 +94,6 @@ public interface LocalArtifactRepository extends BaseEntityRepository<JpaArtifac
* selected software module id * selected software module id
* @return list of {@link Artifact}. * @return list of {@link Artifact}.
*/ */
List<Artifact> findByFilenameAndSoftwareModuleId(final String filename, final Long softwareModuleId); Optional<Artifact> findFirstByFilenameAndSoftwareModuleId(final String filename, final Long softwareModuleId);
} }

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; import org.eclipse.hawkbit.repository.jpa.model.JpaRollout;
import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.Rollout;
@@ -67,5 +68,5 @@ public interface RolloutRepository
* the rollout name * the rollout name
* @return {@link Rollout} for specific name * @return {@link Rollout} for specific name
*/ */
JpaRollout findByName(String name); Optional<Rollout> findByName(String name);
} }

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
@@ -55,7 +56,7 @@ public interface SoftwareModuleRepository
* @return the found {@link SoftwareModule} with the given name AND version * @return the found {@link SoftwareModule} with the given name AND version
* AND type * AND type
*/ */
JpaSoftwareModule findOneByNameAndVersionAndTypeId(String name, String version, Long typeId); Optional<SoftwareModule> findOneByNameAndVersionAndTypeId(String name, String version, Long typeId);
/** /**
* deletes the {@link SoftwareModule}s with the given IDs. * deletes the {@link SoftwareModule}s with the given IDs.

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -52,7 +53,7 @@ public interface SoftwareModuleTypeRepository
* @return all {@link SoftwareModuleType}s in the repository with given * @return all {@link SoftwareModuleType}s in the repository with given
* {@link SoftwareModuleType#getKey()} * {@link SoftwareModuleType#getKey()}
*/ */
JpaSoftwareModuleType findByKey(String key); Optional<SoftwareModuleType> findByKey(String key);
/** /**
* *
@@ -61,7 +62,7 @@ public interface SoftwareModuleTypeRepository
* @return all {@link SoftwareModuleType}s in the repository with given * @return all {@link SoftwareModuleType}s in the repository with given
* {@link SoftwareModuleType#getName()} * {@link SoftwareModuleType#getName()}
*/ */
JpaSoftwareModuleType findByName(String name); Optional<SoftwareModuleType> findByName(String name);
/** /**
* retrieves all software module types with a given * retrieves all software module types with a given

View File

@@ -8,6 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
@@ -32,7 +34,7 @@ public interface TargetFilterQueryRepository
* @param name * @param name
* @return custom target filter * @return custom target filter
*/ */
TargetFilterQuery findByName(final String name); Optional<TargetFilterQuery> findByName(final String name);
/** /**
* Find list of all custom target filters. * Find list of all custom target filters.

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository.jpa;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
@@ -44,7 +45,7 @@ public interface TargetRepository extends BaseEntityRepository<JpaTarget, Long>,
* @return found {@link Target} or <code>null</code> if not found. * @return found {@link Target} or <code>null</code> if not found.
*/ */
@EntityGraph(value = "Target.detail", type = EntityGraphType.LOAD) @EntityGraph(value = "Target.detail", type = EntityGraphType.LOAD)
JpaTarget findByControllerId(String controllerID); Optional<Target> findByControllerId(String controllerID);
/** /**
* Deletes the {@link Target}s with the given target IDs. * Deletes the {@link Target}s with the given target IDs.

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag;
import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetTag;
@@ -43,7 +44,7 @@ public interface TargetTagRepository
* to filter on * to filter on
* @return the {@link TargetTag} if found, otherwise null * @return the {@link TargetTag} if found, otherwise null
*/ */
JpaTargetTag findByNameEquals(String tagName); Optional<TargetTag> findByNameEquals(String tagName);
/** /**
* Returns all instances of the type. * Returns all instances of the type.

View File

@@ -47,14 +47,8 @@ public class JpaDistributionSetCreate extends AbstractDistributionSetUpdateCreat
} }
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) { private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) {
return distributionSetManagement.findDistributionSetTypeByKey(distributionSetTypekey)
final DistributionSetType module = distributionSetManagement .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypekey));
.findDistributionSetTypeByKey(distributionSetTypekey);
if (module == null) {
throw new EntityNotFoundException(
"DistributionSetType with key {" + distributionSetTypekey + "} does not exist");
}
return module;
} }
private Collection<SoftwareModule> findSoftwareModuleWithExceptionIfNotFound( private Collection<SoftwareModule> findSoftwareModuleWithExceptionIfNotFound(
@@ -65,8 +59,7 @@ public class JpaDistributionSetCreate extends AbstractDistributionSetUpdateCreat
final Collection<SoftwareModule> module = softwareManagement.findSoftwareModulesById(softwareModuleId); final Collection<SoftwareModule> module = softwareManagement.findSoftwareModulesById(softwareModuleId);
if (module.size() < softwareModuleId.size()) { if (module.size() < softwareModuleId.size()) {
throw new EntityNotFoundException( throw new EntityNotFoundException(SoftwareModule.class, softwareModuleId);
"Some SoftwareModules out of the range {" + softwareModuleId + "} due not exist");
} }
return module; return module;

View File

@@ -51,8 +51,7 @@ public class JpaDistributionSetTypeCreate extends AbstractDistributionSetTypeUpd
final Collection<SoftwareModuleType> module = softwareManagement final Collection<SoftwareModuleType> module = softwareManagement
.findSoftwareModuleTypesById(softwareModuleTypeId); .findSoftwareModuleTypesById(softwareModuleTypeId);
if (module.size() < softwareModuleTypeId.size()) { if (module.size() < softwareModuleTypeId.size()) {
throw new EntityNotFoundException( throw new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId);
"SoftwareModules types out of the range {" + softwareModuleTypeId + "} due not exist");
} }
return module; return module;

Some files were not shown because too many files have changed in this diff Show More