Split repository API for module and DS management. Refactor utility usage (#524)

* Split DS management and reduce util usage.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Split sw module and type management.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Sonar issues.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Make sonar listen to the exception!

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Register both beans.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Split JPA implementations.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Revert user details change.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix compilation errors.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix bean queries. Fix image path.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Document preferred utility usage.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix exmaples and revert unintended checkin.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Code cleanup.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Typos, readibility.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Remove unused reference.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Rollouts cache delete aware.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix rolloutgroup delete event.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Add new RolloutGroupDeletedEvent event

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>
This commit is contained in:
Kai Zimmermann
2017-06-01 06:28:59 +02:00
committed by GitHub
parent 0ab995d1a4
commit 67a4677ef6
203 changed files with 2738 additions and 2320 deletions

View File

@@ -4,6 +4,7 @@
| Group ID | Artifact ID | Version | CQ |
|---|---|---|---|
|com.github.ben-manes.caffeine|caffeine|2.3.5| [CQ13563](https://dev.eclipse.org/ipzilla/show_bug.cgi?id=13563) |
|aopalliance|aopalliance|1.0| [CQ10346](https://dev.eclipse.org/ipzilla/show_bug.cgi?id=10346) |
|ch.qos.logback|logback-classic|1.1.3| [CQ10347](https://dev.eclipse.org/ipzilla/show_bug.cgi?id=10347) |
|ch.qos.logback|logback-core|1.1.3| [CQ12925](https://dev.eclipse.org/ipzilla/show_bug.cgi?id=12925) |

View File

@@ -21,6 +21,27 @@ Please read this if you intend to contribute to the project.
* Sonarqube:
* Our rule set can be found [here](https://sonar.ops.bosch-iot-rollouts.com/projects) with navigating to the tab "Quality Profiles", selecting "hawkBit", and then selecting "Actions" - "Back up"
### Utility library usage
hawkBit has currently both [guava](https://github.com/google/guava) and [Apache commons lang](https://commons.apache.org/proper/commons-lang/) on the classpath in several of its modules. However, we see introducing too many utility libraries problematic as we force these as transitive dependencies on hawkBit users. We in fact are looking into reducing them in future not adding new ones.
So we kindly ask contributors:
* not introduce extra utility library dependencies
* keep them out of the core modules (e.g. hawkbit-core, hawkbit-rest-core, hawkbit-http-security) to avoid that all modules have them as transitive dependency
* use utility functions in general based in the following priority:
* use utility functions from JDK if feasible
* use Spring utility classes if feasible
* use [guava](https://github.com/google/guava) if feasible
* use [Apache commons lang](https://commons.apache.org/proper/commons-lang/) if feasible
Note that the guava project for instance often documents where they think that JDK is having a similar functionality (e.g. their thoughts on [Throwables.propagate](https://github.com/google/guava/wiki/Why-we-deprecated-Throwables.propagate)).
Examples:
* Prefer `Arrays.asList(...)` from JDK over guava's `Lists.newArrayList(...)`
* Prefer `StringUtils` from Spring over guava's `Strings` Apache's `StringUtils`
### Test documentation
Please documented the test cases that you contribute by means of [Allure](http://allure.qatools.ru) annotations and proper test method naming.

View File

@@ -8,6 +8,7 @@
*/
package org.eclipse.hawkbit.simulator.amqp;
import java.util.Arrays;
import java.util.Map;
import org.eclipse.hawkbit.dmf.amqp.api.EventTopic;
@@ -27,8 +28,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
/**
* Handle all incoming Messages from hawkBit update server.
*
@@ -133,7 +132,7 @@ public class SpReceiverService extends ReceiverService {
final Long actionId = convertMessage(message, Long.class);
final SimulatedUpdate update = new SimulatedUpdate(tenant, thingId, actionId);
spSenderService.finishUpdateProcess(update, Lists.newArrayList("Simulation canceled"));
spSenderService.finishUpdateProcess(update, Arrays.asList("Simulation canceled"));
}
private void handleUpdateProcess(final Message message, final String thingId) {

View File

@@ -8,6 +8,7 @@
*/
package org.eclipse.hawkbit.simulator.ui;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
@@ -23,7 +24,6 @@ import org.eclipse.hawkbit.simulator.event.NextPollCounterUpdate;
import org.eclipse.hawkbit.simulator.event.ProgressUpdate;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.collect.Lists;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.vaadin.data.util.BeanContainer;
@@ -93,7 +93,7 @@ public class SimulatorView extends VerticalLayout implements View {
private final HorizontalLayout toolbar = new HorizontalLayout();
private final Grid grid = new Grid();
private final ComboBox responseComboBox = new ComboBox("",
Lists.newArrayList(ResponseStatus.SUCCESSFUL, ResponseStatus.ERROR));
Arrays.asList(ResponseStatus.SUCCESSFUL, ResponseStatus.ERROR));
private BeanContainer<String, AbstractSimulatedDevice> beanContainer;

View File

@@ -9,13 +9,12 @@
package org.eclipse.hawkbit.mgmt.client.resource.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment;
import com.google.common.collect.Lists;
/**
* Builder pattern for building {@link MgmtDistributionSetRequestBodyPost}.
*/
@@ -84,7 +83,7 @@ public class DistributionSetBuilder {
* @return a single entry list of {@link MgmtDistributionSetRequestBodyPost}
*/
public List<MgmtDistributionSetRequestBodyPost> build() {
return Lists.newArrayList(doBuild(""));
return Arrays.asList(doBuild(""));
}
/**
@@ -114,7 +113,7 @@ public class DistributionSetBuilder {
* @return a list of {@link MgmtDistributionSetRequestBodyPost}
*/
public List<MgmtDistributionSetRequestBodyPost> buildAsList(final int offset, final int count) {
final ArrayList<MgmtDistributionSetRequestBodyPost> bodyList = Lists.newArrayList();
final List<MgmtDistributionSetRequestBodyPost> bodyList = new ArrayList<>();
for (int index = offset; index < count + offset; index++) {
bodyList.add(doBuild(String.valueOf(index)));
}

View File

@@ -9,13 +9,12 @@
package org.eclipse.hawkbit.mgmt.client.resource.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeAssigment;
import com.google.common.collect.Lists;
/**
*
* Builder pattern for building {@link MgmtDistributionSetTypeRequestBodyPost}.
@@ -28,8 +27,8 @@ public class DistributionSetTypeBuilder {
private String key;
private String name;
private String description;
private final List<MgmtSoftwareModuleTypeAssigment> mandatorymodules = Lists.newArrayList();
private final List<MgmtSoftwareModuleTypeAssigment> optionalmodules = Lists.newArrayList();
private final List<MgmtSoftwareModuleTypeAssigment> mandatorymodules = new ArrayList<>();
private final List<MgmtSoftwareModuleTypeAssigment> optionalmodules = new ArrayList<>();
/**
* @param key
@@ -101,7 +100,7 @@ public class DistributionSetTypeBuilder {
* {@link MgmtDistributionSetTypeRequestBodyPost}
*/
public List<MgmtDistributionSetTypeRequestBodyPost> build() {
return Lists.newArrayList(doBuild(""));
return Arrays.asList(doBuild(""));
}
/**
@@ -116,7 +115,7 @@ public class DistributionSetTypeBuilder {
* @return a list of {@link MgmtDistributionSetTypeRequestBodyPost}
*/
public List<MgmtDistributionSetTypeRequestBodyPost> buildAsList(final int count) {
final ArrayList<MgmtDistributionSetTypeRequestBodyPost> bodyList = Lists.newArrayList();
final List<MgmtDistributionSetTypeRequestBodyPost> bodyList = new ArrayList<>();
for (int index = 0; index < count; index++) {
bodyList.add(doBuild(String.valueOf(index)));
}

View File

@@ -9,13 +9,12 @@
package org.eclipse.hawkbit.mgmt.client.resource.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost;
import com.google.common.collect.Lists;
/**
*
* Builder pattern for building {@link MgmtSoftwareModuleRequestBodyPost}.
@@ -90,7 +89,7 @@ public class SoftwareModuleBuilder {
* @return a single entry list of {@link MgmtSoftwareModuleRequestBodyPost}
*/
public List<MgmtSoftwareModuleRequestBodyPost> build() {
return Lists.newArrayList(doBuild(""));
return Arrays.asList(doBuild(""));
}
/**
@@ -104,7 +103,7 @@ public class SoftwareModuleBuilder {
* @return a list of {@link MgmtDistributionSetTypeRequestBodyPost}
*/
public List<MgmtSoftwareModuleRequestBodyPost> buildAsList(final int count) {
final ArrayList<MgmtSoftwareModuleRequestBodyPost> bodyList = Lists.newArrayList();
final List<MgmtSoftwareModuleRequestBodyPost> bodyList = new ArrayList<>();
for (int index = 0; index < count; index++) {
bodyList.add(doBuild(String.valueOf(index)));
}

View File

@@ -9,13 +9,12 @@
package org.eclipse.hawkbit.mgmt.client.resource.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost;
import com.google.common.collect.Lists;
/**
*
* Builder pattern for building {@link MgmtSoftwareModuleRequestBodyPost}.
@@ -79,7 +78,7 @@ public class SoftwareModuleTypeBuilder {
* {@link MgmtSoftwareModuleTypeRequestBodyPost}
*/
public List<MgmtSoftwareModuleTypeRequestBodyPost> build() {
return Lists.newArrayList(doBuild(""));
return Arrays.asList(doBuild(""));
}
/**
@@ -93,7 +92,7 @@ public class SoftwareModuleTypeBuilder {
* @return a list of {@link MgmtSoftwareModuleTypeRequestBodyPost}
*/
public List<MgmtSoftwareModuleTypeRequestBodyPost> buildAsList(final int count) {
final ArrayList<MgmtSoftwareModuleTypeRequestBodyPost> bodyList = Lists.newArrayList();
final List<MgmtSoftwareModuleTypeRequestBodyPost> bodyList = new ArrayList<>();
for (int index = 0; index < count; index++) {
bodyList.add(doBuild(String.valueOf(index)));
}

View File

@@ -9,12 +9,11 @@
package org.eclipse.hawkbit.mgmt.client.resource.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut;
import com.google.common.collect.Lists;
/**
* Builder pattern for building {@link MgmtTagRequestBodyPut}.
*
@@ -64,7 +63,7 @@ public class TagBuilder {
* @return a single entry list of {@link MgmtTagRequestBodyPut}
*/
public List<MgmtTagRequestBodyPut> build() {
return Lists.newArrayList(doBuild(name));
return Arrays.asList(doBuild(name));
}
/**
@@ -77,7 +76,7 @@ public class TagBuilder {
* @return a list of {@link MgmtTagRequestBodyPut}
*/
public List<MgmtTagRequestBodyPut> buildAsList(final int count) {
final ArrayList<MgmtTagRequestBodyPut> bodyList = Lists.newArrayList();
final List<MgmtTagRequestBodyPut> bodyList = new ArrayList<>();
for (int index = 0; index < count; index++) {
bodyList.add(doBuild(name + index));
}

View File

@@ -8,13 +8,13 @@
*/
package org.eclipse.hawkbit.mgmt.client.resource.builder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody;
import com.google.common.collect.Lists;
/**
*
* Builder pattern for building {@link MgmtTargetRequestBody}.
@@ -76,7 +76,7 @@ public class TargetBuilder {
* @return a single entry list of {@link MgmtTargetRequestBody}
*/
public List<MgmtTargetRequestBody> build() {
return Lists.newArrayList(doBuild(""));
return Arrays.asList(doBuild(""));
}
/**
@@ -106,7 +106,7 @@ public class TargetBuilder {
* @return a list of {@link MgmtSoftwareModuleTypeRequestBodyPost}
*/
public List<MgmtTargetRequestBody> buildAsList(final int offset, final int count) {
final List<MgmtTargetRequestBody> bodyList = Lists.newArrayList();
final List<MgmtTargetRequestBody> bodyList = new ArrayList<>();
for (int index = offset; index < count + offset; index++) {
bodyList.add(doBuild(String.format("%06d", index)));
}

View File

@@ -53,6 +53,10 @@
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

View File

@@ -77,6 +77,10 @@
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>

View File

@@ -102,25 +102,11 @@ public class CacheAutoConfiguration {
*/
public class TenantCacheResolver extends SimpleCacheResolver {
/*
* (non-Javadoc)
*
* @see org.springframework.cache.interceptor.AbstractCacheResolver#
* resolveCaches(org.springframework
* .cache.interceptor.CacheOperationInvocationContext)
*/
@Override
public Collection<Cache> resolveCaches(final CacheOperationInvocationContext<?> context) {
return super.resolveCaches(context).stream().map(TenantCacheWrapper::new).collect(Collectors.toList());
}
/*
* (non-Javadoc)
*
* @see org.springframework.cache.interceptor.SimpleCacheResolver#
* getCacheNames(org.springframework
* .cache.interceptor.CacheOperationInvocationContext)
*/
@Override
protected Collection<String> getCacheNames(final CacheOperationInvocationContext<?> context) {
return super.getCacheNames(context).stream()

View File

@@ -87,8 +87,6 @@ import org.vaadin.spring.security.web.VaadinRedirectStrategy;
import org.vaadin.spring.security.web.authentication.VaadinAuthenticationSuccessHandler;
import org.vaadin.spring.security.web.authentication.VaadinUrlAuthenticationSuccessHandler;
import com.google.common.collect.Lists;
/**
* All configurations related to HawkBit's authentication and authorization
* layer.
@@ -223,7 +221,7 @@ public class SecurityManagedConfiguration {
final AnonymousAuthenticationFilter anoymousFilter = new AnonymousAuthenticationFilter(
"controllerAnonymousFilter", "anonymous",
Lists.newArrayList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS),
Arrays.asList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS),
new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_DOWNLOAD_ROLE)));
anoymousFilter.setAuthenticationDetailsSource(authenticationDetailsSource);
httpSec.requestMatchers().antMatchers("/*/controller/v1/**", "/*/controller/artifacts/v1/**").and()

View File

@@ -28,10 +28,7 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@@ -8,6 +8,7 @@
*/
package org.eclipse.hawkbit.api;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -15,8 +16,6 @@ import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import com.google.common.collect.Lists;
/**
* Artifact handler properties class for holding all supported protocols with
* host, ip, port and download pattern.
@@ -85,7 +84,7 @@ public class ArtifactUrlHandlerProperties {
/**
* Support for the following hawkBit API.
*/
private List<ApiType> supports = Lists.newArrayList(ApiType.DDI, ApiType.DMF);
private List<ApiType> supports = Arrays.asList(ApiType.DDI, ApiType.DMF);
public boolean isEnabled() {
return enabled;

View File

@@ -8,7 +8,12 @@
*/
package org.eclipse.hawkbit.api;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@@ -17,12 +22,9 @@ import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.api.ArtifactUrlHandlerProperties.UrlProtocol;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.net.UrlEscapers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
* Implementation for ArtifactUrlHandler for creating urls to download resource
@@ -43,6 +45,8 @@ import com.google.common.net.UrlEscapers;
*/
public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler {
private static final Logger LOG = LoggerFactory.getLogger(PropertyBasedArtifactUrlHandler.class);
private static final String PROTOCOL_PLACEHOLDER = "protocol";
private static final String CONTROLLER_ID_PLACEHOLDER = "controllerId";
private static final String TARGET_ID_BASE10_PLACEHOLDER = "targetId";
@@ -99,7 +103,7 @@ public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler {
for (final Entry<String, String> entry : entrySet) {
if (entry.getKey().equals(PORT_PLACEHOLDER)) {
urlPattern = urlPattern.replace(":{" + entry.getKey() + "}",
Strings.isNullOrEmpty(entry.getValue()) ? "" : (":" + entry.getValue()));
StringUtils.isEmpty(entry.getValue()) ? "" : (":" + entry.getValue()));
} else {
urlPattern = urlPattern.replace("{" + entry.getKey() + "}", entry.getValue());
}
@@ -109,7 +113,7 @@ public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler {
private static Map<String, String> getReplaceMap(final UrlProtocol protocol, final URLPlaceholder placeholder,
final URI requestUri) {
final Map<String, String> replaceMap = Maps.newHashMapWithExpectedSize(19);
final Map<String, String> replaceMap = new HashMap<>();
replaceMap.put(IP_PLACEHOLDER, protocol.getIp());
replaceMap.put(HOSTNAME_PLACEHOLDER, protocol.getHostname());
@@ -117,8 +121,13 @@ public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler {
replaceMap.put(PORT_REQUEST_PLACEHOLDER, getRequestPort(protocol, requestUri));
replaceMap.put(HOSTNAME_WITH_DOMAIN_REQUEST_PLACEHOLDER, computeHostWithRequestDomain(protocol, requestUri));
try {
replaceMap.put(ARTIFACT_FILENAME_PLACEHOLDER,
UrlEscapers.urlFragmentEscaper().escape(placeholder.getSoftwareData().getFilename()));
URLEncoder.encode(placeholder.getSoftwareData().getFilename(), StandardCharsets.UTF_8.toString()));
} catch (final UnsupportedEncodingException e) {
LOG.error("Could not encode {}", placeholder.getSoftwareData().getFilename(), e);
}
replaceMap.put(ARTIFACT_SHA1_PLACEHOLDER, placeholder.getSoftwareData().getSha1Hash());
replaceMap.put(PROTOCOL_PLACEHOLDER, protocol.getProtocol());
replaceMap.put(PORT_PLACEHOLDER, getPort(protocol));
@@ -168,14 +177,14 @@ public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler {
return protocol.getHostname();
}
final String host = Splitter.on('.').trimResults().omitEmptyStrings().splitToList(protocol.getHostname())
.get(0);
final String host = StringUtils.delimitedListToStringArray(protocol.getHostname(), ".")[0].trim();
final List<String> domainElements = Splitter.on('.').trimResults().omitEmptyStrings()
.splitToList(requestUri.getHost());
final String domain = Joiner.on(".").join(domainElements.subList(1, domainElements.size()));
final List<String> domainElements = Arrays
.asList(StringUtils.delimitedListToStringArray(requestUri.getHost(), "."));
final String domain = StringUtils.collectionToDelimitedString(domainElements.subList(1, domainElements.size()),
".");
if (Strings.isNullOrEmpty(domain)) {
if (StringUtils.isEmpty(domain)) {
return protocol.getHostname();
}

View File

@@ -8,8 +8,8 @@
*/
package org.eclipse.hawkbit.tenancy.configuration;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/**
* The {@link #InvalidTenantConfigurationKeyException} is thrown when an invalid

View File

@@ -8,8 +8,8 @@
*/
package org.eclipse.hawkbit.tenancy.configuration.validator;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/**
* Exception which is thrown, when the validation of the configuration value has

View File

@@ -9,10 +9,10 @@
package org.eclipse.hawkbit.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import org.eclipse.hawkbit.api.ArtifactUrlHandlerProperties.UrlProtocol;
@@ -22,8 +22,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.common.collect.Lists;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@@ -41,7 +39,8 @@ public class PropertyBasedArtifactUrlHandlerTest {
private static final long TENANT_ID = 456789L;
private static final String CONTROLLER_ID = "Test";
private static final String FILENAME = "Afile1234";
private static final String FILENAME_DECODE = "test123!§$%&";
private static final String FILENAME_ENCODE = "test123%21%C2%A7%24%25%26";
private static final long SOFTWAREMODULEID = 87654L;
private static final long TARGETID = 3474366L;
private static final String TARGETID_BASE62 = "EZqA";
@@ -57,7 +56,7 @@ public class PropertyBasedArtifactUrlHandlerTest {
private ArtifactUrlHandlerProperties properties;
private static URLPlaceholder placeholder = new URLPlaceholder(TENANT, TENANT_ID, CONTROLLER_ID, TARGETID,
new SoftwareData(SOFTWAREMODULEID, FILENAME, ARTIFACTID, SHA1HASH));
new SoftwareData(SOFTWAREMODULEID, FILENAME_DECODE, ARTIFACTID, SHA1HASH));
@Before
public void setup() {
@@ -72,13 +71,12 @@ public class PropertyBasedArtifactUrlHandlerTest {
properties.getProtocols().put("download-http", new UrlProtocol());
final List<ArtifactUrl> ddiUrls = urlHandlerUnderTest.getUrls(placeholder, ApiType.DDI);
assertEquals(Lists.newArrayList(
assertThat(ddiUrls).containsExactly(
new ArtifactUrl("http".toUpperCase(), "download-http", HTTP_LOCALHOST + TENANT + "/controller/v1/"
+ CONTROLLER_ID + "/softwaremodules/" + SOFTWAREMODULEID + "/artifacts/" + FILENAME)),
ddiUrls);
+ CONTROLLER_ID + "/softwaremodules/" + SOFTWAREMODULEID + "/artifacts/" + FILENAME_ENCODE));
final List<ArtifactUrl> dmfUrls = urlHandlerUnderTest.getUrls(placeholder, ApiType.DMF);
assertEquals(ddiUrls, dmfUrls);
assertThat(ddiUrls).isEqualTo(dmfUrls);
}
@Test
@@ -89,7 +87,7 @@ public class PropertyBasedArtifactUrlHandlerTest {
proto.setPort(5683);
proto.setProtocol(TEST_PROTO);
proto.setRel(TEST_REL);
proto.setSupports(Lists.newArrayList(ApiType.DMF));
proto.setSupports(Arrays.asList(ApiType.DMF));
proto.setRef("{protocol}://{ip}:{port}/fw/{tenant}/{controllerId}/sha1/{artifactSHA1}");
properties.getProtocols().put(TEST_PROTO, proto);
@@ -98,8 +96,8 @@ public class PropertyBasedArtifactUrlHandlerTest {
assertThat(urls).isEmpty();
urls = urlHandlerUnderTest.getUrls(placeholder, ApiType.DMF);
assertEquals(Lists.newArrayList(new ArtifactUrl(TEST_PROTO.toUpperCase(), TEST_REL,
"coap://127.0.0.1:5683/fw/" + TENANT + "/" + CONTROLLER_ID + "/sha1/" + SHA1HASH)), urls);
assertThat(urls).containsExactly(new ArtifactUrl(TEST_PROTO.toUpperCase(), TEST_REL,
"coap://127.0.0.1:5683/fw/" + TENANT + "/" + CONTROLLER_ID + "/sha1/" + SHA1HASH));
}
@Test
@@ -110,7 +108,7 @@ public class PropertyBasedArtifactUrlHandlerTest {
proto.setPort(5683);
proto.setProtocol(TEST_PROTO);
proto.setRel(TEST_REL);
proto.setSupports(Lists.newArrayList(ApiType.DMF));
proto.setSupports(Arrays.asList(ApiType.DMF));
proto.setRef("{protocol}://{ip}:{port}/fws/{tenant}/{targetIdBase62}/{artifactIdBase62}");
properties.getProtocols().put("ftp", proto);
@@ -119,9 +117,8 @@ public class PropertyBasedArtifactUrlHandlerTest {
assertThat(urls).isEmpty();
urls = urlHandlerUnderTest.getUrls(placeholder, ApiType.DMF);
assertEquals(Lists.newArrayList(new ArtifactUrl(TEST_PROTO.toUpperCase(), TEST_REL,
TEST_PROTO + "://127.0.0.1:5683/fws/" + TENANT + "/" + TARGETID_BASE62 + "/" + ARTIFACTID_BASE62)),
urls);
assertThat(urls).containsExactly(new ArtifactUrl(TEST_PROTO.toUpperCase(), TEST_REL,
TEST_PROTO + "://127.0.0.1:5683/fws/" + TENANT + "/" + TARGETID_BASE62 + "/" + ARTIFACTID_BASE62));
}
@Test
@@ -134,15 +131,15 @@ public class PropertyBasedArtifactUrlHandlerTest {
proto.setPort(5683);
proto.setProtocol(TEST_PROTO);
proto.setRel(TEST_REL);
proto.setSupports(Lists.newArrayList(ApiType.DDI));
proto.setSupports(Arrays.asList(ApiType.DDI));
proto.setRef("{protocol}://{hostnameRequest}:{port}/fws/{tenant}/{targetIdBase62}/{artifactIdBase62}");
properties.getProtocols().put("ftp", proto);
final List<ArtifactUrl> urls = urlHandlerUnderTest.getUrls(placeholder, ApiType.DDI,
new URI("https://" + testHost));
assertEquals(Lists.newArrayList(new ArtifactUrl(TEST_PROTO.toUpperCase(), TEST_REL, TEST_PROTO + "://"
+ testHost + ":5683/fws/" + TENANT + "/" + TARGETID_BASE62 + "/" + ARTIFACTID_BASE62)), urls);
assertThat(urls).containsExactly(new ArtifactUrl(TEST_PROTO.toUpperCase(), TEST_REL, TEST_PROTO + "://"
+ testHost + ":5683/fws/" + TENANT + "/" + TARGETID_BASE62 + "/" + ARTIFACTID_BASE62));
}
@Test
@@ -156,16 +153,16 @@ public class PropertyBasedArtifactUrlHandlerTest {
final List<ArtifactUrl> ddiUrls = urlHandlerUnderTest.getUrls(placeholder, ApiType.DDI,
new URI("http://anotherHost.com:8083"));
assertEquals(Lists.newArrayList(new ArtifactUrl("http".toUpperCase(), "download-http",
assertThat(ddiUrls).containsExactly(new ArtifactUrl("http".toUpperCase(), "download-http",
"http://localhost:8083/" + TENANT + "/controller/v1/" + CONTROLLER_ID + "/softwaremodules/"
+ SOFTWAREMODULEID + "/artifacts/" + FILENAME)),
ddiUrls);
+ SOFTWAREMODULEID + "/artifacts/" + FILENAME_ENCODE));
final List<ArtifactUrl> dmfUrls = urlHandlerUnderTest.getUrls(placeholder, ApiType.DMF);
assertEquals(Lists.newArrayList(new ArtifactUrl("http".toUpperCase(), "download-http",
assertThat(dmfUrls).containsExactly(new ArtifactUrl("http".toUpperCase(), "download-http",
"http://localhost:8080/" + TENANT + "/controller/v1/" + CONTROLLER_ID + "/softwaremodules/"
+ SOFTWAREMODULEID + "/artifacts/" + FILENAME)),
dmfUrls);
+ SOFTWAREMODULEID + "/artifacts/" + FILENAME_ENCODE));
}
@Test
@@ -180,15 +177,14 @@ public class PropertyBasedArtifactUrlHandlerTest {
final List<ArtifactUrl> ddiUrls = urlHandlerUnderTest.getUrls(placeholder, ApiType.DDI,
new URI("http://anotherHost.com:8083"));
assertEquals(Lists.newArrayList(
assertThat(ddiUrls).containsExactly(
new ArtifactUrl("http".toUpperCase(), "download-http", "http://host.com/" + TENANT + "/controller/v1/"
+ CONTROLLER_ID + "/softwaremodules/" + SOFTWAREMODULEID + "/artifacts/" + FILENAME)),
ddiUrls);
+ CONTROLLER_ID + "/softwaremodules/" + SOFTWAREMODULEID + "/artifacts/" + FILENAME_ENCODE));
final List<ArtifactUrl> dmfUrls = urlHandlerUnderTest.getUrls(placeholder, ApiType.DMF);
assertEquals(Lists.newArrayList(new ArtifactUrl("http".toUpperCase(), "download-http",
assertThat(dmfUrls).containsExactly(new ArtifactUrl("http".toUpperCase(), "download-http",
"http://host.bumlux.net/" + TENANT + "/controller/v1/" + CONTROLLER_ID + "/softwaremodules/"
+ SOFTWAREMODULEID + "/artifacts/" + FILENAME)),
dmfUrls);
+ SOFTWAREMODULEID + "/artifacts/" + FILENAME_ENCODE));
}
}

View File

@@ -40,6 +40,10 @@
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>

View File

@@ -33,7 +33,7 @@ import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.builder.ActionStatusCreate;
import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNotFoundException;
@@ -82,7 +82,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
private ControllerManagement controllerManagement;
@Autowired
private SoftwareManagement softwareManagement;
private SoftwareModuleManagement softwareModuleManagement;
@Autowired
private ArtifactManagement artifactManagement;
@@ -114,7 +114,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
final Target target = controllerManagement.findByControllerId(controllerId)
.orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(softwareModuleId)
final SoftwareModule softwareModule = softwareModuleManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
return new ResponseEntity<>(
@@ -144,7 +144,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
final Target target = controllerManagement.findByControllerId(controllerId)
.orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
final SoftwareModule module = softwareModuleManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (checkModule(fileName, module)) {
@@ -208,7 +208,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
controllerManagement.findByControllerId(controllerId)
.orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
final SoftwareModule module = softwareModuleManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (checkModule(fileName, module)) {

View File

@@ -46,7 +46,6 @@ import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;
import ru.yandex.qatools.allure.annotations.Description;
@@ -78,7 +77,7 @@ public class DdiArtifactDownloadTest extends AbstractDDiApiIntegrationTest {
public void invalidRequestsOnArtifactResource() throws Exception {
// create target
final Target target = testdataFactory.createTarget();
final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = Arrays.asList(target);
// create ds
final DistributionSet ds = testdataFactory.createDistributionSet("");
@@ -161,11 +160,11 @@ public class DdiArtifactDownloadTest extends AbstractDDiApiIntegrationTest {
public void downloadArtifactThroughFileName() throws Exception {
downLoadProgress = 1;
shippedBytes = 0;
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
// create target
final Target target = testdataFactory.createTarget();
final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = Arrays.asList(target);
// create ds
final DistributionSet ds = testdataFactory.createDistributionSet("");
@@ -224,8 +223,8 @@ public class DdiArtifactDownloadTest extends AbstractDDiApiIntegrationTest {
"attachment;filename=" + artifact.getFilename() + ".MD5SUM"))
.andReturn();
assertThat(result.getResponse().getContentAsByteArray()).isEqualTo(
new String(artifact.getMd5Hash() + " " + artifact.getFilename()).getBytes(Charsets.US_ASCII));
assertThat(result.getResponse().getContentAsByteArray())
.isEqualTo((artifact.getMd5Hash() + " " + artifact.getFilename()).getBytes(Charsets.US_ASCII));
}
@Test
@@ -234,7 +233,7 @@ public class DdiArtifactDownloadTest extends AbstractDDiApiIntegrationTest {
public void rangeDownloadArtifact() throws Exception {
// create target
final Target target = testdataFactory.createTarget();
final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = Arrays.asList(target);
// create ds
final DistributionSet ds = testdataFactory.createDistributionSet("");

View File

@@ -23,6 +23,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
@@ -54,7 +55,6 @@ import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Description;
@@ -124,7 +124,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0);
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.FORCED,
RepositoryModelConstants.NO_FORCE_TIME, Lists.newArrayList(savedTarget.getControllerId()))
RepositoryModelConstants.NO_FORCE_TIME, Arrays.asList(savedTarget.getControllerId()))
.getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
@@ -232,8 +232,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(ds.getId(),
ActionType.TIMEFORCED, System.currentTimeMillis() + 1_000,
Lists.newArrayList(target.getControllerId()));
ActionType.TIMEFORCED, System.currentTimeMillis() + 1_000, Arrays.asList(target.getControllerId()));
final Action action = deploymentManagement
.findActiveActionsByTarget(PAGE, result.getAssignedEntity().get(0).getControllerId()).getContent()
@@ -286,7 +285,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0);
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.SOFT,
RepositoryModelConstants.NO_FORCE_TIME, Lists.newArrayList(savedTarget.getControllerId()))
RepositoryModelConstants.NO_FORCE_TIME, Arrays.asList(savedTarget.getControllerId()))
.getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
@@ -401,7 +400,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0);
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.TIMEFORCED,
System.currentTimeMillis(), Lists.newArrayList(savedTarget.getControllerId())).getAssignedEntity();
System.currentTimeMillis(), Arrays.asList(savedTarget.getControllerId())).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
@@ -657,8 +656,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
assertThat(targetManagement.findTargetByControllerID("4712").get().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN);
assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(PAGE, ds.getId()).getContent()
.get(0);
final Action action = deploymentManagement.findActionsByDistributionSet(PAGE, ds.getId()).getContent().get(0);
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
tenantAware.getCurrentTenant())
@@ -684,9 +682,9 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
// redo
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()).get();
assignDistributionSet(ds, Lists.newArrayList(targetManagement.findTargetByControllerID("4712").get()));
final Action action2 = deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())
.getContent().get(0);
assignDistributionSet(ds, Arrays.asList(targetManagement.findTargetByControllerID("4712").get()));
final Action action2 = deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId()).getContent()
.get(0);
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action2.getId() + "/feedback",
tenantAware.getCurrentTenant())
@@ -719,13 +717,12 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget("4712");
final List<Target> toAssign = Lists.newArrayList(savedTarget);
final List<Target> toAssign = Arrays.asList(savedTarget);
Target myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(PAGE, ds.getId()).getContent()
.get(0);
final Action action = deploymentManagement.findActionsByDistributionSet(PAGE, ds.getId()).getContent().get(0);
myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
@@ -875,14 +872,14 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
final List<Target> toAssign = Lists.newArrayList(savedTarget);
final List<Target> toAssign2 = Lists.newArrayList(savedTarget2);
final List<Target> toAssign = Arrays.asList(savedTarget);
final List<Target> toAssign2 = Arrays.asList(savedTarget2);
savedTarget = assignDistributionSet(savedSet, toAssign).getAssignedEntity().iterator().next();
assignDistributionSet(savedSet2, toAssign2);
final Action updateAction = deploymentManagement
.findActiveActionsByTarget(PAGE, savedTarget.getControllerId()).getContent().get(0);
final Action updateAction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
// action exists but is not assigned to this target
mvc.perform(post("/{tenant}/controller/v1/4713/deploymentBase/" + updateAction.getId() + "/feedback",

View File

@@ -13,6 +13,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.List;
import org.eclipse.hawkbit.repository.model.Action;
@@ -25,7 +26,6 @@ import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;
import ru.yandex.qatools.allure.annotations.Description;
@@ -147,7 +147,7 @@ public class DosFilterTest extends AbstractDDiApiIntegrationTest {
private Long prepareDeploymentBase() {
final DistributionSet ds = testdataFactory.createDistributionSet("test");
final Target target = testdataFactory.createTarget("4711");
final List<Target> toAssign = Lists.newArrayList(target);
final List<Target> toAssign = Arrays.asList(target);
final Iterable<Target> saved = assignDistributionSet(ds, toAssign).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, target.getControllerId())).hasSize(1);

View File

@@ -62,6 +62,10 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>

View File

@@ -15,8 +15,6 @@ import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.hawkbit.dmf.amqp.api.EventTopic;
import org.eclipse.hawkbit.dmf.amqp.api.MessageHeaderKey;
import org.eclipse.hawkbit.dmf.amqp.api.MessageType;
@@ -45,6 +43,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.util.StringUtils;
/**
*
@@ -240,7 +239,8 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
final Action action = checkActionExist(message, actionUpdateStatus);
final List<String> messages = actionUpdateStatus.getMessage();
if (ArrayUtils.isNotEmpty(message.getMessageProperties().getCorrelationId())) {
if (isCorrelationIdNotEmpty(message)) {
messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "DMF message correlation-id "
+ convertCorrelationId(message));
}
@@ -256,7 +256,13 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
}
}
private Status mapStatus(final Message message, final DmfActionUpdateStatus actionUpdateStatus, final Action action) {
private static boolean isCorrelationIdNotEmpty(final Message message) {
return message.getMessageProperties().getCorrelationId() != null
&& message.getMessageProperties().getCorrelationId().length > 0;
}
private Status mapStatus(final Message message, final DmfActionUpdateStatus actionUpdateStatus,
final Action action) {
Status status = null;
switch (actionUpdateStatus.getActionStatus()) {
case DOWNLOAD:

View File

@@ -19,6 +19,7 @@ import static org.mockito.Mockito.when;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@@ -54,8 +55,6 @@ import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import com.google.common.collect.Lists;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@@ -96,7 +95,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
final ArtifactUrlHandler artifactUrlHandlerMock = Mockito.mock(ArtifactUrlHandler.class);
when(artifactUrlHandlerMock.getUrls(anyObject(), anyObject()))
.thenReturn(Lists.newArrayList(new ArtifactUrl("http", "download", "http://mockurl")));
.thenReturn(Arrays.asList(new ArtifactUrl("http", "download", "http://mockurl")));
systemManagement = Mockito.mock(SystemManagement.class);
final TenantMetaData tenantMetaData = Mockito.mock(TenantMetaData.class);
@@ -178,7 +177,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
for (final Artifact artifact : testdataFactory.createArtifacts(module.getId())) {
receivedList.add(new DbArtifact());
}
module = softwareManagement.findSoftwareModuleById(module.getId()).get();
module = softwareModuleManagement.findSoftwareModuleById(module.getId()).get();
dsA = distributionSetManagement.findDistributionSetById(dsA.getId()).get();
final Action action = createAction(dsA);

View File

@@ -9,9 +9,9 @@
package org.eclipse.hawkbit.integration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -22,6 +22,7 @@ import org.eclipse.hawkbit.dmf.amqp.api.MessageType;
import org.eclipse.hawkbit.dmf.json.model.DmfActionStatus;
import org.eclipse.hawkbit.dmf.json.model.DmfActionUpdateStatus;
import org.eclipse.hawkbit.dmf.json.model.DmfAttributeUpdate;
import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.event.remote.TargetPollEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.ActionCreatedEvent;
@@ -51,6 +52,7 @@ import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Device Management Federation API")
@Stories("Amqp Message Handler Service")
public class AmqpMessageHandlerServiceIntegrationTest extends AmqpServiceIntegrationTest {
private static final String CORRELATION_ID = UUID.randomUUID().toString();
@Autowired
private AmqpProperties amqpProperties;
@@ -512,7 +514,7 @@ public class AmqpMessageHandlerServiceIntegrationTest extends AmqpServiceIntegra
final Long actionId = registerTargetAndCancelActionId();
sendActionUpdateStatus(new DmfActionUpdateStatus(actionId, DmfActionStatus.CANCEL_REJECTED));
assertAction(actionId, Status.RUNNING, Status.CANCELING, Status.CANCEL_REJECTED);
assertAction(actionId, 1, Status.RUNNING, Status.CANCELING, Status.CANCEL_REJECTED);
}
@Test
@@ -597,21 +599,36 @@ public class AmqpMessageHandlerServiceIntegrationTest extends AmqpServiceIntegra
private void registerTargetAndSendAndAssertUpdateActionStatus(final DmfActionStatus sendActionStatus,
final Status expectedActionStatus) {
final Long actionId = registerTargetAndSendActionStatus(sendActionStatus);
assertAction(actionId, Status.RUNNING, expectedActionStatus);
assertAction(actionId, 1, Status.RUNNING, expectedActionStatus);
}
private void assertAction(final Long actionId, final Status... expectedActionStates) {
private void assertAction(final Long actionId, final int messages, final Status... expectedActionStates) {
createConditionFactory().await().until(() -> {
try {
securityRule.runAsPrivileged(() -> {
final List<Status> status = deploymentManagement.findActionStatusByAction(PAGE, actionId)
.getContent().stream().map(actionStatus -> actionStatus.getStatus())
final List<org.eclipse.hawkbit.repository.model.ActionStatus> actionStatusList = deploymentManagement
.findActionStatusByAction(PAGE, actionId).getContent();
// Check correlation ID
final List<String> messagesFromServer = actionStatusList.stream()
.flatMap(actionStatus -> deploymentManagement
.findMessagesByActionStatusId(PAGE, actionStatus.getId()).getContent().stream())
.filter(Objects::nonNull)
.filter(message -> message
.startsWith(RepositoryConstants.SERVER_MESSAGE_PREFIX + "DMF message"))
.collect(Collectors.toList());
assertThat(messagesFromServer).hasSize(messages)
.allMatch(message -> message.endsWith(CORRELATION_ID));
final List<Status> status = actionStatusList.stream().map(actionStatus -> actionStatus.getStatus())
.collect(Collectors.toList());
assertThat(status).containsOnly(expectedActionStates);
return null;
});
} catch (final Exception e) {
fail(e.getMessage());
throw new RuntimeException(e);
}
});
}
@@ -620,6 +637,7 @@ public class AmqpMessageHandlerServiceIntegrationTest extends AmqpServiceIntegra
final MessageProperties messageProperties = createMessagePropertiesWithTenant(tenant);
messageProperties.getHeaders().put(MessageHeaderKey.TYPE, MessageType.EVENT.toString());
messageProperties.getHeaders().put(MessageHeaderKey.TOPIC, eventTopic.toString());
messageProperties.setCorrelationId(CORRELATION_ID.getBytes());
return createMessage(payload, messageProperties);
}

View File

@@ -41,6 +41,10 @@
<artifactId>hawkbit-dmf-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-junit</artifactId>

View File

@@ -72,7 +72,7 @@ public abstract class AbstractAmqpIntegrationTest extends AbstractIntegrationTes
return getDmfClient().getMessageConverter().toMessage(payload, messageProperties);
}
protected int getQueueMessageCount(String queueName) {
protected int getQueueMessageCount(final String queueName) {
return Integer
.parseInt(rabbitAdmin.getQueueProperties(queueName).get(RabbitAdmin.QUEUE_MESSAGE_COUNT).toString());
}

View File

@@ -11,6 +11,7 @@ package org.eclipse.hawkbit.security;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import javax.servlet.FilterChain;
@@ -33,9 +34,6 @@ import org.springframework.security.web.authentication.preauth.AbstractPreAuthen
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.util.AntPathMatcher;
import com.google.common.collect.Iterators;
import com.google.common.collect.UnmodifiableIterator;
/**
* An abstraction for all controller based security to parse the e.g. the tenant
* name from the URL and the controller ID from the URL to do security checks
@@ -170,8 +168,10 @@ public abstract class AbstractHttpControllerAuthenticationFilter extends Abstrac
final String tenant, final String controllerId) {
final DmfTenantSecurityToken secruityToken = new DmfTenantSecurityToken(tenant, null, controllerId, null,
FileResource.createFileResourceBySha1(""));
final UnmodifiableIterator<String> forEnumeration = Iterators.forEnumeration(request.getHeaderNames());
forEnumeration.forEachRemaining(header -> secruityToken.putHeader(header, request.getHeader(header)));
Collections.list(request.getHeaderNames())
.forEach(header -> secruityToken.putHeader(header, request.getHeader(header)));
return secruityToken;
}

View File

@@ -12,6 +12,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -21,8 +23,6 @@ import org.springframework.security.authentication.InsufficientAuthenticationExc
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import com.google.common.collect.Lists;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@@ -47,8 +47,8 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
public void principalAndCredentialsNotTheSameThrowsAuthenticationException() {
final String principal = "controllerIdURL";
final String credentials = "controllerIdHeader";
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
principal, Lists.newArrayList(credentials));
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
Arrays.asList(credentials));
token.setDetails(webAuthenticationDetailsMock);
// test, should throw authentication exception
@@ -66,12 +66,11 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
public void principalAndCredentialsAreTheSameWithNoSourceIpCheckIsSuccessful() {
final String principal = "controllerId";
final String credentials = "controllerId";
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
principal, Lists.newArrayList(credentials));
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
Arrays.asList(credentials));
token.setDetails(webAuthenticationDetailsMock);
final Authentication authenticate = underTestWithoutSourceIpCheck
.authenticate(token);
final Authentication authenticate = underTestWithoutSourceIpCheck.authenticate(token);
assertThat(authenticate.isAuthenticated()).isTrue();
}
@@ -81,8 +80,8 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
final String remoteAddress = "192.168.1.1";
final String principal = "controllerId";
final String credentials = "controllerId";
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
principal, Lists.newArrayList(credentials));
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
Arrays.asList(credentials));
token.setDetails(webAuthenticationDetailsMock);
when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(remoteAddress);
@@ -102,15 +101,14 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
public void priniciapAndCredentialsAreTheSameAndSourceIpIsTrusted() {
final String principal = "controllerId";
final String credentials = "controllerId";
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
principal, Lists.newArrayList(credentials));
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
Arrays.asList(credentials));
token.setDetails(webAuthenticationDetailsMock);
when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP);
// test, should throw authentication exception
final Authentication authenticate = underTestWithSourceIpCheck
.authenticate(token);
final Authentication authenticate = underTestWithSourceIpCheck.authenticate(token);
assertThat(authenticate.isAuthenticated()).isTrue();
}
@@ -120,8 +118,8 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
"192.168.1.3" };
final String principal = "controllerId";
final String credentials = "controllerId";
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
principal, Lists.newArrayList(credentials));
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
Arrays.asList(credentials));
token.setDetails(webAuthenticationDetailsMock);
when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP);
@@ -139,8 +137,8 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {
final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", "192.168.1.3" };
final String principal = "controllerId";
final String credentials = "controllerId";
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
principal, Lists.newArrayList(credentials));
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
Arrays.asList(credentials));
token.setDetails(webAuthenticationDetailsMock);
when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP);

View File

@@ -40,6 +40,10 @@
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>

View File

@@ -29,7 +29,7 @@ import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.TargetManagement;
@@ -63,7 +63,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtDistributionSetResource.class);
@Autowired
private SoftwareManagement softwareManagement;
private SoftwareModuleManagement softwareModuleManagement;
@Autowired
private TargetManagement targetManagement;
@@ -346,7 +346,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeSoftwareModuleSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<SoftwareModule> softwaremodules = softwareManagement.findSoftwareModuleByAssignedTo(pageable,
final Page<SoftwareModule> softwaremodules = softwareModuleManagement.findSoftwareModuleByAssignedTo(pageable,
distributionSetId);
return new ResponseEntity<>(new PagedList<>(MgmtSoftwareModuleMapper.toResponse(softwaremodules.getContent()),
softwaremodules.getTotalElements()), HttpStatus.OK);

View File

@@ -8,6 +8,7 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.Arrays;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.MgmtId;
@@ -18,10 +19,10 @@ import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionS
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.DistributionSetTypeManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.SoftwareModuleTypeNotInDistributionSetTypeException;
import org.eclipse.hawkbit.repository.model.Artifact;
@@ -40,8 +41,6 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.google.common.collect.Lists;
/**
* REST Resource handling for {@link SoftwareModule} and related
* {@link Artifact} CRUD operations.
@@ -50,10 +49,10 @@ import com.google.common.collect.Lists;
public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeRestApi {
@Autowired
private SoftwareManagement softwareManagement;
private SoftwareModuleTypeManagement softwareModuleTypeManagement;
@Autowired
private DistributionSetManagement distributionSetManagement;
private DistributionSetTypeManagement distributionSetTypeManagement;
@Autowired
private EntityFactory entityFactory;
@@ -73,11 +72,11 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
final Slice<DistributionSetType> findModuleTypessAll;
Long countModulesAll;
if (rsqlParam != null) {
findModuleTypessAll = distributionSetManagement.findDistributionSetTypesAll(rsqlParam, pageable);
findModuleTypessAll = distributionSetTypeManagement.findDistributionSetTypesAll(rsqlParam, pageable);
countModulesAll = ((Page<DistributionSetType>) findModuleTypessAll).getTotalElements();
} else {
findModuleTypessAll = distributionSetManagement.findDistributionSetTypesAll(pageable);
countModulesAll = distributionSetManagement.countDistributionSetTypesAll();
findModuleTypessAll = distributionSetTypeManagement.findDistributionSetTypesAll(pageable);
countModulesAll = distributionSetTypeManagement.countDistributionSetTypesAll();
}
final List<MgmtDistributionSetType> rest = MgmtDistributionSetTypeMapper
@@ -96,7 +95,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@Override
public ResponseEntity<Void> deleteDistributionSetType(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
distributionSetManagement.deleteDistributionSetType(distributionSetTypeId);
distributionSetTypeManagement.deleteDistributionSetType(distributionSetTypeId);
return ResponseEntity.ok().build();
}
@@ -107,7 +106,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) {
return ResponseEntity.ok(MgmtDistributionSetTypeMapper
.toResponse(distributionSetManagement.updateDistributionSetType(entityFactory.distributionSetType()
.toResponse(distributionSetTypeManagement.updateDistributionSetType(entityFactory.distributionSetType()
.update(distributionSetTypeId).description(restDistributionSetType.getDescription())
.colour(restDistributionSetType.getColour()))));
}
@@ -116,7 +115,8 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
public ResponseEntity<List<MgmtDistributionSetType>> createDistributionSetTypes(
@RequestBody final List<MgmtDistributionSetTypeRequestBodyPost> distributionSetTypes) {
final List<DistributionSetType> createdSoftwareModules = distributionSetManagement.createDistributionSetTypes(
final List<DistributionSetType> createdSoftwareModules = distributionSetTypeManagement
.createDistributionSetTypes(
MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, distributionSetTypes));
return ResponseEntity.status(HttpStatus.CREATED)
@@ -124,7 +124,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
}
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final Long distributionSetTypeId) {
return distributionSetManagement.findDistributionSetTypeById(distributionSetTypeId)
return distributionSetTypeManagement.findDistributionSetTypeById(distributionSetTypeId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypeId));
}
@@ -178,7 +178,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
public ResponseEntity<Void> removeMandatoryModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
distributionSetManagement.unassignSoftwareModuleType(distributionSetTypeId, softwareModuleTypeId);
distributionSetTypeManagement.unassignSoftwareModuleType(distributionSetTypeId, softwareModuleTypeId);
return ResponseEntity.ok().build();
}
@@ -195,8 +195,8 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
public ResponseEntity<Void> addMandatoryModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) {
distributionSetManagement.assignMandatorySoftwareModuleTypes(distributionSetTypeId,
Lists.newArrayList(smtId.getId()));
distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(distributionSetTypeId,
Arrays.asList(smtId.getId()));
return ResponseEntity.ok().build();
}
@@ -205,15 +205,15 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
public ResponseEntity<Void> addOptionalModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) {
distributionSetManagement.assignOptionalSoftwareModuleTypes(distributionSetTypeId,
Lists.newArrayList(smtId.getId()));
distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(distributionSetTypeId,
Arrays.asList(smtId.getId()));
return ResponseEntity.ok().build();
}
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
return softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId)
return softwareModuleTypeManagement.findSoftwareModuleTypeById(softwareModuleTypeId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId));
}
}

View File

@@ -15,7 +15,7 @@ import javax.servlet.http.HttpServletRequest;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadArtifactRestApi;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNotFoundException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Artifact;
@@ -39,7 +39,7 @@ import org.springframework.web.context.WebApplicationContext;
public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi {
@Autowired
private SoftwareManagement softwareManagement;
private SoftwareModuleManagement softwareModuleManagement;
@Autowired
private ArtifactManagement artifactManagement;
@@ -61,7 +61,7 @@ public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi
@ResponseBody
public ResponseEntity<InputStream> downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("artifactId") final Long artifactId) {
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
final SoftwareModule module = softwareModuleManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
final Artifact artifact = module.getArtifact(artifactId)
.orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId));

View File

@@ -19,9 +19,6 @@ import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
* A mapper which maps repository model to RESTful model representation and
* back.
*
*
*
*
*/
final class MgmtRestModelMapper {

View File

@@ -16,7 +16,6 @@ import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifactHash;
@@ -116,8 +115,8 @@ public final class MgmtSoftwareModuleMapper {
response.add(linkTo(methodOn(MgmtSoftwareModuleResource.class).getMetadata(response.getModuleId(),
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("metadata").expand(ArrayUtils.toArray()));
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null)).withRel("metadata")
.expand());
return response;
}

View File

@@ -23,7 +23,7 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestApi;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -57,7 +57,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
private ArtifactManagement artifactManagement;
@Autowired
private SoftwareManagement softwareManagement;
private SoftwareModuleManagement softwareModuleManagement;
@Autowired
private EntityFactory entityFactory;
@@ -138,11 +138,11 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
final Slice<SoftwareModule> findModulesAll;
Long countModulesAll;
if (rsqlParam != null) {
findModulesAll = softwareManagement.findSoftwareModulesByPredicate(rsqlParam, pageable);
findModulesAll = softwareModuleManagement.findSoftwareModulesByPredicate(rsqlParam, pageable);
countModulesAll = ((Page<SoftwareModule>) findModulesAll).getTotalElements();
} else {
findModulesAll = softwareManagement.findSoftwareModulesAll(pageable);
countModulesAll = softwareManagement.countSoftwareModulesAll();
findModulesAll = softwareModuleManagement.findSoftwareModulesAll(pageable);
countModulesAll = softwareModuleManagement.countSoftwareModulesAll();
}
final List<MgmtSoftwareModule> rest = MgmtSoftwareModuleMapper.toResponse(findModulesAll.getContent());
@@ -162,7 +162,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@RequestBody final List<MgmtSoftwareModuleRequestBodyPost> softwareModules) {
LOG.debug("creating {} softwareModules", softwareModules.size());
final Collection<SoftwareModule> createdSoftwareModules = softwareManagement
final Collection<SoftwareModule> createdSoftwareModules = softwareModuleManagement
.createSoftwareModule(MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules));
LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED);
@@ -176,7 +176,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule) {
return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponse(
softwareManagement.updateSoftwareModule(entityFactory.softwareModule().update(softwareModuleId)
softwareModuleManagement.updateSoftwareModule(entityFactory.softwareModule().update(softwareModuleId)
.description(restSoftwareModule.getDescription()).vendor(restSoftwareModule.getVendor()))));
}
@@ -184,7 +184,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity<Void> deleteSoftwareModule(@PathVariable("softwareModuleId") final Long softwareModuleId) {
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
softwareManagement.deleteSoftwareModule(module.getId());
softwareModuleManagement.deleteSoftwareModule(module.getId());
return ResponseEntity.ok().build();
}
@@ -208,10 +208,10 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
final Page<SoftwareModuleMetadata> metaDataPage;
if (rsqlParam != null) {
metaDataPage = softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId, rsqlParam,
metaDataPage = softwareModuleManagement.findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId, rsqlParam,
pageable);
} else {
metaDataPage = softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId, pageable);
metaDataPage = softwareModuleManagement.findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId, pageable);
}
return ResponseEntity
@@ -223,7 +223,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity<MgmtMetadata> getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) {
final SoftwareModuleMetadata findOne = softwareManagement
final SoftwareModuleMetadata findOne = softwareModuleManagement
.findSoftwareModuleMetadata(softwareModuleId, metadataKey).orElseThrow(
() -> new EntityNotFoundException(SoftwareModuleMetadata.class, softwareModuleId, metadataKey));
@@ -233,7 +233,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@Override
public ResponseEntity<MgmtMetadata> updateMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata) {
final SoftwareModuleMetadata updated = softwareManagement.updateSoftwareModuleMetadata(softwareModuleId,
final SoftwareModuleMetadata updated = softwareModuleManagement.updateSoftwareModuleMetadata(softwareModuleId,
entityFactory.generateMetadata(metadataKey, metadata.getValue()));
return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(updated));
@@ -242,7 +242,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@Override
public ResponseEntity<Void> deleteMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) {
softwareManagement.deleteSoftwareModuleMetadata(softwareModuleId, metadataKey);
softwareModuleManagement.deleteSoftwareModuleMetadata(softwareModuleId, metadataKey);
return ResponseEntity.ok().build();
}
@@ -252,7 +252,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@PathVariable("softwareModuleId") final Long softwareModuleId,
@RequestBody final List<MgmtMetadata> metadataRest) {
final List<SoftwareModuleMetadata> created = softwareManagement.createSoftwareModuleMetadata(softwareModuleId,
final List<SoftwareModuleMetadata> created = softwareModuleManagement.createSoftwareModuleMetadata(softwareModuleId,
MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, metadataRest));
return ResponseEntity.status(HttpStatus.CREATED).body(MgmtSoftwareModuleMapper.toResponseSwMetadata(created));
@@ -261,7 +261,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
final Long artifactId) {
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
final SoftwareModule module = softwareModuleManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (artifactId != null && !module.getArtifact(artifactId).isPresent()) {

View File

@@ -18,7 +18,7 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -43,7 +43,7 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRestApi {
@Autowired
private SoftwareManagement softwareManagement;
private SoftwareModuleTypeManagement softwareModuleTypeManagement;
@Autowired
private EntityFactory entityFactory;
@@ -64,11 +64,11 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
final Slice<SoftwareModuleType> findModuleTypessAll;
Long countModulesAll;
if (rsqlParam != null) {
findModuleTypessAll = softwareManagement.findSoftwareModuleTypesAll(rsqlParam, pageable);
findModuleTypessAll = softwareModuleTypeManagement.findSoftwareModuleTypesAll(rsqlParam, pageable);
countModulesAll = ((Page<SoftwareModuleType>) findModuleTypessAll).getTotalElements();
} else {
findModuleTypessAll = softwareManagement.findSoftwareModuleTypesAll(pageable);
countModulesAll = softwareManagement.countSoftwareModuleTypesAll();
findModuleTypessAll = softwareModuleTypeManagement.findSoftwareModuleTypesAll(pageable);
countModulesAll = softwareModuleTypeManagement.countSoftwareModuleTypesAll();
}
final List<MgmtSoftwareModuleType> rest = MgmtSoftwareModuleTypeMapper
@@ -87,7 +87,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
@Override
public ResponseEntity<Void> deleteSoftwareModuleType(
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
softwareManagement.deleteSoftwareModuleType(softwareModuleTypeId);
softwareModuleTypeManagement.deleteSoftwareModuleType(softwareModuleTypeId);
return new ResponseEntity<>(HttpStatus.OK);
}
@@ -96,7 +96,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId,
@RequestBody final MgmtSoftwareModuleTypeRequestBodyPut restSoftwareModuleType) {
final SoftwareModuleType updatedSoftwareModuleType = softwareManagement.updateSoftwareModuleType(entityFactory
final SoftwareModuleType updatedSoftwareModuleType = softwareModuleTypeManagement.updateSoftwareModuleType(entityFactory
.softwareModuleType().update(softwareModuleTypeId).description(restSoftwareModuleType.getDescription())
.colour(restSoftwareModuleType.getColour()));
@@ -107,7 +107,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
public ResponseEntity<List<MgmtSoftwareModuleType>> createSoftwareModuleTypes(
@RequestBody final List<MgmtSoftwareModuleTypeRequestBodyPost> softwareModuleTypes) {
final List<SoftwareModuleType> createdSoftwareModules = softwareManagement.createSoftwareModuleType(
final List<SoftwareModuleType> createdSoftwareModules = softwareModuleTypeManagement.createSoftwareModuleType(
MgmtSoftwareModuleTypeMapper.smFromRequest(entityFactory, softwareModuleTypes));
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules),
@@ -115,7 +115,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
}
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
return softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId)
return softwareModuleTypeManagement.findSoftwareModuleTypeById(softwareModuleTypeId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId));
}

View File

@@ -19,7 +19,6 @@ import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.hawkbit.mgmt.json.model.MgmtPollStatus;
import org.eclipse.hawkbit.mgmt.json.model.action.MgmtAction;
import org.eclipse.hawkbit.mgmt.json.model.action.MgmtActionStatus;
@@ -67,7 +66,7 @@ public final class MgmtTargetMapper {
response.add(linkTo(methodOn(MgmtTargetRestApi.class).getActionHistory(response.getControllerId(), 0,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE,
ActionFields.ID.getFieldName() + ":" + SortDirection.DESC, null))
.withRel(MgmtRestConstants.TARGET_V1_ACTIONS).expand(ArrayUtils.toArray()));
.withRel(MgmtRestConstants.TARGET_V1_ACTIONS).expand());
}
static void addPollStatus(final Target target, final MgmtTarget targetRest) {

View File

@@ -11,6 +11,7 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@@ -51,8 +52,6 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.google.common.collect.Lists;
/**
* REST Resource handling target CRUD operations.
*/
@@ -281,7 +280,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final ActionType type = (dsId.getType() != null) ? MgmtRestModelMapper.convertActionType(dsId.getType())
: ActionType.FORCED;
this.deploymentManagement.assignDistributionSet(dsId.getId(), type, dsId.getForcetime(),
Lists.newArrayList(controllerId));
Arrays.asList(controllerId));
return new ResponseEntity<>(HttpStatus.OK);
}

View File

@@ -21,6 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
@@ -45,7 +46,6 @@ import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jayway.jsonpath.JsonPath;
@@ -167,7 +167,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(disSet.getModules().size())));
// create Software Modules
final List<Long> smIDs = Lists.newArrayList(testdataFactory.createSoftwareModuleOs().getId(),
final List<Long> smIDs = Arrays.asList(testdataFactory.createSoftwareModuleOs().getId(),
testdataFactory.createSoftwareModuleApp().getId());
// post assignment
@@ -270,7 +270,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
// assign knownTargetId to distribution set
assignDistributionSet(createdDs.getId(), knownTargetId);
// make it in install state
testdataFactory.sendUpdateActionStatusToTargets(Lists.newArrayList(createTarget), Status.FINISHED,
testdataFactory.sendUpdateActionStatusToTargets(Arrays.asList(createTarget), Status.FINISHED,
Collections.singletonList("some message"));
mvc.perform(get(
@@ -414,8 +414,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that multiple DS requested are listed with expected payload.")
public void getDistributionSets() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(0);
DistributionSet set = testdataFactory.createDistributionSet("one");
set = distributionSetManagement.updateDistributionSet(entityFactory.distributionSet().update(set.getId())
@@ -424,8 +423,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
// load also lazy stuff
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).get();
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(1);
// perform request
mvc.perform(get("/rest/v1/distributionsets").accept(MediaType.APPLICATION_JSON))
@@ -488,28 +486,29 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that multipe DS posted to API are created in the repository.")
public void createDistributionSets() throws Exception {
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(0);
final SoftwareModule ah = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP);
final SoftwareModule jvm = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_RT);
final SoftwareModule os = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_OS);
DistributionSet one = testdataFactory.generateDistributionSet("one", "one", standardDsType,
Lists.newArrayList(os, jvm, ah));
Arrays.asList(os, jvm, ah));
DistributionSet two = testdataFactory.generateDistributionSet("two", "two", standardDsType,
Lists.newArrayList(os, jvm, ah));
Arrays.asList(os, jvm, ah));
DistributionSet three = testdataFactory.generateDistributionSet("three", "three", standardDsType,
Lists.newArrayList(os, jvm, ah), true);
Arrays.asList(os, jvm, ah), true);
final long current = System.currentTimeMillis();
final MvcResult mvcResult = executeMgmtTargetPost(one, two, three);
one = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
.findDistributionSetsAll("name==one", PAGE, false).getContent().get(0).getId()).get();
two = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
.findDistributionSetsAll("name==two", PAGE, false).getContent().get(0).getId()).get();
one = distributionSetManagement.findDistributionSetByIdWithDetails(
distributionSetManagement.findDistributionSetsAll("name==one", PAGE, false).getContent().get(0).getId())
.get();
two = distributionSetManagement.findDistributionSetByIdWithDetails(
distributionSetManagement.findDistributionSetsAll("name==two", PAGE, false).getContent().get(0).getId())
.get();
three = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
.findDistributionSetsAll("name==three", PAGE, false).getContent().get(0).getId()).get();
@@ -542,8 +541,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.isEqualTo(String.valueOf(three.getId()));
// check in database
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(3);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(3);
assertThat(one.isRequiredMigrationStep()).isEqualTo(false);
assertThat(two.isRequiredMigrationStep()).isEqualTo(false);
assertThat(three.isRequiredMigrationStep()).isEqualTo(true);
@@ -558,7 +556,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
final DistributionSet three) throws Exception {
return mvc
.perform(post("/rest/v1/distributionsets/")
.content(JsonBuilder.distributionSets(Lists.newArrayList(one, two, three)))
.content(JsonBuilder.distributionSets(Arrays.asList(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))
@@ -607,21 +605,18 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that DS deletion request to API is reflected by the repository.")
public void deleteUnassignedistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one");
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(1);
// perform request
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// check repository content
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.isEmpty();
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).isEmpty();
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(0);
}
@@ -636,25 +631,21 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@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 {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one");
testdataFactory.createTarget("test");
assignDistributionSet(set.getId(), "test");
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(1);
// perform request
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// check repository content
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, true, true))
.hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, true, true)).hasSize(1);
}
@Test
@@ -662,8 +653,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
public void updateDistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one");
@@ -686,12 +676,11 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
public void updateRequiredMigrationStepFailsIfDistributionSetisInUse() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true)).hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one");
deploymentManagement.assignDistributionSet(set.getId(),
Lists.newArrayList(new TargetWithActionType(testdataFactory.createTarget().getControllerId())));
Arrays.asList(new TargetWithActionType(testdataFactory.createTarget().getControllerId())));
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(1);
@@ -732,16 +721,14 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(status().isBadRequest());
final DistributionSet missingName = entityFactory.distributionSet().create().build();
mvc.perform(
post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(Lists.newArrayList(missingName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
mvc.perform(post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(Arrays.asList(missingName)))
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
final DistributionSet toLongName = testdataFactory.generateDistributionSet(RandomStringUtils.randomAscii(80));
mvc.perform(
post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(Lists.newArrayList(toLongName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
mvc.perform(post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(Arrays.asList(toLongName)))
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
// unsupported media type
mvc.perform(post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(sets))
@@ -929,7 +916,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
// prepare targets
final Collection<String> knownTargetIds = Lists.newArrayList("1", "2", "3", "4", "5");
final Collection<String> knownTargetIds = Arrays.asList("1", "2", "3", "4", "5");
knownTargetIds.forEach(controllerId -> targetManagement
.createTarget(entityFactory.target().create().controllerId(controllerId)));

View File

@@ -22,6 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -37,7 +38,6 @@ import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Description;
@@ -58,10 +58,10 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests.")
public void getDistributionSetTypes() throws Exception {
DistributionSetType testType = distributionSetManagement
DistributionSetType testType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
testType = distributionSetManagement.updateDistributionSetType(
testType = distributionSetTypeManagement.updateDistributionSetType(
entityFactory.distributionSetType().update(testType.getId()).description("Desc1234"));
// 4 types overall (2 hawkbit tenant default, 1 test default and 1
@@ -99,10 +99,10 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with sorting by KEY.")
public void getDistributionSetTypesSortedByKey() throws Exception {
DistributionSetType testType = distributionSetManagement
DistributionSetType testType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("zzzzz").name("TestName123")
.description("Desc123").colour("col12"));
testType = distributionSetManagement.updateDistributionSetType(
testType = distributionSetTypeManagement.updateDistributionSetType(
entityFactory.distributionSetType().update(testType.getId()).description("Desc1234"));
// descending
@@ -148,9 +148,12 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Step
private void verifyCreatedDistributionSetTypes(final MvcResult mvcResult) throws UnsupportedEncodingException {
final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("testKey1").get();
final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("testKey2").get();
final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("testKey3").get();
final DistributionSetType created1 = distributionSetTypeManagement.findDistributionSetTypeByKey("testKey1")
.get();
final DistributionSetType created2 = distributionSetTypeManagement.findDistributionSetTypeByKey("testKey2")
.get();
final DistributionSetType created3 = distributionSetTypeManagement.findDistributionSetTypeByKey("testKey3")
.get();
assertThat(created1.getMandatoryModuleTypes()).containsOnly(osType);
assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType);
@@ -187,7 +190,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
.toString()).isEqualTo(
"http://localhost/rest/v1/distributionsettypes/" + created3.getId() + "/optionalmoduletypes");
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(6);
assertThat(distributionSetTypeManagement.countDistributionSetTypesAll()).isEqualTo(6);
}
@Step
@@ -214,24 +217,24 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Step
private List<DistributionSetType> createTestDistributionSetTestTypes() {
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
assertThat(distributionSetTypeManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
return Lists.newArrayList(
return Arrays.asList(
entityFactory.distributionSetType().create().key("testKey1").name("TestName1").description("Desc1")
.colour("col").mandatory(Lists.newArrayList(osType.getId()))
.optional(Lists.newArrayList(runtimeType.getId())).build(),
.colour("col").mandatory(Arrays.asList(osType.getId()))
.optional(Arrays.asList(runtimeType.getId())).build(),
entityFactory.distributionSetType().create().key("testKey2").name("TestName2").description("Desc2")
.colour("col")
.optional(Lists.newArrayList(runtimeType.getId(), osType.getId(), appType.getId())).build(),
.colour("col").optional(Arrays.asList(runtimeType.getId(), osType.getId(), appType.getId()))
.build(),
entityFactory.distributionSetType().create().key("testKey3").name("TestName3").description("Desc3")
.colour("col").mandatory(Lists.newArrayList(runtimeType.getId(), osType.getId())).build());
.colour("col").mandatory(Arrays.asList(runtimeType.getId(), osType.getId())).build());
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.")
public void addMandatoryModuleToDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement
DistributionSetType testType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
@@ -240,7 +243,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
testType = distributionSetTypeManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
@@ -251,7 +254,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.")
public void addOptionalModuleToDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement
DistributionSetType testType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
@@ -260,7 +263,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
testType = distributionSetTypeManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).containsExactly(osType);
@@ -315,9 +318,9 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
}
private DistributionSetType generateTestType() {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(entityFactory
final DistributionSetType testType = distributionSetTypeManagement.createDistributionSetType(entityFactory
.distributionSetType().create().key("test123").name("TestName123").description("Desc123").colour("col")
.mandatory(Lists.newArrayList(osType.getId())).optional(Lists.newArrayList(appType.getId())));
.mandatory(Arrays.asList(osType.getId())).optional(Arrays.asList(appType.getId())));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
@@ -351,7 +354,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
testType = distributionSetTypeManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
@@ -368,7 +371,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
testType = distributionSetTypeManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).isEmpty();
@@ -380,10 +383,10 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} GET requests.")
public void getDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement
DistributionSetType testType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
testType = distributionSetManagement.updateDistributionSetType(
testType = distributionSetTypeManagement.updateDistributionSetType(
entityFactory.distributionSetType().update(testType.getId()).description("Desc1234"));
mvc.perform(get("/rest/v1/distributionsettypes/{dstId}", testType.getId()).accept(MediaType.APPLICATION_JSON))
@@ -400,16 +403,16 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (hard delete scenario).")
public void deleteDistributionSetTypeUnused() throws Exception {
final DistributionSetType testType = distributionSetManagement
final DistributionSetType testType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1);
assertThat(distributionSetTypeManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1);
mvc.perform(delete("/rest/v1/distributionsettypes/{dsId}", testType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
assertThat(distributionSetTypeManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
}
@Test
@@ -423,27 +426,27 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).")
public void deleteDistributionSetTypeUsed() throws Exception {
final DistributionSetType testType = distributionSetManagement
final DistributionSetType testType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("sdfsd")
.description("dsfsdf").version("1").type(testType));
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1);
assertThat(distributionSetTypeManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1);
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/distributionsettypes/{smId}", testType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(1);
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
assertThat(distributionSetTypeManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
}
@Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} PUT requests.")
public void updateDistributionSetTypeOnlyDescriptionAndNameUntouched() throws Exception {
final DistributionSetType testType = distributionSetManagement
final DistributionSetType testType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col"));
@@ -507,7 +510,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
// .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
// .name("TestName123").description("Desc123").colour("col"));
final SoftwareModuleType testSmType = softwareManagement.createSoftwareModuleType(
final SoftwareModuleType testSmType = softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("test123").name("TestName123"));
// DST does not exist
@@ -549,11 +552,11 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
// Modules types at creation time invalid
final DistributionSetType testNewType = entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col").mandatory(Lists.newArrayList(osType.getId()))
.name("TestName123").description("Desc123").colour("col").mandatory(Arrays.asList(osType.getId()))
.optional(Collections.emptyList()).build();
mvc.perform(post("/rest/v1/distributionsettypes")
.content(JsonBuilder.distributionSetTypes(Lists.newArrayList(testNewType)))
.content(JsonBuilder.distributionSetTypes(Arrays.asList(testNewType)))
.contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isUnsupportedMediaType());
@@ -574,7 +577,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
final DistributionSetType toLongName = entityFactory.distributionSetType().create().key("test123")
.name(RandomStringUtils.randomAscii(80)).build();
mvc.perform(post("/rest/v1/distributionsettypes")
.content(JsonBuilder.distributionSetTypes(Lists.newArrayList(toLongName)))
.content(JsonBuilder.distributionSetTypes(Arrays.asList(toLongName)))
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
@@ -595,9 +598,9 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@Description("Search erquest of software module types.")
public void searchDistributionSetTypeRsql() throws Exception {
distributionSetManagement.createDistributionSetType(
distributionSetTypeManagement.createDistributionSetType(
entityFactory.distributionSetType().create().key("test123").name("TestName123"));
distributionSetManagement.createDistributionSetType(
distributionSetTypeManagement.createDistributionSetType(
entityFactory.distributionSetType().create().key("test1234").name("TestName1234"));
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
@@ -612,7 +615,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
softwareManagement.createSoftwareModule(
softwareModuleManagement.createSoftwareModule(
entityFactory.softwareModule().create().name(str).description(str).vendor(str).version(str));
character++;
}

View File

@@ -23,6 +23,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
@@ -47,8 +48,6 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import com.google.common.collect.Lists;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
@@ -144,7 +143,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
final float percentTargetsInGroup1 = 20;
final float percentTargetsInGroup2 = 100;
final List<RolloutGroup> rolloutGroups = Lists.newArrayList(
final List<RolloutGroup> rolloutGroups = Arrays.asList(
entityFactory.rolloutGroup().create().name("Group1").description("Group1desc")
.targetPercentage(percentTargetsInGroup1).build(),
entityFactory.rolloutGroup().create().name("Group2").description("Group2desc")
@@ -168,7 +167,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
final int amountTargets = 10;
testdataFactory.createTargets(amountTargets, "ro-target", "rollout");
final List<RolloutGroup> rolloutGroups = Lists.newArrayList(
final List<RolloutGroup> rolloutGroups = Arrays.asList(
entityFactory.rolloutGroup().create().name("Group1").description("Group1desc").targetPercentage(0F)
.build(),
entityFactory.rolloutGroup().create().name("Group2").description("Group2desc").targetPercentage(100F)
@@ -193,7 +192,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
final int amountTargets = 10;
testdataFactory.createTargets(amountTargets, "ro-target", "rollout");
final List<RolloutGroup> rolloutGroups = Lists.newArrayList(
final List<RolloutGroup> rolloutGroups = Arrays.asList(
entityFactory.rolloutGroup().create().name("Group1").description("Group1desc").targetPercentage(1F)
.build(),
entityFactory.rolloutGroup().create().name("Group2").description("Group2desc").targetPercentage(101F)

View File

@@ -54,7 +54,6 @@ import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.bind.annotation.RestController;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Description;
@@ -71,7 +70,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
@Before
public void assertPreparationOfRepo() {
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("no softwaremodule should be founded")
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).as("no softwaremodule should be founded")
.hasSize(0);
}
@@ -87,7 +86,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
final String updateVendor = "newVendor1";
final String updateDescription = "newDescription1";
SoftwareModule sm = softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType)
SoftwareModule sm = softwareModuleManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType)
.name(knownSWName).version(knownSWVersion).description(knownSWDescription).vendor(knownSWVendor));
assertThat(sm.getName()).as("Wrong name of the software module").isEqualTo(knownSWName);
@@ -108,7 +107,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("$.description", equalTo(updateDescription)))
.andExpect(jsonPath("$.name", equalTo(knownSWName))).andReturn();
sm = softwareManagement.findSoftwareModuleById(sm.getId()).get();
sm = softwareModuleManagement.findSoftwareModuleById(sm.getId()).get();
assertThat(sm.getName()).isEqualTo(knownSWName);
assertThat(sm.getVendor()).isEqualTo(updateVendor);
assertThat(sm.getLastModifiedBy()).isEqualTo("smUpdateTester");
@@ -141,7 +140,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
// check rest of response compared to DB
final MgmtArtifact artResult = ResourceUtility
.convertArtifactResponse(mvcResult.getResponse().getContentAsString());
final Long artId = softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getId();
final Long artId = softwareModuleManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getId();
assertThat(artResult.getArtifactId()).as("Wrong artifact id").isEqualTo(artId);
assertThat(JsonPath.compile("$._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.as("Link contains no self url")
@@ -161,7 +160,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
// binary
try (InputStream fileInputStream = artifactManagement
.loadArtifactBinary(
softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getSha1Hash())
softwareModuleManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getSha1Hash())
.get().getFileInputStream()) {
assertTrue("Wrong artifact content",
IOUtils.contentEquals(new ByteArrayInputStream(random), fileInputStream));
@@ -175,14 +174,14 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.isEqualTo(HashGeneratorUtils.generateMD5(random));
// metadata
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getFilename())
assertThat(softwareModuleManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getFilename())
.as("wrong metadata of the filename").isEqualTo("origFilename");
}
@Test
@Description("Verfies that the system does not accept empty artifact uploads. Expected response: BAD REQUEST")
public void emptyUploadArtifact() throws Exception {
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0);
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
@@ -313,7 +312,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
assertTrue("Response has wrong response content",
Arrays.equals(result2.getResponse().getContentAsByteArray(), random));
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(1);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2);
}
@@ -420,7 +419,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
public void invalidRequestsOnSoftwaremodulesResource() throws Exception {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
final List<SoftwareModule> modules = Lists.newArrayList(sm);
final List<SoftwareModule> modules = Arrays.asList(sm);
// SM does not exist
mvc.perform(get("/rest/v1/softwaremodules/12345678")).andDo(MockMvcResultPrinter.print())
@@ -446,7 +445,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
final SoftwareModule toLongName = entityFactory.softwareModule().create().type(osType)
.name(RandomStringUtils.randomAscii(80)).build();
mvc.perform(
post("/rest/v1/softwaremodules").content(JsonBuilder.softwareModules(Lists.newArrayList(toLongName)))
post("/rest/v1/softwaremodules").content(JsonBuilder.softwareModules(Arrays.asList(toLongName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
@@ -551,7 +550,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.self.href",
contains("http://localhost/rest/v1/softwaremodules/" + app.getId())));
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(2);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(2);
}
@Test
@@ -562,7 +561,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
testdataFactory.createSoftwareModuleOs("2");
final SoftwareModule app2 = testdataFactory.createSoftwareModuleApp("2");
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(4);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).hasSize(4);
// only by name, only one exists per name
mvc.perform(get("/rest/v1/softwaremodules?q=name==" + os1.getName()).accept(MediaType.APPLICATION_JSON))
@@ -652,7 +651,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("$._links.artifacts.href",
equalTo("http://localhost/rest/v1/softwaremodules/" + os.getId() + "/artifacts")));
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(1);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(1);
}
@Test
@@ -664,7 +663,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
final SoftwareModule ah = entityFactory.softwareModule().create().name("name3").type(appType)
.version("version3").vendor("vendor3").description("description3").build();
final List<SoftwareModule> modules = Lists.newArrayList(os, ah);
final List<SoftwareModule> modules = Arrays.asList(os, ah);
final long current = System.currentTimeMillis();
@@ -686,9 +685,9 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[1].createdAt", not(equalTo(0)))).andReturn();
final SoftwareModule osCreated = softwareManagement
final SoftwareModule osCreated = softwareModuleManagement
.findSoftwareModuleByNameAndVersion("name1", "version1", osType.getId()).get();
final SoftwareModule appCreated = softwareManagement
final SoftwareModule appCreated = softwareModuleManagement
.findSoftwareModuleByNameAndVersion("name3", "version3", appType.getId()).get();
assertThat(
@@ -707,14 +706,14 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.toString()).as("Response contains invalid artifacts href")
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId() + "/artifacts");
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Wrong softwaremodule size").hasSize(2);
assertThat(softwareManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent().get(0).getName())
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).as("Wrong softwaremodule size").hasSize(2);
assertThat(softwareModuleManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent().get(0).getName())
.as("Softwaremoudle name is wrong").isEqualTo(os.getName());
assertThat(softwareManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent().get(0)
assertThat(softwareModuleManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent().get(0)
.getCreatedBy()).as("Softwaremoudle created by is wrong").isEqualTo("uploadTester");
assertThat(softwareManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent().get(0)
assertThat(softwareModuleManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent().get(0)
.getCreatedAt()).as("Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current);
assertThat(softwareManagement.findSoftwareModulesByType(PAGE, appType.getId()).getContent().get(0).getName())
assertThat(softwareModuleManagement.findSoftwareModulesByType(PAGE, appType.getId()).getContent().get(0).getName())
.as("Softwaremoudle name is wrong").isEqualTo(ah.getName());
}
@@ -728,13 +727,13 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremoudle size is wrong").hasSize(1);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).as("Softwaremoudle size is wrong").hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", sm.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
assertThat(softwareManagement.findSoftwareModulesAll(PAGE))
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE))
.as("After delete no softwarmodule should be available").isEmpty();
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0);
}
@@ -749,7 +748,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
artifactManagement.createArtifact(new ByteArrayInputStream(random),
ds1.findFirstModuleByType(appType).get().getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(3);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).hasSize(3);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(appType).get().getId()))
@@ -760,7 +759,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// all 3 are now marked as deleted
assertThat(softwareManagement.findSoftwareModulesAll(PAGE).getNumber())
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE).getNumber())
.as("After delete no softwarmodule should be available").isEqualTo(0);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
}
@@ -779,9 +778,9 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file2", false);
// check repo before delete
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(1);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).hasSize(1);
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()).hasSize(2);
assertThat(softwareModuleManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()).hasSize(2);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2);
// delete
@@ -789,10 +788,10 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// check that only one artifact is still alive and still assigned
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("After the sm should be marked as deleted")
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).as("After the sm should be marked as deleted")
.hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts())
assertThat(softwareModuleManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts())
.as("After delete artifact should available for marked as deleted sm's").hasSize(1);
}
@@ -820,9 +819,9 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
final SoftwareModuleMetadata metaKey1 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey1)
final SoftwareModuleMetadata metaKey1 = softwareModuleManagement.findSoftwareModuleMetadata(sm.getId(), knownKey1)
.get();
final SoftwareModuleMetadata metaKey2 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey2)
final SoftwareModuleMetadata metaKey2 = softwareModuleManagement.findSoftwareModuleMetadata(sm.getId(), knownKey2)
.get();
assertThat(metaKey1.getValue()).as("Metadata key is wrong").isEqualTo(knownValue1);
@@ -838,7 +837,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
final String updateValue = "valueForUpdate";
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
softwareManagement.createSoftwareModuleMetadata(sm.getId(),
softwareModuleManagement.createSoftwareModuleMetadata(sm.getId(),
entityFactory.generateMetadata(knownKey, knownValue));
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
@@ -849,7 +848,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
final SoftwareModuleMetadata assertDS = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey)
final SoftwareModuleMetadata assertDS = softwareModuleManagement.findSoftwareModuleMetadata(sm.getId(), knownKey)
.get();
assertThat(assertDS.getValue()).as("Metadata is wrong").isEqualTo(updateValue);
}
@@ -862,13 +861,13 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
final String knownValue = "knownValue";
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
softwareManagement.createSoftwareModuleMetadata(sm.getId(),
softwareModuleManagement.createSoftwareModuleMetadata(sm.getId(),
entityFactory.generateMetadata(knownKey, knownValue));
mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey)).isNotPresent();
assertThat(softwareModuleManagement.findSoftwareModuleMetadata(sm.getId(), knownKey)).isNotPresent();
}
@Test
@@ -879,7 +878,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
final String knownValue = "knownValue";
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
softwareManagement.createSoftwareModuleMetadata(sm.getId(),
softwareModuleManagement.createSoftwareModuleMetadata(sm.getId(),
entityFactory.generateMetadata(knownKey, knownValue));
mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/XXX", sm.getId(), knownKey))
@@ -888,7 +887,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
mvc.perform(delete("/rest/v1/softwaremodules/1234/metadata/{key}", knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
assertThat(softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey)).isPresent();
assertThat(softwareModuleManagement.findSoftwareModuleMetadata(sm.getId(), knownKey)).isPresent();
}
@Test
@@ -907,7 +906,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
for (int index = 0; index < totalMetadata; index++) {
softwareManagement.createSoftwareModuleMetadata(sm.getId(),
softwareModuleManagement.createSoftwareModuleMetadata(sm.getId(),
entityFactory.generateMetadata(knownKeyPrefix + index, knownValuePrefix + index));
}
@@ -923,7 +922,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType).name(str)
softwareModuleManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType).name(str)
.description(str).vendor(str).version(str));
character++;
}

View File

@@ -22,6 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
@@ -35,7 +36,6 @@ import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Description;
@@ -90,9 +90,10 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
}
private SoftwareModuleType createTestType() {
SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType()
.create().key("test123").name("TestName123").description("Desc123").maxAssignments(5));
testType = softwareManagement.updateSoftwareModuleType(
SoftwareModuleType testType = softwareModuleTypeManagement
.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test123").name("TestName123")
.description("Desc123").maxAssignments(5));
testType = softwareModuleTypeManagement.updateSoftwareModuleType(
entityFactory.softwareModuleType().update(testType.getId()).description("Desc1234"));
return testType;
}
@@ -162,7 +163,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.")
public void createSoftwareModuleTypes() throws Exception {
final List<SoftwareModuleType> types = Lists.newArrayList(
final List<SoftwareModuleType> types = Arrays.asList(
entityFactory.softwareModuleType().create().key("test1").name("TestName1").description("Desc1")
.colour("col1").maxAssignments(1).build(),
entityFactory.softwareModuleType().create().key("test2").name("TestName2").description("Desc2")
@@ -189,9 +190,9 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
.andExpect(jsonPath("[2].createdAt", not(equalTo(0))))
.andExpect(jsonPath("[2].maxAssignments", equalTo(3))).andReturn();
final SoftwareModuleType created1 = softwareManagement.findSoftwareModuleTypeByKey("test1").get();
final SoftwareModuleType created2 = softwareManagement.findSoftwareModuleTypeByKey("test2").get();
final SoftwareModuleType created3 = softwareManagement.findSoftwareModuleTypeByKey("test3").get();
final SoftwareModuleType created1 = softwareModuleTypeManagement.findSoftwareModuleTypeByKey("test1").get();
final SoftwareModuleType created2 = softwareModuleTypeManagement.findSoftwareModuleTypeByKey("test2").get();
final SoftwareModuleType created3 = softwareModuleTypeManagement.findSoftwareModuleTypeByKey("test3").get();
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
@@ -203,7 +204,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created3.getId());
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(6);
assertThat(softwareModuleTypeManagement.countSoftwareModuleTypesAll()).isEqualTo(6);
}
@Test
@@ -230,12 +231,12 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
public void deleteSoftwareModuleTypeUnused() throws Exception {
final SoftwareModuleType testType = createTestType();
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
assertThat(softwareModuleTypeManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
assertThat(softwareModuleTypeManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
}
@Test
@@ -250,15 +251,15 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).")
public void deleteSoftwareModuleTypeUsed() throws Exception {
final SoftwareModuleType testType = createTestType();
softwareManagement.createSoftwareModule(
softwareModuleManagement.createSoftwareModule(
entityFactory.softwareModule().create().type(testType).name("name").version("version"));
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
assertThat(softwareModuleTypeManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
assertThat(softwareModuleTypeManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
}
@Test
@@ -321,7 +322,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception {
final SoftwareModuleType testType = createTestType();
final List<SoftwareModuleType> types = Lists.newArrayList(testType);
final List<SoftwareModuleType> types = Arrays.asList(testType);
// SM does not exist
mvc.perform(get("/rest/v1/softwaremoduletypes/12345678")).andDo(MockMvcResultPrinter.print())
@@ -347,10 +348,10 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
final SoftwareModuleType toLongName = entityFactory.softwareModuleType().create().key("test123")
.name(RandomStringUtils.randomAscii(80)).build();
mvc.perform(post("/rest/v1/softwaremoduletypes")
.content(JsonBuilder.softwareModuleTypes(Lists.newArrayList(toLongName)))
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
mvc.perform(
post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypes(Arrays.asList(toLongName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
// unsupported media type
mvc.perform(post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypes(types))
@@ -369,10 +370,10 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
@Test
@Description("Search erquest of software module types.")
public void searchSoftwareModuleTypeRsql() throws Exception {
softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test123")
softwareModuleTypeManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test123")
.name("TestName123").description("Desc123").maxAssignments(5));
softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test1234")
.name("TestName1234").description("Desc1234").maxAssignments(5));
softwareModuleTypeManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create()
.key("test1234").name("TestName1234").description("Desc1234").maxAssignments(5));
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
@@ -387,7 +388,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType).name(str)
softwareModuleManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType).name(str)
.description(str).vendor(str).version(str));
character++;
}

View File

@@ -24,6 +24,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -59,7 +60,6 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Description;
@@ -192,7 +192,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
final DistributionSet dsA = testdataFactory.createDistributionSet("");
final Target createTarget = testdataFactory.createTarget("knownTargetId");
assignDistributionSet(dsA, Lists.newArrayList(createTarget));
assignDistributionSet(dsA, Arrays.asList(createTarget));
final String rsqlPendingStatus = "status==pending";
final String rsqlFinishedStatus = "status==finished";
@@ -230,8 +230,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNoContent());
final Action action = deploymentManagement.findAction(
deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE).getContent().get(0).getId())
.get();
deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE).getContent().get(0).getId()).get();
// still active because in "canceling" state and waiting for controller
// feedback
assertThat(action.isActive()).isTrue();
@@ -695,7 +694,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.build();
final MvcResult mvcResult = mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING)
.content(JsonBuilder.targets(Lists.newArrayList(test1), true)).contentType(MediaType.APPLICATION_JSON))
.content(JsonBuilder.targets(Arrays.asList(test1), true)).contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();
assertThat(targetManagement.countTargetsAll()).isEqualTo(0);
@@ -717,7 +716,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
final Target test3 = entityFactory.target().create().controllerId("id3").name("testname3")
.description("testid3").build();
final List<Target> targets = Lists.newArrayList(test1, test2, test3);
final List<Target> targets = Arrays.asList(test1, test2, test3);
final MvcResult mvcResult = mvc
.perform(post("/rest/v1/targets/").content(JsonBuilder.targets(targets, true))
@@ -1044,7 +1043,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
throws InterruptedException {
final Target target = testdataFactory.createTarget(knownTargetId);
final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = Arrays.asList(target);
final Iterator<DistributionSet> sets = testdataFactory.createDistributionSets(2).iterator();
final DistributionSet one = sets.next();
@@ -1300,7 +1299,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
final DistributionSet dsA = testdataFactory.createDistributionSet("");
final Target tA = testdataFactory.createTarget("target-id-A");
// assign a distribution set so we get an active update action
assignDistributionSet(dsA, Lists.newArrayList(tA));
assignDistributionSet(dsA, Arrays.asList(tA));
// verify active action
final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE);
assertThat(actionsByTarget.getContent()).hasSize(1);

View File

@@ -63,5 +63,10 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -10,7 +10,6 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.validation.constraints.NotNull;

View File

@@ -16,8 +16,6 @@ import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeUpdate;
import org.eclipse.hawkbit.repository.builder.DistributionSetUpdate;
import org.eclipse.hawkbit.repository.exception.DistributionSetCreationFailedMissingMandatoryModuleException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
@@ -33,10 +31,8 @@ import org.eclipse.hawkbit.repository.model.DistributionSetFilter.DistributionSe
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
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.model.Tag;
import org.eclipse.hawkbit.repository.model.Target;
import org.hibernate.validator.constraints.NotEmpty;
@@ -101,27 +97,6 @@ public interface DistributionSetManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetsAll();
/**
* Count all {@link DistributionSet}s in the repository that are not marked
* as deleted.
*
* @param typeId
* to look for
*
* @return number of {@link DistributionSet}s
*
* @throws EntityNotFoundException
* if type with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetsByType(@NotNull Long typeId);
/**
* @return number of {@link DistributionSetType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetTypesAll();
/**
* Creates a new {@link DistributionSet}.
*
@@ -177,36 +152,6 @@ public interface DistributionSetManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<DistributionSet> createDistributionSets(@NotNull Collection<DistributionSetCreate> creates);
/**
* Creates new {@link DistributionSetType}.
*
* @param create
* to create
* @return created entity
*
* @throws EntityNotFoundException
* if a provided linked entity does not exists (
* {@link DistributionSetType#getMandatoryModuleTypes()} or
* {@link DistributionSetType#getOptionalModuleTypes()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
DistributionSetType createDistributionSetType(@NotNull DistributionSetTypeCreate create);
/**
* Creates multiple {@link DistributionSetType}s.
*
* @param creates
* to create
* @return created entity
*
* @throws EntityNotFoundException
* if a provided linked entity does not exists (
* {@link DistributionSetType#getMandatoryModuleTypes()} or
* {@link DistributionSetType#getOptionalModuleTypes()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<DistributionSetType> createDistributionSetTypes(@NotNull Collection<DistributionSetTypeCreate> creates);
/**
* <p>
* {@link DistributionSet} can be deleted/erased from the repository if they
@@ -257,18 +202,6 @@ public interface DistributionSetManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
void deleteDistributionSetMetadata(@NotNull final Long dsId, @NotEmpty final String key);
/**
* Deletes or mark as delete in case the type is in use.
*
* @param typeId
* to delete
*
* @throws EntityNotFoundException
* if given set does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSetType(@NotNull Long typeId);
/**
* retrieves the distribution set for a given action.
*
@@ -501,58 +434,6 @@ public interface DistributionSetManagement {
Page<DistributionSet> findDistributionSetsByTag(@NotNull final Pageable pageable, @NotNull String rsqlParam,
@NotNull final Long tagId);
/**
* @param id
* as {@link DistributionSetType#getId()}
* @return {@link DistributionSetType}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<DistributionSetType> findDistributionSetTypeById(@NotNull Long id);
/**
* @param key
* as {@link DistributionSetType#getKey()}
* @return {@link DistributionSetType}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<DistributionSetType> findDistributionSetTypeByKey(@NotEmpty String key);
/**
* @param name
* as {@link DistributionSetType#getName()}
* @return {@link DistributionSetType}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<DistributionSetType> findDistributionSetTypeByName(@NotEmpty String name);
/**
* @param pageable
* parameter
* @return all {@link DistributionSetType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetType> findDistributionSetTypesAll(@NotNull Pageable pageable);
/**
* Generic predicate based query for {@link DistributionSetType}.
*
* @param rsqlParam
* rsql query string
* @param pageable
* parameter for paging
*
* @return the found {@link SoftwareModuleType}s
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetType> findDistributionSetTypesAll(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* finds a single distribution set meta data by its id.
*
@@ -668,90 +549,6 @@ public interface DistributionSetManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetMetadata updateDistributionSetMetadata(@NotNull Long dsId, @NotNull MetaData md);
/**
* Updates existing {@link DistributionSetType}. Resets assigned
* {@link SoftwareModuleType}s as well and sets as provided.
*
* @param update
* to update
*
* @return updated entity
*
* @throws EntityNotFoundException
* in case the {@link DistributionSetType} does not exists and
* cannot be updated
*
* @throws EntityReadOnlyException
* if the {@link DistributionSetType} is already in use by a
* {@link DistributionSet} and user tries to change list of
* {@link SoftwareModuleType}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType updateDistributionSetType(@NotNull DistributionSetTypeUpdate update);
/**
* Unassigns a {@link SoftwareModuleType} from the
* {@link DistributionSetType}. Does nothing if {@link SoftwareModuleType}
* has not been assigned in the first place.
*
* @param dsTypeId
* to update
* @param softwareModuleId
* to unassign
* @return updated {@link DistributionSetType}
*
* @throws EntityNotFoundException
* in case the {@link DistributionSetType} does not exist
*
* @throws EntityReadOnlyException
* if the {@link DistributionSetType} while it is already in use
* by a {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType unassignSoftwareModuleType(@NotNull Long dsTypeId, @NotNull Long softwareModuleId);
/**
* Assigns {@link DistributionSetType#getMandatoryModuleTypes()}.
*
* @param dsTypeId
* to update
* @param softwareModuleTypeIds
* to assign
* @return updated {@link DistributionSetType}
*
* @throws EntityNotFoundException
* in case the {@link DistributionSetType} or at least one of
* the {@link SoftwareModuleType}s do not exist
*
* @throws EntityReadOnlyException
* if the {@link DistributionSetType} while it is already in use
* by a {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType assignOptionalSoftwareModuleTypes(@NotNull Long dsTypeId,
@NotEmpty Collection<Long> softwareModuleTypeIds);
/**
* Assigns {@link DistributionSetType#getOptionalModuleTypes()}.
*
* @param dsTypeId
* to update
* @param softwareModuleTypes
* to assign
* @return updated {@link DistributionSetType}
*
* @throws EntityNotFoundException
* in case the {@link DistributionSetType} or at least one of
* the {@link SoftwareModuleType}s do not exist
*
* @throws EntityReadOnlyException
* if the {@link DistributionSetType} while it is already in use
* by a {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType assignMandatorySoftwareModuleTypes(@NotNull Long dsTypeId,
@NotEmpty Collection<Long> softwareModuleTypes);
/**
* Retrieves all distribution set without details.
*

View File

@@ -0,0 +1,237 @@
/**
* 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;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeUpdate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Management service for {@link DistributionSetType}s.
*
*/
public interface DistributionSetTypeManagement {
/**
* Creates new {@link DistributionSetType}.
*
* @param create
* to create
* @return created entity
*
* @throws EntityNotFoundException
* if a provided linked entity does not exists (
* {@link DistributionSetType#getMandatoryModuleTypes()} or
* {@link DistributionSetType#getOptionalModuleTypes()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
DistributionSetType createDistributionSetType(@NotNull DistributionSetTypeCreate create);
/**
* Creates multiple {@link DistributionSetType}s.
*
* @param creates
* to create
* @return created entity
*
* @throws EntityNotFoundException
* if a provided linked entity does not exists (
* {@link DistributionSetType#getMandatoryModuleTypes()} or
* {@link DistributionSetType#getOptionalModuleTypes()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<DistributionSetType> createDistributionSetTypes(@NotNull Collection<DistributionSetTypeCreate> creates);
/**
* Count all {@link DistributionSet}s in the repository that are not marked
* as deleted.
*
* @param typeId
* to look for
*
* @return number of {@link DistributionSet}s
*
* @throws EntityNotFoundException
* if type with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetsByType(@NotNull Long typeId);
/**
* Deletes or mark as delete in case the type is in use.
*
* @param typeId
* to delete
*
* @throws EntityNotFoundException
* if given set does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSetType(@NotNull Long typeId);
/**
* @param key
* as {@link DistributionSetType#getKey()}
* @return {@link DistributionSetType}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<DistributionSetType> findDistributionSetTypeByKey(@NotEmpty String key);
/**
* @param name
* as {@link DistributionSetType#getName()}
* @return {@link DistributionSetType}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<DistributionSetType> findDistributionSetTypeByName(@NotEmpty String name);
/**
* @param pageable
* parameter
* @return all {@link DistributionSetType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetType> findDistributionSetTypesAll(@NotNull Pageable pageable);
/**
* Generic predicate based query for {@link DistributionSetType}.
*
* @param rsqlParam
* rsql query string
* @param pageable
* parameter for paging
*
* @return the found {@link SoftwareModuleType}s
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetType> findDistributionSetTypesAll(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* @param id
* as {@link DistributionSetType#getId()}
* @return {@link DistributionSetType}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<DistributionSetType> findDistributionSetTypeById(@NotNull Long id);
/**
* Updates existing {@link DistributionSetType}. Resets assigned
* {@link SoftwareModuleType}s as well and sets as provided.
*
* @param update
* to update
*
* @return updated entity
*
* @throws EntityNotFoundException
* in case the {@link DistributionSetType} does not exists and
* cannot be updated
*
* @throws EntityReadOnlyException
* if the {@link DistributionSetType} is already in use by a
* {@link DistributionSet} and user tries to change list of
* {@link SoftwareModuleType}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType updateDistributionSetType(@NotNull DistributionSetTypeUpdate update);
/**
* Assigns {@link DistributionSetType#getMandatoryModuleTypes()}.
*
* @param dsTypeId
* to update
* @param softwareModuleTypeIds
* to assign
* @return updated {@link DistributionSetType}
*
* @throws EntityNotFoundException
* in case the {@link DistributionSetType} or at least one of
* the {@link SoftwareModuleType}s do not exist
*
* @throws EntityReadOnlyException
* if the {@link DistributionSetType} while it is already in use
* by a {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType assignOptionalSoftwareModuleTypes(@NotNull Long dsTypeId,
@NotEmpty Collection<Long> softwareModuleTypeIds);
/**
* Assigns {@link DistributionSetType#getOptionalModuleTypes()}.
*
* @param dsTypeId
* to update
* @param softwareModuleTypes
* to assign
* @return updated {@link DistributionSetType}
*
* @throws EntityNotFoundException
* in case the {@link DistributionSetType} or at least one of
* the {@link SoftwareModuleType}s do not exist
*
* @throws EntityReadOnlyException
* if the {@link DistributionSetType} while it is already in use
* by a {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType assignMandatorySoftwareModuleTypes(@NotNull Long dsTypeId,
@NotEmpty Collection<Long> softwareModuleTypes);
/**
* Unassigns a {@link SoftwareModuleType} from the
* {@link DistributionSetType}. Does nothing if {@link SoftwareModuleType}
* has not been assigned in the first place.
*
* @param dsTypeId
* to update
* @param softwareModuleId
* to unassign
* @return updated {@link DistributionSetType}
*
* @throws EntityNotFoundException
* in case the {@link DistributionSetType} does not exist
*
* @throws EntityReadOnlyException
* if the {@link DistributionSetType} while it is already in use
* by a {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType unassignSoftwareModuleType(@NotNull Long dsTypeId, @NotNull Long softwareModuleId);
/**
* @return number of {@link DistributionSetType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetTypesAll();
}

View File

@@ -16,8 +16,6 @@ import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeUpdate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleUpdate;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
@@ -39,7 +37,7 @@ import org.springframework.security.access.prepost.PreAuthorize;
* Service for managing {@link SoftwareModule}s.
*
*/
public interface SoftwareManagement {
public interface SoftwareModuleManagement {
/**
* Counts {@link SoftwareModule}s with given
@@ -67,12 +65,6 @@ public interface SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countSoftwareModulesAll();
/**
* @return number of {@link SoftwareModuleType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countSoftwareModuleTypesAll();
/**
* Create {@link SoftwareModule}s in the repository.
*
@@ -137,26 +129,6 @@ public interface SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull Long moduleId, @NotNull MetaData metadata);
/**
* Creates multiple {@link SoftwareModuleType}s.
*
* @param creates
* to create
* @return created Entity
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<SoftwareModuleType> createSoftwareModuleType(@NotNull Collection<SoftwareModuleTypeCreate> creates);
/**
* Creates new {@link SoftwareModuleType}.
*
* @param create
* to create
* @return created Entity
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
SoftwareModuleType createSoftwareModuleType(@NotNull SoftwareModuleTypeCreate create);
/**
* Deletes the given {@link SoftwareModule} Entity.
*
@@ -192,18 +164,6 @@ public interface SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModules(@NotNull Collection<Long> moduleIds);
/**
* Deletes or marks as delete in case the type is in use.
*
* @param typeId
* to delete
*
* @throws EntityNotFoundException
* not found is type with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModuleType(@NotNull Long typeId);
/**
* @param pageable
* the page request to page the result set
@@ -433,62 +393,6 @@ public interface SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice<SoftwareModule> findSoftwareModulesByType(@NotNull Pageable pageable, @NotNull Long typeId);
/**
*
* @param id
* to search for
* @return {@link SoftwareModuleType} in the repository with given
* {@link SoftwareModuleType#getId()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<SoftwareModuleType> findSoftwareModuleTypeById(@NotNull Long id);
/**
*
* @param key
* to search for
* @return {@link SoftwareModuleType} in the repository with given
* {@link SoftwareModuleType#getKey()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<SoftwareModuleType> findSoftwareModuleTypeByKey(@NotEmpty String key);
/**
*
* @param name
* to search for
* @return all {@link SoftwareModuleType}s in the repository with given
* {@link SoftwareModuleType#getName()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<SoftwareModuleType> findSoftwareModuleTypeByName(@NotEmpty String name);
/**
* @param pageable
* parameter
* @return all {@link SoftwareModuleType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleType> findSoftwareModuleTypesAll(@NotNull Pageable pageable);
/**
* Retrieves all {@link SoftwareModuleType}s with a given specification.
*
* @param rsqlParam
* filter definition in RSQL syntax
* @param pageable
* pagination parameter
* @return the found {@link SoftwareModuleType}s
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleType> findSoftwareModuleTypesAll(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* Updates existing {@link SoftwareModule}. Update-able values are
* {@link SoftwareModule#getDescription()}
@@ -524,19 +428,4 @@ public interface SoftwareManagement {
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleMetadata updateSoftwareModuleMetadata(@NotNull Long moduleId, @NotNull MetaData metadata);
/**
* Updates existing {@link SoftwareModuleType}.
*
* @param update
* to update
*
* @return updated Entity
*
* @throws EntityNotFoundException
* in case the {@link SoftwareModuleType} does not exists and
* cannot be updated
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleType updateSoftwareModuleType(@NotNull SoftwareModuleTypeUpdate update);
}

View File

@@ -0,0 +1,144 @@
/**
* 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;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeUpdate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Service for managing {@link SoftwareModuleType}s.
*
*/
public interface SoftwareModuleTypeManagement {
/**
* @return number of {@link SoftwareModuleType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countSoftwareModuleTypesAll();
/**
* Creates multiple {@link SoftwareModuleType}s.
*
* @param creates
* to create
* @return created Entity
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<SoftwareModuleType> createSoftwareModuleType(@NotNull Collection<SoftwareModuleTypeCreate> creates);
/**
* Creates new {@link SoftwareModuleType}.
*
* @param create
* to create
* @return created Entity
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
SoftwareModuleType createSoftwareModuleType(@NotNull SoftwareModuleTypeCreate create);
/**
* Deletes or marks as delete in case the type is in use.
*
* @param typeId
* to delete
*
* @throws EntityNotFoundException
* not found is type with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModuleType(@NotNull Long typeId);
/**
*
* @param id
* to search for
* @return {@link SoftwareModuleType} in the repository with given
* {@link SoftwareModuleType#getId()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<SoftwareModuleType> findSoftwareModuleTypeById(@NotNull Long id);
/**
*
* @param key
* to search for
* @return {@link SoftwareModuleType} in the repository with given
* {@link SoftwareModuleType#getKey()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<SoftwareModuleType> findSoftwareModuleTypeByKey(@NotEmpty String key);
/**
*
* @param name
* to search for
* @return all {@link SoftwareModuleType}s in the repository with given
* {@link SoftwareModuleType#getName()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Optional<SoftwareModuleType> findSoftwareModuleTypeByName(@NotEmpty String name);
/**
* @param pageable
* parameter
* @return all {@link SoftwareModuleType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleType> findSoftwareModuleTypesAll(@NotNull Pageable pageable);
/**
* Retrieves all {@link SoftwareModuleType}s with a given specification.
*
* @param rsqlParam
* filter definition in RSQL syntax
* @param pageable
* pagination parameter
* @return the found {@link SoftwareModuleType}s
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleType> findSoftwareModuleTypesAll(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* Updates existing {@link SoftwareModuleType}.
*
* @param update
* to update
*
* @return updated Entity
*
* @throws EntityNotFoundException
* in case the {@link SoftwareModuleType} does not exists and
* cannot be updated
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleType updateSoftwareModuleType(@NotNull SoftwareModuleTypeUpdate update);
}

View File

@@ -8,6 +8,7 @@
*/
package org.eclipse.hawkbit.repository.builder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
@@ -16,8 +17,6 @@ import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.hibernate.validator.constraints.NotEmpty;
import com.google.common.collect.Lists;
/**
* Builder to create a new {@link DistributionSetType} entry. Defines all fields
* that can be set at creation time. Other fields are set by the repository
@@ -67,7 +66,7 @@ public interface DistributionSetTypeCreate {
* @return updated builder instance
*/
default DistributionSetTypeCreate mandatory(final Long mandatory) {
return mandatory(Lists.newArrayList(mandatory));
return mandatory(Arrays.asList(mandatory));
}
/**
@@ -92,7 +91,7 @@ public interface DistributionSetTypeCreate {
* @return updated builder instance
*/
default DistributionSetTypeCreate optional(final Long optional) {
return optional(Lists.newArrayList(optional));
return optional(Arrays.asList(optional));
}
/**

View File

@@ -0,0 +1,45 @@
/**
* 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.event.remote;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
/**
*
* Defines the remote event of deleting a {@link RolloutGroup}.
*/
public class RolloutGroupDeletedEvent extends RemoteIdEvent {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public RolloutGroupDeletedEvent() {
// for serialization libs like jackson
}
/**
* Constructor for json serialization.
*
* @param tenant
* the tenant
* @param entityId
* the entity id
* @param entityClass
* the entity class
* @param applicationId
* the origin application id
*/
public RolloutGroupDeletedEvent(final String tenant, final Long entityId, final String entityClass,
final String applicationId) {
super(entityId, tenant, entityClass, applicationId);
}
}

View File

@@ -8,7 +8,6 @@
*/
package org.eclipse.hawkbit.repository.event.remote.entity;
import org.apache.commons.lang3.ClassUtils;
import org.eclipse.hawkbit.repository.event.remote.EventEntityManagerHolder;
import org.eclipse.hawkbit.repository.event.remote.RemoteIdEvent;
import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
@@ -63,7 +62,7 @@ public class RemoteEntityEvent<E extends TenantAwareBaseEntity> extends RemoteId
@SuppressWarnings("unchecked")
private E reloadEntityFromRepository() {
try {
final Class<E> clazz = (Class<E>) ClassUtils.getClass(getEntityClass());
final Class<E> clazz = (Class<E>) Class.forName(getEntityClass());
return EventEntityManagerHolder.getInstance().getEventEntityManager().findEntity(getTenant(), getEntityId(),
clazz);
} catch (final ClassNotFoundException e) {

View File

@@ -10,8 +10,6 @@ package org.eclipse.hawkbit.repository.model;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import com.google.common.io.BaseEncoding;
/**
* Binaries for a {@link SoftwareModule} Note: the decision which artifacts have
* to be downloaded are done on the device side. e.g. Full Package, Signatures,
@@ -35,8 +33,8 @@ public interface Artifact extends TenantAwareBaseEntity {
String getMd5Hash();
/**
* @return SHA-1 hash of the artifact in {@link BaseEncoding#base16()}
* format that identifies the {@link DbArtifact} in the system.
* @return SHA-1 hash of the artifact in Base16 format that identifies the
* {@link DbArtifact} in the system.
*/
String getSha1Hash();

View File

@@ -9,10 +9,9 @@
package org.eclipse.hawkbit.repository.report.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.common.collect.ImmutableList;
/**
* Bean for holding the system usage stats.
*
@@ -89,7 +88,7 @@ public class SystemUsageReport {
* @return tenant data
*/
public List<TenantUsage> getTenants() {
return ImmutableList.copyOf(tenants);
return Collections.unmodifiableList(tenants);
}
}

View File

@@ -9,10 +9,9 @@
package org.eclipse.hawkbit.repository.report.model;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.google.common.collect.Maps;
/**
* System usage stats element for a tenant.
*
@@ -58,7 +57,7 @@ public class TenantUsage {
private Map<String, String> getLazyUsageData() {
if (usageData == null) {
usageData = Maps.newHashMap();
usageData = new HashMap<>();
}
return usageData;
}

View File

@@ -24,6 +24,10 @@
<artifactId>hawkbit-repository-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>

View File

@@ -16,6 +16,7 @@ import org.eclipse.hawkbit.repository.event.remote.DistributionSetDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.DistributionSetTagDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.DownloadProgressEvent;
import org.eclipse.hawkbit.repository.event.remote.RolloutDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.RolloutGroupDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.SoftwareModuleDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.event.remote.TargetDeletedEvent;
@@ -99,6 +100,7 @@ public class EventType {
TYPES.put(24, TargetPollEvent.class);
TYPES.put(25, RolloutDeletedEvent.class);
TYPES.put(26, RolloutGroupDeletedEvent.class);
}
private int value;

View File

@@ -12,12 +12,12 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.hawkbit.repository.exception.ConstraintViolationException;
import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
import org.springframework.util.StringUtils;
/**
* A collection of static helper methods for the {@link RolloutManagement}
@@ -193,14 +193,14 @@ public final class RolloutHelper {
return concatAndTargetFilters(baseFilter, groupFilter);
}
final String previousGroupFilters = getAllGroupsTargetFilter(groups);
if (StringUtils.isNotEmpty(previousGroupFilters)) {
if (StringUtils.isNotEmpty(groupFilter)) {
if (!StringUtils.isEmpty(previousGroupFilters)) {
if (!StringUtils.isEmpty(groupFilter)) {
return concatAndTargetFilters(baseFilter, groupFilter, previousGroupFilters);
} else {
return concatAndTargetFilters(baseFilter, previousGroupFilters);
}
}
if (StringUtils.isNotEmpty(groupFilter)) {
if (!StringUtils.isEmpty(groupFilter)) {
return concatAndTargetFilters(baseFilter, groupFilter);
} else {
return baseFilter;
@@ -208,8 +208,8 @@ public final class RolloutHelper {
}
private static boolean isTargetFilterInGroups(final String groupFilter, final List<RolloutGroup> groups) {
return StringUtils.isNotEmpty(groupFilter)
&& groups.stream().anyMatch(prevGroup -> StringUtils.isNotEmpty(prevGroup.getTargetFilterQuery())
return !StringUtils.isEmpty(groupFilter)
&& groups.stream().anyMatch(prevGroup -> !StringUtils.isEmpty(prevGroup.getTargetFilterQuery())
&& prevGroup.getTargetFilterQuery().equals(groupFilter));
}

View File

@@ -16,6 +16,8 @@ import java.util.stream.Collectors;
import org.eclipse.hawkbit.cache.TenancyCacheManager;
import org.eclipse.hawkbit.cache.TenantAwareCacheManager;
import org.eclipse.hawkbit.repository.event.remote.RolloutDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.RolloutGroupDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.AbstractActionEvent;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
@@ -214,6 +216,18 @@ public class RolloutStatusCache {
cache.evict(event.getRolloutGroupId());
}
@EventListener(classes = RolloutDeletedEvent.class)
void invalidateCachedTotalTargetCountOnRolloutDelete(final RolloutDeletedEvent event) {
final Cache cache = tenantAware.runAsTenant(event.getTenant(), () -> cacheManager.getCache(CACHE_RO_NAME));
cache.evict(event.getEntityId());
}
@EventListener(classes = RolloutGroupDeletedEvent.class)
void invalidateCachedTotalTargetCountOnRolloutGroupDelete(final RolloutGroupDeletedEvent event) {
final Cache cache = tenantAware.runAsTenant(event.getTenant(), () -> cacheManager.getCache(CACHE_GR_NAME));
cache.evict(event.getEntityId());
}
private static final class CachedTotalTargetCountActionStatus {
private final long rolloutId;
private final List<TotalTargetCountActionStatus> status;

View File

@@ -51,10 +51,6 @@
<artifactId>hawkbit-artifact-repository-filesystem</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
@@ -75,6 +71,10 @@
<groupId>cz.jirutka.rsql</groupId>
<artifactId>rsql-parser</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<!-- Test -->
<dependency>

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@@ -20,22 +21,19 @@ import javax.persistence.EntityManager;
import org.eclipse.hawkbit.repository.DistributionSetFields;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.DistributionSetMetadataFields;
import org.eclipse.hawkbit.repository.DistributionSetTypeFields;
import org.eclipse.hawkbit.repository.DistributionSetTypeManagement;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.TagManagement;
import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeUpdate;
import org.eclipse.hawkbit.repository.builder.DistributionSetUpdate;
import org.eclipse.hawkbit.repository.builder.GenericDistributionSetTypeUpdate;
import org.eclipse.hawkbit.repository.builder.GenericDistributionSetUpdate;
import org.eclipse.hawkbit.repository.event.remote.DistributionSetDeletedEvent;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.jpa.builder.JpaDistributionSetCreate;
import org.eclipse.hawkbit.repository.jpa.builder.JpaDistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.jpa.configuration.Constants;
import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor;
import org.eclipse.hawkbit.repository.jpa.model.DsMetadataCompositeKey;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata;
@@ -43,10 +41,8 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType;
import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetSpecification;
import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetTypeSpecification;
import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -58,7 +54,6 @@ import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
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.tenancy.TenantAware;
import org.springframework.beans.factory.annotation.Autowired;
@@ -73,9 +68,9 @@ import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
/**
@@ -99,7 +94,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
private SystemManagement systemManagement;
@Autowired
private DistributionSetTypeRepository distributionSetTypeRepository;
private DistributionSetTypeManagement distributionSetTypeManagement;
@Autowired
private DistributionSetMetadataRepository distributionSetMetadataRepository;
@@ -126,10 +121,10 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
private SoftwareModuleRepository softwareModuleRepository;
@Autowired
private SoftwareModuleTypeRepository softwareModuleTypeRepository;
private DistributionSetTagRepository distributionSetTagRepository;
@Autowired
private DistributionSetTagRepository distributionSetTagRepository;
private AfterTransactionCommitExecutor afterCommit;
@Override
public Optional<DistributionSet> findDistributionSetByIdWithDetails(final Long distid) {
@@ -210,7 +205,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
}
if (update.getType() != null) {
final DistributionSetType type = findDistributionSetTypeWithExceptionIfNotFound(update.getType());
final DistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(update.getType());
if (!type.getId().equals(set.getType().getId())) {
checkDistributionSetIsAssignedToTargets(update.getId());
@@ -221,14 +216,9 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
return distributionSetRepository.save(set);
}
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) {
return findDistributionSetTypeByKey(distributionSetTypekey)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypekey));
}
private JpaDistributionSetType findDistributionSetTypeAndThrowExceptionIfNotFound(final Long setId) {
return (JpaDistributionSetType) findDistributionSetTypeById(setId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, setId));
private JpaDistributionSetType findDistributionSetTypeAndThrowExceptionIfNotFound(final String key) {
return (JpaDistributionSetType) distributionSetTypeManagement.findDistributionSetTypeByKey(key)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, key));
}
@@ -276,9 +266,9 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
distributionSetRepository.deleteByIdIn(toHardDelete);
}
distributionSetIDs.forEach(
afterCommit.afterCommit(() -> distributionSetIDs.forEach(
dsId -> eventPublisher.publishEvent(new DistributionSetDeletedEvent(tenantAware.getCurrentTenant(),
dsId, JpaDistributionSet.class.getName(), applicationContext.getId())));
dsId, JpaDistributionSet.class.getName(), applicationContext.getId()))));
}
@Override
@@ -338,117 +328,6 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
return distributionSetRepository.save(set);
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType updateDistributionSetType(final DistributionSetTypeUpdate u) {
final GenericDistributionSetTypeUpdate update = (GenericDistributionSetTypeUpdate) u;
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(update.getId());
update.getDescription().ifPresent(type::setDescription);
update.getColour().ifPresent(type::setColour);
if (hasModules(update)) {
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(update.getId());
update.getMandatory().ifPresent(
mand -> softwareModuleTypeRepository.findByIdIn(mand).forEach(type::addMandatoryModuleType));
update.getOptional().ifPresent(
opt -> softwareModuleTypeRepository.findByIdIn(opt).forEach(type::addOptionalModuleType));
}
return distributionSetTypeRepository.save(type);
}
private static boolean hasModules(final GenericDistributionSetTypeUpdate update) {
return update.getOptional().isPresent() || update.getMandatory().isPresent();
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType assignMandatorySoftwareModuleTypes(final Long dsTypeId,
final Collection<Long> softwareModulesTypeIds) {
final Collection<JpaSoftwareModuleType> modules = softwareModuleTypeRepository
.findByIdIn(softwareModulesTypeIds);
if (modules.size() < softwareModulesTypeIds.size()) {
throw new EntityNotFoundException(SoftwareModuleType.class, softwareModulesTypeIds,
modules.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()));
}
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
modules.forEach(type::addMandatoryModuleType);
return distributionSetTypeRepository.save(type);
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType assignOptionalSoftwareModuleTypes(final Long dsTypeId,
final Collection<Long> softwareModulesTypeIds) {
final Collection<JpaSoftwareModuleType> modules = softwareModuleTypeRepository
.findByIdIn(softwareModulesTypeIds);
if (modules.size() < softwareModulesTypeIds.size()) {
throw new EntityNotFoundException(SoftwareModuleType.class, softwareModulesTypeIds,
modules.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()));
}
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
modules.forEach(type::addOptionalModuleType);
return distributionSetTypeRepository.save(type);
}
private void checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(final Long type) {
if (distributionSetRepository.countByTypeId(type) > 0) {
throw new EntityReadOnlyException(String.format(
"distribution set type %s is already assigned to distribution sets and cannot be changed", type));
}
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType unassignSoftwareModuleType(final Long dsTypeId, final Long softwareModuleTypeId) {
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
type.removeModuleType(softwareModuleTypeId);
return distributionSetTypeRepository.save(type);
}
@Override
public Page<DistributionSetType> findDistributionSetTypesAll(final String rsqlParam, final Pageable pageable) {
final Specification<JpaDistributionSetType> spec = RSQLUtility.parse(rsqlParam, DistributionSetTypeFields.class,
virtualPropertyReplacer);
return convertDsTPage(distributionSetTypeRepository.findAll(spec, pageable));
}
private static Page<DistributionSetType> convertDsTPage(final Page<JpaDistributionSetType> findAll) {
return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()));
}
@Override
public Page<DistributionSetType> findDistributionSetTypesAll(final Pageable pageable) {
return convertDsTPage(distributionSetTypeRepository.findByDeleted(pageable, false));
}
@Override
public Page<DistributionSet> findDistributionSetsByFilters(final Pageable pageable,
final DistributionSetFilter distributionSetFilter) {
@@ -579,56 +458,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
public Long countDistributionSetsAll() {
final Specification<JpaDistributionSet> spec = DistributionSetSpecification.isDeleted(Boolean.FALSE);
return distributionSetRepository.count(SpecificationsBuilder.combineWithAnd(Lists.newArrayList(spec)));
}
@Override
public Long countDistributionSetTypesAll() {
return distributionSetTypeRepository.countByDeleted(false);
}
@Override
public Optional<DistributionSetType> findDistributionSetTypeByName(final String name) {
return Optional
.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name)));
}
@Override
public Optional<DistributionSetType> findDistributionSetTypeById(final Long typeId) {
return Optional
.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(typeId)));
}
@Override
public Optional<DistributionSetType> findDistributionSetTypeByKey(final String key) {
return Optional.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key)));
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType createDistributionSetType(final DistributionSetTypeCreate c) {
final JpaDistributionSetTypeCreate create = (JpaDistributionSetTypeCreate) c;
return distributionSetTypeRepository.save(create.build());
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public void deleteDistributionSetType(final Long typeId) {
final JpaDistributionSetType toDelete = distributionSetTypeRepository.findById(typeId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, typeId));
if (distributionSetRepository.countByTypeId(typeId) > 0) {
toDelete.setDeleted(true);
distributionSetTypeRepository.save(toDelete);
} else {
distributionSetTypeRepository.delete(typeId);
}
return distributionSetRepository.count(SpecificationsBuilder.combineWithAnd(Arrays.asList(spec)));
}
@Override
@@ -788,7 +618,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
specList.add(spec);
}
if (!Strings.isNullOrEmpty(distributionSetFilter.getSearchText())) {
if (!StringUtils.isEmpty(distributionSetFilter.getSearchText())) {
spec = DistributionSetSpecification.likeNameOrDescriptionOrVersion(distributionSetFilter.getSearchText());
specList.add(spec);
}
@@ -896,14 +726,6 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
return result;
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public List<DistributionSetType> createDistributionSetTypes(final Collection<DistributionSetTypeCreate> types) {
return types.stream().map(this::createDistributionSetType).collect(Collectors.toList());
}
@Override
@Transactional
@Retryable(include = {
@@ -911,7 +733,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
public void deleteDistributionSet(final Long setId) {
throwExceptionIfDistributionSetDoesNotExist(setId);
deleteDistributionSet(Lists.newArrayList(setId));
deleteDistributionSet(Arrays.asList(setId));
}
private void throwExceptionIfDistributionSetDoesNotExist(final Long setId) {
@@ -920,15 +742,6 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
}
}
@Override
public Long countDistributionSetsByType(final Long typeId) {
if (!distributionSetTypeRepository.exists(typeId)) {
throw new EntityNotFoundException(DistributionSetType.class, typeId);
}
return distributionSetRepository.countByTypeId(typeId);
}
@Override
public List<DistributionSet> findDistributionSetsById(final Collection<Long> ids) {
return Collections.unmodifiableList(distributionSetRepository.findAll(ids));

View File

@@ -0,0 +1,250 @@
/**
* 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.jpa;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.repository.DistributionSetTypeFields;
import org.eclipse.hawkbit.repository.DistributionSetTypeManagement;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeUpdate;
import org.eclipse.hawkbit.repository.builder.GenericDistributionSetTypeUpdate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.jpa.builder.JpaDistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.jpa.configuration.Constants;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType;
import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetTypeSpecification;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
/**
* JPA implementation of {@link DistributionSetTypeManagement}.
*
*/
@Transactional(readOnly = true)
@Validated
public class JpaDistributionSetTypeManagement implements DistributionSetTypeManagement {
private final DistributionSetTypeRepository distributionSetTypeRepository;
private final SoftwareModuleTypeRepository softwareModuleTypeRepository;
private final DistributionSetRepository distributionSetRepository;
private final VirtualPropertyReplacer virtualPropertyReplacer;
JpaDistributionSetTypeManagement(final DistributionSetTypeRepository distributionSetTypeRepository,
final SoftwareModuleTypeRepository softwareModuleTypeRepository,
final DistributionSetRepository distributionSetRepository,
final VirtualPropertyReplacer virtualPropertyReplacer) {
this.distributionSetTypeRepository = distributionSetTypeRepository;
this.softwareModuleTypeRepository = softwareModuleTypeRepository;
this.distributionSetRepository = distributionSetRepository;
this.virtualPropertyReplacer = virtualPropertyReplacer;
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType updateDistributionSetType(final DistributionSetTypeUpdate u) {
final GenericDistributionSetTypeUpdate update = (GenericDistributionSetTypeUpdate) u;
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(update.getId());
update.getDescription().ifPresent(type::setDescription);
update.getColour().ifPresent(type::setColour);
if (hasModules(update)) {
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(update.getId());
update.getMandatory().ifPresent(
mand -> softwareModuleTypeRepository.findByIdIn(mand).forEach(type::addMandatoryModuleType));
update.getOptional().ifPresent(
opt -> softwareModuleTypeRepository.findByIdIn(opt).forEach(type::addOptionalModuleType));
}
return distributionSetTypeRepository.save(type);
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType assignMandatorySoftwareModuleTypes(final Long dsTypeId,
final Collection<Long> softwareModulesTypeIds) {
final Collection<JpaSoftwareModuleType> modules = softwareModuleTypeRepository
.findByIdIn(softwareModulesTypeIds);
if (modules.size() < softwareModulesTypeIds.size()) {
throw new EntityNotFoundException(SoftwareModuleType.class, softwareModulesTypeIds,
modules.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()));
}
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
modules.forEach(type::addMandatoryModuleType);
return distributionSetTypeRepository.save(type);
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType assignOptionalSoftwareModuleTypes(final Long dsTypeId,
final Collection<Long> softwareModulesTypeIds) {
final Collection<JpaSoftwareModuleType> modules = softwareModuleTypeRepository
.findByIdIn(softwareModulesTypeIds);
if (modules.size() < softwareModulesTypeIds.size()) {
throw new EntityNotFoundException(SoftwareModuleType.class, softwareModulesTypeIds,
modules.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()));
}
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
modules.forEach(type::addOptionalModuleType);
return distributionSetTypeRepository.save(type);
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType unassignSoftwareModuleType(final Long dsTypeId, final Long softwareModuleTypeId) {
final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
type.removeModuleType(softwareModuleTypeId);
return distributionSetTypeRepository.save(type);
}
@Override
public Page<DistributionSetType> findDistributionSetTypesAll(final String rsqlParam, final Pageable pageable) {
final Specification<JpaDistributionSetType> spec = RSQLUtility.parse(rsqlParam, DistributionSetTypeFields.class,
virtualPropertyReplacer);
return convertDsTPage(distributionSetTypeRepository.findAll(spec, pageable));
}
@Override
public Page<DistributionSetType> findDistributionSetTypesAll(final Pageable pageable) {
return convertDsTPage(distributionSetTypeRepository.findByDeleted(pageable, false));
}
@Override
public Long countDistributionSetTypesAll() {
return distributionSetTypeRepository.countByDeleted(false);
}
@Override
public Optional<DistributionSetType> findDistributionSetTypeByName(final String name) {
return Optional
.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name)));
}
@Override
public Optional<DistributionSetType> findDistributionSetTypeById(final Long typeId) {
return Optional
.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(typeId)));
}
@Override
public Optional<DistributionSetType> findDistributionSetTypeByKey(final String key) {
return Optional.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key)));
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public DistributionSetType createDistributionSetType(final DistributionSetTypeCreate c) {
final JpaDistributionSetTypeCreate create = (JpaDistributionSetTypeCreate) c;
return distributionSetTypeRepository.save(create.build());
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public void deleteDistributionSetType(final Long typeId) {
final JpaDistributionSetType toDelete = distributionSetTypeRepository.findById(typeId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, typeId));
if (distributionSetRepository.countByTypeId(typeId) > 0) {
toDelete.setDeleted(true);
distributionSetTypeRepository.save(toDelete);
} else {
distributionSetTypeRepository.delete(typeId);
}
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public List<DistributionSetType> createDistributionSetTypes(final Collection<DistributionSetTypeCreate> types) {
return types.stream().map(this::createDistributionSetType).collect(Collectors.toList());
}
@Override
public Long countDistributionSetsByType(final Long typeId) {
if (!distributionSetTypeRepository.exists(typeId)) {
throw new EntityNotFoundException(DistributionSetType.class, typeId);
}
return distributionSetRepository.countByTypeId(typeId);
}
private JpaDistributionSetType findDistributionSetTypeAndThrowExceptionIfNotFound(final Long setId) {
return (JpaDistributionSetType) findDistributionSetTypeById(setId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, setId));
}
private static boolean hasModules(final GenericDistributionSetTypeUpdate update) {
return update.getOptional().isPresent() || update.getMandatory().isPresent();
}
private void checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(final Long type) {
if (distributionSetRepository.countByTypeId(type) > 0) {
throw new EntityReadOnlyException(String.format(
"distribution set type %s is already assigned to distribution sets and cannot be changed", type));
}
}
private static Page<DistributionSetType> convertDsTPage(final Page<JpaDistributionSetType> findAll) {
return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()));
}
}

View File

@@ -20,7 +20,6 @@ import java.util.stream.StreamSupport;
import javax.persistence.EntityManager;
import javax.validation.ConstraintDeclarationException;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.hawkbit.repository.AbstractRolloutManagement;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
@@ -35,6 +34,7 @@ import org.eclipse.hawkbit.repository.builder.GenericRolloutUpdate;
import org.eclipse.hawkbit.repository.builder.RolloutCreate;
import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate;
import org.eclipse.hawkbit.repository.builder.RolloutUpdate;
import org.eclipse.hawkbit.repository.event.remote.RolloutGroupDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutUpdatedEvent;
import org.eclipse.hawkbit.repository.exception.ConstraintViolationException;
@@ -93,6 +93,7 @@ import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.validation.annotation.Validated;
@@ -143,6 +144,9 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
@Autowired
private RolloutStatusCache rolloutStatusCache;
@Autowired
private ApplicationContext applicationContext;
JpaRolloutManagement(final TargetManagement targetManagement, final DeploymentManagement deploymentManagement,
final RolloutGroupManagement rolloutGroupManagement,
final DistributionSetManagement distributionSetManagement, final ApplicationContext context,
@@ -869,9 +873,21 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
rollout.setStatus(RolloutStatus.DELETED);
rollout.setDeleted(true);
rolloutRepository.save(rollout);
sendRolloutGroupDeletedEvents(rollout);
}
private void sendRolloutGroupDeletedEvents(final JpaRollout rollout) {
final List<Long> groupIds = rollout.getRolloutGroups().stream().map(RolloutGroup::getId)
.collect(Collectors.toList());
afterCommit.afterCommit(() -> groupIds.forEach(rolloutGroupId -> eventPublisher
.publishEvent(new RolloutGroupDeletedEvent(tenantAware.getCurrentTenant(), rolloutGroupId,
JpaRolloutGroup.class.getName(), applicationContext.getId()))));
}
private void hardDeleteRollout(final JpaRollout rollout) {
sendRolloutGroupDeletedEvents(rollout);
rolloutRepository.delete(rollout);
}
@@ -911,7 +927,7 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
public Slice<Rollout> findRolloutWithDetailedStatusByFilters(final Pageable pageable, final String searchText,
final boolean deleted) {
final Slice<JpaRollout> findAll = findByCriteriaAPI(pageable,
Lists.newArrayList(JpaRolloutHelper.likeNameOrDescription(searchText, deleted)));
Arrays.asList(JpaRolloutHelper.likeNameOrDescription(searchText, deleted)));
setRolloutStatusDetails(findAll);
return JpaRolloutHelper.convertPage(findAll, pageable);
}

View File

@@ -28,27 +28,21 @@ import javax.persistence.criteria.Root;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleFields;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields;
import org.eclipse.hawkbit.repository.builder.GenericSoftwareModuleTypeUpdate;
import org.eclipse.hawkbit.repository.builder.GenericSoftwareModuleUpdate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeUpdate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleUpdate;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.jpa.builder.JpaSoftwareModuleCreate;
import org.eclipse.hawkbit.repository.jpa.builder.JpaSoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.jpa.configuration.Constants;
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.JpaSoftwareModuleMetadata;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata_;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule_;
import org.eclipse.hawkbit.repository.jpa.model.SwMetadataCompositeKey;
import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
@@ -75,19 +69,19 @@ import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* JPA implementation of {@link SoftwareManagement}.
* JPA implementation of {@link SoftwareModuleManagement}.
*
*/
@Transactional(readOnly = true)
@Validated
public class JpaSoftwareManagement implements SoftwareManagement {
public class JpaSoftwareModuleManagement implements SoftwareModuleManagement {
@Autowired
private EntityManager entityManager;
@@ -95,9 +89,6 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Autowired
private DistributionSetRepository distributionSetRepository;
@Autowired
private DistributionSetTypeRepository distributionSetTypeRepository;
@Autowired
private SoftwareModuleRepository softwareModuleRepository;
@@ -135,22 +126,6 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return softwareModuleRepository.save(module);
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public SoftwareModuleType updateSoftwareModuleType(final SoftwareModuleTypeUpdate u) {
final GenericSoftwareModuleTypeUpdate update = (GenericSoftwareModuleTypeUpdate) u;
final JpaSoftwareModuleType type = (JpaSoftwareModuleType) findSoftwareModuleTypeById(update.getId())
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, update.getId()));
update.getDescription().ifPresent(type::setDescription);
update.getColour().ifPresent(type::setColour);
return softwareModuleTypeRepository.save(type);
}
@Override
@Transactional
@Retryable(include = {
@@ -294,7 +269,7 @@ public class JpaSoftwareManagement implements SoftwareManagement {
public Long countSoftwareModulesAll() {
final Specification<JpaSoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse();
return countSwModuleByCriteriaAPI(Lists.newArrayList(spec));
return countSwModuleByCriteriaAPI(Arrays.asList(spec));
}
@Override
@@ -305,20 +280,6 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return convertSmPage(softwareModuleRepository.findAll(spec, pageable), pageable);
}
@Override
public Page<SoftwareModuleType> findSoftwareModuleTypesAll(final String rsqlParam, final Pageable pageable) {
final Specification<JpaSoftwareModuleType> spec = RSQLUtility.parse(rsqlParam, SoftwareModuleTypeFields.class,
virtualPropertyReplacer);
return convertSmTPage(softwareModuleTypeRepository.findAll(spec, pageable), pageable);
}
private static Page<SoftwareModuleType> convertSmTPage(final Page<JpaSoftwareModuleType> findAll,
final Pageable pageable) {
return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements());
}
@Override
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public List<SoftwareModule> findSoftwareModulesById(final Collection<Long> ids) {
@@ -334,7 +295,7 @@ public class JpaSoftwareManagement implements SoftwareManagement {
Specification<JpaSoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse();
specList.add(spec);
if (!Strings.isNullOrEmpty(searchText)) {
if (!StringUtils.isEmpty(searchText)) {
spec = SoftwareModuleSpecification.likeNameOrVersion(searchText);
specList.add(spec);
}
@@ -427,7 +388,7 @@ public class JpaSoftwareManagement implements SoftwareManagement {
private List<Specification<JpaSoftwareModule>> buildSpecificationList(final String searchText, final Long typeId) {
final List<Specification<JpaSoftwareModule>> specList = Lists.newArrayListWithExpectedSize(3);
if (!Strings.isNullOrEmpty(searchText)) {
if (!StringUtils.isEmpty(searchText)) {
specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText));
}
if (typeId != null) {
@@ -455,7 +416,7 @@ public class JpaSoftwareManagement implements SoftwareManagement {
Specification<JpaSoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse();
specList.add(spec);
if (!Strings.isNullOrEmpty(searchText)) {
if (!StringUtils.isEmpty(searchText)) {
spec = SoftwareModuleSpecification.likeNameOrVersion(searchText);
specList.add(spec);
}
@@ -470,58 +431,6 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return countSwModuleByCriteriaAPI(specList);
}
@Override
public Page<SoftwareModuleType> findSoftwareModuleTypesAll(final Pageable pageable) {
return softwareModuleTypeRepository.findByDeleted(pageable, false);
}
@Override
public Long countSoftwareModuleTypesAll() {
return softwareModuleTypeRepository.countByDeleted(false);
}
@Override
public Optional<SoftwareModuleType> findSoftwareModuleTypeByKey(final String key) {
return softwareModuleTypeRepository.findByKey(key);
}
@Override
public Optional<SoftwareModuleType> findSoftwareModuleTypeById(final Long smTypeId) {
return Optional.ofNullable(softwareModuleTypeRepository.findOne(smTypeId));
}
@Override
public Optional<SoftwareModuleType> findSoftwareModuleTypeByName(final String name) {
return softwareModuleTypeRepository.findByName(name);
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public SoftwareModuleType createSoftwareModuleType(final SoftwareModuleTypeCreate c) {
final JpaSoftwareModuleTypeCreate create = (JpaSoftwareModuleTypeCreate) c;
return softwareModuleTypeRepository.save(create.build());
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public void deleteSoftwareModuleType(final Long typeId) {
final JpaSoftwareModuleType toDelete = softwareModuleTypeRepository.findById(typeId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, typeId));
if (softwareModuleRepository.countByType(toDelete) > 0
|| distributionSetTypeRepository.countByElementsSmType(toDelete) > 0) {
toDelete.setDeleted(true);
softwareModuleTypeRepository.save(toDelete);
} else {
softwareModuleTypeRepository.delete(toDelete);
}
}
@Override
public Page<SoftwareModule> findSoftwareModuleByAssignedTo(final Pageable pageable, final Long setId) {
if (!distributionSetRepository.exists(setId)) {
@@ -685,14 +594,6 @@ public class JpaSoftwareManagement implements SoftwareManagement {
deleteSoftwareModules(Sets.newHashSet(moduleId));
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public List<SoftwareModuleType> createSoftwareModuleType(final Collection<SoftwareModuleTypeCreate> creates) {
return creates.stream().map(this::createSoftwareModuleType).collect(Collectors.toList());
}
@Override
public List<SoftwareModuleType> findSoftwareModuleTypesById(final Collection<Long> ids) {
return Collections.unmodifiableList(softwareModuleTypeRepository.findByIdIn(ids));

View File

@@ -0,0 +1,155 @@
/**
* 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.jpa;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement;
import org.eclipse.hawkbit.repository.builder.GenericSoftwareModuleTypeUpdate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeUpdate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.jpa.builder.JpaSoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.jpa.configuration.Constants;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType;
import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
/**
* JPA implementation of {@link SoftwareModuleTypeManagement}.
*
*/
@Transactional(readOnly = true)
@Validated
public class JpaSoftwareModuleTypeManagement implements SoftwareModuleTypeManagement {
private final DistributionSetTypeRepository distributionSetTypeRepository;
private final SoftwareModuleTypeRepository softwareModuleTypeRepository;
private final VirtualPropertyReplacer virtualPropertyReplacer;
private final SoftwareModuleRepository softwareModuleRepository;
JpaSoftwareModuleTypeManagement(final DistributionSetTypeRepository distributionSetTypeRepository,
final SoftwareModuleTypeRepository softwareModuleTypeRepository,
final VirtualPropertyReplacer virtualPropertyReplacer,
final SoftwareModuleRepository softwareModuleRepository) {
this.distributionSetTypeRepository = distributionSetTypeRepository;
this.softwareModuleTypeRepository = softwareModuleTypeRepository;
this.virtualPropertyReplacer = virtualPropertyReplacer;
this.softwareModuleRepository = softwareModuleRepository;
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public SoftwareModuleType updateSoftwareModuleType(final SoftwareModuleTypeUpdate u) {
final GenericSoftwareModuleTypeUpdate update = (GenericSoftwareModuleTypeUpdate) u;
final JpaSoftwareModuleType type = (JpaSoftwareModuleType) findSoftwareModuleTypeById(update.getId())
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, update.getId()));
update.getDescription().ifPresent(type::setDescription);
update.getColour().ifPresent(type::setColour);
return softwareModuleTypeRepository.save(type);
}
@Override
public Page<SoftwareModuleType> findSoftwareModuleTypesAll(final String rsqlParam, final Pageable pageable) {
final Specification<JpaSoftwareModuleType> spec = RSQLUtility.parse(rsqlParam, SoftwareModuleTypeFields.class,
virtualPropertyReplacer);
return convertSmTPage(softwareModuleTypeRepository.findAll(spec, pageable), pageable);
}
@Override
public Page<SoftwareModuleType> findSoftwareModuleTypesAll(final Pageable pageable) {
return softwareModuleTypeRepository.findByDeleted(pageable, false);
}
@Override
public Long countSoftwareModuleTypesAll() {
return softwareModuleTypeRepository.countByDeleted(false);
}
@Override
public Optional<SoftwareModuleType> findSoftwareModuleTypeByKey(final String key) {
return softwareModuleTypeRepository.findByKey(key);
}
@Override
public Optional<SoftwareModuleType> findSoftwareModuleTypeById(final Long smTypeId) {
return Optional.ofNullable(softwareModuleTypeRepository.findOne(smTypeId));
}
@Override
public Optional<SoftwareModuleType> findSoftwareModuleTypeByName(final String name) {
return softwareModuleTypeRepository.findByName(name);
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public SoftwareModuleType createSoftwareModuleType(final SoftwareModuleTypeCreate c) {
final JpaSoftwareModuleTypeCreate create = (JpaSoftwareModuleTypeCreate) c;
return softwareModuleTypeRepository.save(create.build());
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public void deleteSoftwareModuleType(final Long typeId) {
final JpaSoftwareModuleType toDelete = softwareModuleTypeRepository.findById(typeId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, typeId));
if (softwareModuleRepository.countByType(toDelete) > 0
|| distributionSetTypeRepository.countByElementsSmType(toDelete) > 0) {
toDelete.setDeleted(true);
softwareModuleTypeRepository.save(toDelete);
} else {
softwareModuleTypeRepository.delete(toDelete);
}
}
@Override
@Transactional
@Retryable(include = {
ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public List<SoftwareModuleType> createSoftwareModuleType(final Collection<SoftwareModuleTypeCreate> creates) {
return creates.stream().map(this::createSoftwareModuleType).collect(Collectors.toList());
}
private static Page<SoftwareModuleType> convertSmTPage(final Page<JpaSoftwareModuleType> findAll,
final Pageable pageable) {
return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements());
}
}

View File

@@ -41,9 +41,9 @@ import org.springframework.data.jpa.domain.Specifications;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
/**
@@ -108,7 +108,7 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
@Override
public Page<TargetFilterQuery> findTargetFilterQueryByName(final Pageable pageable, final String name) {
List<Specification<JpaTargetFilterQuery>> specList = Collections.emptyList();
if (!Strings.isNullOrEmpty(name)) {
if (!StringUtils.isEmpty(name)) {
specList = Collections.singletonList(TargetFilterQuerySpecification.likeName(name));
}
return convertPage(findTargetFilterQueryByCriteriaAPI(pageable, specList), pageable);
@@ -117,7 +117,7 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
@Override
public Page<TargetFilterQuery> findTargetFilterQueryByFilter(final Pageable pageable, final String rsqlFilter) {
List<Specification<JpaTargetFilterQuery>> specList = Collections.emptyList();
if (!Strings.isNullOrEmpty(rsqlFilter)) {
if (!StringUtils.isEmpty(rsqlFilter)) {
specList = Collections.singletonList(
RSQLUtility.parse(rsqlFilter, TargetFilterQueryFields.class, virtualPropertyReplacer));
}
@@ -127,7 +127,7 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
@Override
public Page<TargetFilterQuery> findTargetFilterQueryByQuery(final Pageable pageable, final String query) {
List<Specification<JpaTargetFilterQuery>> specList = Collections.emptyList();
if (!Strings.isNullOrEmpty(query)) {
if (!StringUtils.isEmpty(query)) {
specList = Collections.singletonList(TargetFilterQuerySpecification.equalsQuery(query));
}
return convertPage(findTargetFilterQueryByCriteriaAPI(pageable, specList), pageable);
@@ -142,7 +142,7 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
specList.add(TargetFilterQuerySpecification.byAutoAssignDS(distributionSet));
if (!Strings.isNullOrEmpty(rsqlFilter)) {
if (!StringUtils.isEmpty(rsqlFilter)) {
specList.add(RSQLUtility.parse(rsqlFilter, TargetFilterQueryFields.class, virtualPropertyReplacer));
}
return convertPage(findTargetFilterQueryByCriteriaAPI(pageable, specList), pageable);

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository.jpa;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@@ -25,7 +26,6 @@ import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.hawkbit.repository.FilterParams;
import org.eclipse.hawkbit.repository.TargetFields;
import org.eclipse.hawkbit.repository.TargetManagement;
@@ -37,6 +37,7 @@ import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.jpa.builder.JpaTargetCreate;
import org.eclipse.hawkbit.repository.jpa.builder.JpaTargetUpdate;
import org.eclipse.hawkbit.repository.jpa.configuration.Constants;
import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag;
@@ -66,10 +67,9 @@ import org.springframework.data.jpa.domain.Specification;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import com.google.common.collect.Lists;
/**
* JPA implementation of {@link TargetManagement}.
*
@@ -108,6 +108,9 @@ public class JpaTargetManagement implements TargetManagement {
@Autowired
private TenantAware tenantAware;
@Autowired
private AfterTransactionCommitExecutor afterCommit;
@Autowired
private VirtualPropertyReplacer virtualPropertyReplacer;
@@ -183,10 +186,10 @@ public class JpaTargetManagement implements TargetManagement {
targetRepository.deleteByIdIn(targetIDs);
targets.forEach(target -> eventPublisher.publishEvent(
afterCommit.afterCommit(() -> targets.forEach(target -> eventPublisher.publishEvent(
new TargetDeletedEvent(tenantAware.getCurrentTenant(), target.getId(), target.getControllerId(),
Optional.ofNullable(target.getAddress()).map(URI::toString).orElse(null),
JpaTarget.class.getName(), applicationContext.getId())));
JpaTarget.class.getName(), applicationContext.getId()))));
}
@Override
@@ -298,7 +301,7 @@ public class JpaTargetManagement implements TargetManagement {
specList.add(TargetSpecifications
.hasInstalledOrAssignedDistributionSet(filterParams.getFilterByDistributionId()));
}
if (StringUtils.isNotEmpty(filterParams.getFilterBySearchText())) {
if (!StringUtils.isEmpty(filterParams.getFilterBySearchText())) {
specList.add(TargetSpecifications.likeIdOrNameOrDescription(filterParams.getFilterBySearchText()));
}
if (isHasTagsFilterActive(filterParams)) {
@@ -529,7 +532,7 @@ public class JpaTargetManagement implements TargetManagement {
final String targetFilterQuery) {
final Specification<JpaTarget> spec = RSQLUtility.parse(targetFilterQuery, TargetFields.class,
virtualPropertyReplacer);
final List<Specification<JpaTarget>> specList = Lists.newArrayList(spec,
final List<Specification<JpaTarget>> specList = Arrays.asList(spec,
TargetSpecifications.isNotInRolloutGroups(groups));
return countByCriteriaAPI(specList);

View File

@@ -18,13 +18,15 @@ import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.DistributionSetTypeManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.PropertiesQuotaManagement;
import org.eclipse.hawkbit.repository.RepositoryProperties;
import org.eclipse.hawkbit.repository.RolloutGroupManagement;
import org.eclipse.hawkbit.repository.RolloutManagement;
import org.eclipse.hawkbit.repository.RolloutStatusCache;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.TagManagement;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
@@ -140,16 +142,16 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration {
}
/**
* @param distributionSetManagement
* @param distributionSetTypeManagement
* to loading the {@link DistributionSetType}
* @param softwareManagement
* for loading {@link DistributionSet#getModules()}
* @return DistributionSetBuilder bean
*/
@Bean
DistributionSetBuilder distributionSetBuilder(final DistributionSetManagement distributionSetManagement,
final SoftwareManagement softwareManagement) {
return new JpaDistributionSetBuilder(distributionSetManagement, softwareManagement);
DistributionSetBuilder distributionSetBuilder(final DistributionSetTypeManagement distributionSetTypeManagement,
final SoftwareModuleManagement softwareManagement) {
return new JpaDistributionSetBuilder(distributionSetTypeManagement, softwareManagement);
}
/**
@@ -160,18 +162,18 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration {
* @return DistributionSetTypeBuilder bean
*/
@Bean
DistributionSetTypeBuilder distributionSetTypeBuilder(final SoftwareManagement softwareManagement) {
DistributionSetTypeBuilder distributionSetTypeBuilder(final SoftwareModuleManagement softwareManagement) {
return new JpaDistributionSetTypeBuilder(softwareManagement);
}
/**
* @param softwareManagement
* @param softwareModuleTypeManagement
* for loading {@link SoftwareModule#getType()}
* @return SoftwareModuleBuilder bean
*/
@Bean
SoftwareModuleBuilder softwareModuleBuilder(final SoftwareManagement softwareManagement) {
return new JpaSoftwareModuleBuilder(softwareManagement);
SoftwareModuleBuilder softwareModuleBuilder(final SoftwareModuleTypeManagement softwareModuleTypeManagement) {
return new JpaSoftwareModuleBuilder(softwareModuleTypeManagement);
}
/**
@@ -346,6 +348,22 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration {
return new JpaDistributionSetManagement();
}
/**
* {@link JpaDistributionSetManagement} bean.
*
* @return a new {@link DistributionSetManagement}
*/
@Bean
@ConditionalOnMissingBean
DistributionSetTypeManagement distributionSetTypeManagement(
final DistributionSetTypeRepository distributionSetTypeRepository,
final SoftwareModuleTypeRepository softwareModuleTypeRepository,
final DistributionSetRepository distributionSetRepository,
final VirtualPropertyReplacer virtualPropertyReplacer) {
return new JpaDistributionSetTypeManagement(distributionSetTypeRepository, softwareModuleTypeRepository,
distributionSetRepository, virtualPropertyReplacer);
}
/**
* {@link JpaTenantStatsManagement} bean.
*
@@ -413,14 +431,30 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration {
}
/**
* {@link JpaSoftwareManagement} bean.
* {@link JpaSoftwareModuleManagement} bean.
*
* @return a new {@link SoftwareManagement}
* @return a new {@link SoftwareModuleManagement}
*/
@Bean
@ConditionalOnMissingBean
SoftwareManagement softwareManagement() {
return new JpaSoftwareManagement();
SoftwareModuleManagement softwareModuleManagement() {
return new JpaSoftwareModuleManagement();
}
/**
* {@link JpaSoftwareModuleManagement} bean.
*
* @return a new {@link SoftwareModuleManagement}
*/
@Bean
@ConditionalOnMissingBean
SoftwareModuleTypeManagement softwareModuleTypeManagement(
final DistributionSetTypeRepository distributionSetTypeRepository,
final SoftwareModuleTypeRepository softwareModuleTypeRepository,
final VirtualPropertyReplacer virtualPropertyReplacer,
final SoftwareModuleRepository softwareModuleRepository) {
return new JpaSoftwareModuleTypeManagement(distributionSetTypeRepository, softwareModuleTypeRepository,
virtualPropertyReplacer, softwareModuleRepository);
}
@Bean

View File

@@ -8,8 +8,8 @@
*/
package org.eclipse.hawkbit.repository.jpa.builder;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.DistributionSetTypeManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.builder.DistributionSetBuilder;
import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetUpdate;
@@ -22,13 +22,13 @@ import org.eclipse.hawkbit.repository.model.DistributionSet;
*/
public class JpaDistributionSetBuilder implements DistributionSetBuilder {
private final DistributionSetManagement distributionSetManagement;
private final SoftwareManagement softwareManagement;
private final DistributionSetTypeManagement distributionSetTypeManagement;
private final SoftwareModuleManagement softwareModuleManagement;
public JpaDistributionSetBuilder(final DistributionSetManagement distributionSetManagement,
final SoftwareManagement softwareManagement) {
this.distributionSetManagement = distributionSetManagement;
this.softwareManagement = softwareManagement;
public JpaDistributionSetBuilder(final DistributionSetTypeManagement distributionSetTypeManagement,
final SoftwareModuleManagement softwareManagement) {
this.distributionSetTypeManagement = distributionSetTypeManagement;
this.softwareModuleManagement = softwareManagement;
}
@Override
@@ -38,7 +38,7 @@ public class JpaDistributionSetBuilder implements DistributionSetBuilder {
@Override
public DistributionSetCreate create() {
return new JpaDistributionSetCreate(distributionSetManagement, softwareManagement);
return new JpaDistributionSetCreate(distributionSetTypeManagement, softwareModuleManagement);
}
}

View File

@@ -12,8 +12,8 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.DistributionSetTypeManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.builder.AbstractDistributionSetUpdateCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
@@ -29,13 +29,13 @@ import org.springframework.util.CollectionUtils;
public class JpaDistributionSetCreate extends AbstractDistributionSetUpdateCreate<DistributionSetCreate>
implements DistributionSetCreate {
private final DistributionSetManagement distributionSetManagement;
private final SoftwareManagement softwareManagement;
private final DistributionSetTypeManagement distributionSetTypeManagement;
private final SoftwareModuleManagement softwareModuleManagement;
JpaDistributionSetCreate(final DistributionSetManagement distributionSetManagement,
final SoftwareManagement softwareManagement) {
this.distributionSetManagement = distributionSetManagement;
this.softwareManagement = softwareManagement;
JpaDistributionSetCreate(final DistributionSetTypeManagement distributionSetTypeManagement,
final SoftwareModuleManagement softwareManagement) {
this.distributionSetTypeManagement = distributionSetTypeManagement;
this.softwareModuleManagement = softwareManagement;
}
@Override
@@ -47,7 +47,7 @@ public class JpaDistributionSetCreate extends AbstractDistributionSetUpdateCreat
}
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) {
return distributionSetManagement.findDistributionSetTypeByKey(distributionSetTypekey)
return distributionSetTypeManagement.findDistributionSetTypeByKey(distributionSetTypekey)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypekey));
}
@@ -57,7 +57,7 @@ public class JpaDistributionSetCreate extends AbstractDistributionSetUpdateCreat
return Collections.emptyList();
}
final Collection<SoftwareModule> module = softwareManagement.findSoftwareModulesById(softwareModuleId);
final Collection<SoftwareModule> module = softwareModuleManagement.findSoftwareModulesById(softwareModuleId);
if (module.size() < softwareModuleId.size()) {
throw new EntityNotFoundException(SoftwareModule.class, softwareModuleId);
}

View File

@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.repository.jpa.builder;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeBuilder;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeUpdate;
@@ -21,10 +21,10 @@ import org.eclipse.hawkbit.repository.model.DistributionSetType;
*/
public class JpaDistributionSetTypeBuilder implements DistributionSetTypeBuilder {
private final SoftwareManagement softwareManagement;
private final SoftwareModuleManagement softwareModuleManagement;
public JpaDistributionSetTypeBuilder(final SoftwareManagement softwareManagement) {
this.softwareManagement = softwareManagement;
public JpaDistributionSetTypeBuilder(final SoftwareModuleManagement softwareManagement) {
this.softwareModuleManagement = softwareManagement;
}
@Override
@@ -34,7 +34,7 @@ public class JpaDistributionSetTypeBuilder implements DistributionSetTypeBuilder
@Override
public DistributionSetTypeCreate create() {
return new JpaDistributionSetTypeCreate(softwareManagement);
return new JpaDistributionSetTypeCreate(softwareModuleManagement);
}
}

View File

@@ -11,7 +11,7 @@ package org.eclipse.hawkbit.repository.jpa.builder;
import java.util.Collection;
import java.util.Collections;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.builder.AbstractDistributionSetTypeUpdateCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
@@ -26,10 +26,10 @@ import org.springframework.util.CollectionUtils;
public class JpaDistributionSetTypeCreate extends AbstractDistributionSetTypeUpdateCreate<DistributionSetTypeCreate>
implements DistributionSetTypeCreate {
private final SoftwareManagement softwareManagement;
private final SoftwareModuleManagement softwareModuleManagement;
JpaDistributionSetTypeCreate(final SoftwareManagement softwareManagement) {
this.softwareManagement = softwareManagement;
JpaDistributionSetTypeCreate(final SoftwareModuleManagement softwareManagement) {
this.softwareModuleManagement = softwareManagement;
}
@Override
@@ -48,7 +48,7 @@ public class JpaDistributionSetTypeCreate extends AbstractDistributionSetTypeUpd
return Collections.emptyList();
}
final Collection<SoftwareModuleType> module = softwareManagement
final Collection<SoftwareModuleType> module = softwareModuleManagement
.findSoftwareModuleTypesById(softwareModuleTypeId);
if (module.size() < softwareModuleTypeId.size()) {
throw new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId);

View File

@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.repository.jpa.builder;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement;
import org.eclipse.hawkbit.repository.builder.GenericSoftwareModuleUpdate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleBuilder;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate;
@@ -21,10 +21,10 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule;
*/
public class JpaSoftwareModuleBuilder implements SoftwareModuleBuilder {
private final SoftwareManagement softwareManagement;
private final SoftwareModuleTypeManagement softwareModuleTypeManagement;
public JpaSoftwareModuleBuilder(final SoftwareManagement softwareManagement) {
this.softwareManagement = softwareManagement;
public JpaSoftwareModuleBuilder(final SoftwareModuleTypeManagement softwareModuleTypeManagement) {
this.softwareModuleTypeManagement = softwareModuleTypeManagement;
}
@Override
@@ -34,7 +34,7 @@ public class JpaSoftwareModuleBuilder implements SoftwareModuleBuilder {
@Override
public SoftwareModuleCreate create() {
return new JpaSoftwareModuleCreate(softwareManagement);
return new JpaSoftwareModuleCreate(softwareModuleTypeManagement);
}
}

View File

@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.repository.jpa.builder;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement;
import org.eclipse.hawkbit.repository.builder.AbstractSoftwareModuleUpdateCreate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate;
import org.eclipse.hawkbit.repository.exception.ConstraintViolationException;
@@ -23,10 +23,10 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
public class JpaSoftwareModuleCreate extends AbstractSoftwareModuleUpdateCreate<SoftwareModuleCreate>
implements SoftwareModuleCreate {
private final SoftwareManagement softwareManagement;
private final SoftwareModuleTypeManagement softwareModuleTypeManagement;
JpaSoftwareModuleCreate(final SoftwareManagement softwareManagement) {
this.softwareManagement = softwareManagement;
JpaSoftwareModuleCreate(final SoftwareModuleTypeManagement softwareModuleTypeManagement) {
this.softwareModuleTypeManagement = softwareModuleTypeManagement;
}
@Override
@@ -39,7 +39,7 @@ public class JpaSoftwareModuleCreate extends AbstractSoftwareModuleUpdateCreate<
throw new ConstraintViolationException("type cannot be null");
}
return softwareManagement.findSoftwareModuleTypeByKey(type.trim())
return softwareModuleTypeManagement.findSoftwareModuleTypeByKey(type.trim())
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, type.trim()));
}
}

View File

@@ -8,11 +8,11 @@
*/
package org.eclipse.hawkbit.repository.jpa.builder;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.hawkbit.repository.builder.AbstractTargetUpdateCreate;
import org.eclipse.hawkbit.repository.builder.TargetCreate;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.springframework.util.StringUtils;
/**
* Create/build implementation.

View File

@@ -27,6 +27,7 @@ import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.eclipse.hawkbit.repository.event.remote.RolloutGroupDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupUpdatedEvent;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
@@ -295,6 +296,7 @@ public class JpaRolloutGroup extends AbstractJpaNamedEntity implements RolloutGr
@Override
public void fireDeleteEvent(final DescriptorEvent descriptorEvent) {
// there is no RolloutGroup deleted event
EventPublisherHolder.getInstance().getEventPublisher().publishEvent(new RolloutGroupDeletedEvent(getTenant(),
getId(), getClass().getName(), EventPublisherHolder.getInstance().getApplicationId()));
}
}

View File

@@ -14,6 +14,7 @@ import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@@ -67,8 +68,6 @@ import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
/**
* JPA implementation of {@link Target}.
*
@@ -90,7 +89,7 @@ public class JpaTarget extends AbstractJpaNamedEntity implements Target, EventAw
private static final Logger LOG = LoggerFactory.getLogger(JpaTarget.class);
private static final List<String> TARGET_UPDATE_EVENT_IGNORE_FIELDS = Lists.newArrayList("lastTargetQuery",
private static final List<String> TARGET_UPDATE_EVENT_IGNORE_FIELDS = Arrays.asList("lastTargetQuery",
"lastTargetQuery", "address", "optLockRevision", "lastModifiedAt", "lastModifiedBy");
@Column(name = "controller_id", length = 64)

View File

@@ -36,7 +36,6 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.orm.jpa.JpaSystemException;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import cz.jirutka.rsql.parser.ParseException;
@@ -166,7 +165,7 @@ public class RsqlParserValidationOracle implements RsqlValidationOracle {
nextTokenBeginColumn + currentTokenImageName.length(), currentTokenImageName));
} else if (shouldSuggestDotToken(currentTokenImageName, containsDot)) {
return Optional.of(
Lists.newArrayList(new SuggestToken(currentTokenEndColumn, nextTokenBeginColumn + 1, null, ".")));
Arrays.asList(new SuggestToken(currentTokenEndColumn, nextTokenBeginColumn + 1, null, ".")));
} else if (shouldSuggestSubTokenFieldNames(currentTokenImageName, containsDot)) {
return handleSubtokenSuggestion(currentTokenImageName, nextTokenBeginColumn);
}

View File

@@ -12,7 +12,6 @@ import static org.junit.Assert.fail;
import java.util.Map;
import org.apache.commons.lang3.ClassUtils;
import org.eclipse.hawkbit.event.BusProtoStuffMessageConverter;
import org.eclipse.hawkbit.repository.event.TenantAwareEvent;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -27,6 +26,7 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.AbstractMessageConverter;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

View File

@@ -17,7 +17,6 @@ import javax.persistence.PersistenceContext;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.eclipse.hawkbit.cache.TenantAwareCacheManager;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -90,9 +89,6 @@ public abstract class AbstractJpaIntegrationTest extends AbstractIntegrationTest
@Autowired
protected RolloutRepository rolloutRepository;
@Autowired
protected TenantAwareCacheManager cacheManager;
@Autowired
protected TenantConfigurationProperties tenantConfigurationProperties;
@@ -108,7 +104,7 @@ public abstract class AbstractJpaIntegrationTest extends AbstractIntegrationTest
protected TargetTagAssignmentResult toggleTagAssignment(final Collection<Target> targets, final TargetTag tag) {
return targetManagement.toggleTagAssignment(
targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()), tag.getName());
targets.stream().map(Target::getControllerId).collect(Collectors.toList()), tag.getName());
}
public DistributionSetTagAssignmentResult toggleTagAssignment(final Collection<DistributionSet> sets,

View File

@@ -127,7 +127,7 @@ public class ArtifactManagementTest extends AbstractJpaIntegrationTest {
assertThat(artifactRepository.findAll()).hasSize(4);
assertThat(softwareModuleRepository.findAll()).hasSize(3);
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()).hasSize(3);
assertThat(softwareModuleManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()).hasSize(3);
}
@Test

View File

@@ -14,6 +14,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
@@ -111,13 +112,11 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final Target target = testdataFactory.createTarget();
verifyThrownExceptionBy(() -> deploymentManagement.assignDistributionSet(NOT_EXIST_IDL,
Lists.newArrayList(new TargetWithActionType(target.getControllerId()))), "DistributionSet");
verifyThrownExceptionBy(
() -> deploymentManagement.assignDistributionSet(NOT_EXIST_IDL,
Lists.newArrayList(new TargetWithActionType(target.getControllerId())), "xxx"),
"DistributionSet");
Arrays.asList(new TargetWithActionType(target.getControllerId()))), "DistributionSet");
verifyThrownExceptionBy(() -> deploymentManagement.assignDistributionSet(NOT_EXIST_IDL,
Arrays.asList(new TargetWithActionType(target.getControllerId())), "xxx"), "DistributionSet");
verifyThrownExceptionBy(() -> deploymentManagement.assignDistributionSet(NOT_EXIST_IDL, ActionType.FORCED,
System.currentTimeMillis(), Lists.newArrayList(target.getControllerId())), "DistributionSet");
System.currentTimeMillis(), Arrays.asList(target.getControllerId())), "DistributionSet");
verifyThrownExceptionBy(() -> deploymentManagement.cancelAction(NOT_EXIST_IDL), "Action");
verifyThrownExceptionBy(() -> deploymentManagement.countActionsByTarget(NOT_EXIST_ID), "Target");
@@ -126,12 +125,10 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByDistributionSet(PAGE, NOT_EXIST_IDL),
"DistributionSet");
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByTarget(NOT_EXIST_ID, PAGE), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByTarget("id==*", NOT_EXIST_ID, PAGE),
"Target");
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByTarget("id==*", NOT_EXIST_ID, PAGE), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findActiveActionsByTarget(PAGE, NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findInActiveActionsByTarget(PAGE, NOT_EXIST_ID),
"Target");
verifyThrownExceptionBy(() -> deploymentManagement.findInActiveActionsByTarget(PAGE, NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.forceQuitAction(NOT_EXIST_IDL), "Action");
verifyThrownExceptionBy(() -> deploymentManagement.forceTargetAction(NOT_EXIST_IDL), "Action");
}
@@ -200,7 +197,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final Long actionId = assignDistributionSet(testDs, testTarget).getActions().get(0);
// create action-status entry with one message
controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(actionId)
.status(Action.Status.FINISHED).messages(Lists.newArrayList("finished message")));
.status(Action.Status.FINISHED).messages(Arrays.asList("finished message")));
final Page<ActionStatus> actionStates = deploymentManagement.findActionStatusByAction(PAGE, actionId);
// find newly created action-status entry with message
@@ -426,8 +423,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId()).get())
.as("wrong assigned ds").isEqualTo(ds);
final JpaAction action = actionRepository
.findByTargetAndDistributionSet(PAGE, (JpaTarget) target, (JpaDistributionSet) ds).getContent()
.get(0);
.findByTargetAndDistributionSet(PAGE, (JpaTarget) target, (JpaDistributionSet) ds).getContent().get(0);
assertThat(action).as("action should not be null").isNotNull();
return action;
}
@@ -505,7 +501,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet incomplete = distributionSetManagement
.createDistributionSet(entityFactory.distributionSet().create().name("incomplete").version("v1")
.type(standardDsType).modules(Lists.newArrayList(ah.getId())));
.type(standardDsType).modules(Arrays.asList(ah.getId())));
try {
assignDistributionSet(incomplete, targets);
@@ -786,7 +782,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet dsA = testdataFactory.createDistributionSet("a");
final DistributionSet dsB = testdataFactory.createDistributionSet("b");
List<Target> targs = Lists.newArrayList(testdataFactory.createTarget("target-id-A"));
List<Target> targs = Arrays.asList(testdataFactory.createTarget("target-id-A"));
// doing the assignment
targs = assignDistributionSet(dsA, targs).getAssignedEntity();
@@ -856,7 +852,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(dsA.getOptLockRevision()).as("lock revision is wrong").isEqualTo(
distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).get().getOptLockRevision());
assignDistributionSet(dsA, Lists.newArrayList(targ));
assignDistributionSet(dsA, Arrays.asList(targ));
assertThat(dsA.getOptLockRevision()).as("lock revision is wrong").isEqualTo(
distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).get().getOptLockRevision());
@@ -872,7 +868,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet(
ds.getId(), ActionType.SOFT,
org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME,
Lists.newArrayList(target.getControllerId()));
Arrays.asList(target.getControllerId()));
final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0))
.get();
// verify preparation
@@ -897,7 +893,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet(
ds.getId(), ActionType.FORCED,
org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME,
Lists.newArrayList(target.getControllerId()));
Arrays.asList(target.getControllerId()));
final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0))
.get();
// verify perparation

View File

@@ -13,6 +13,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
@@ -31,7 +32,6 @@ import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.exception.UnsupportedSoftwareModuleForThisDistributionSetException;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
@@ -75,9 +75,6 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isNotPresent();
assertThat(distributionSetManagement.findDistributionSetMetadata(set.getId(), NOT_EXIST_ID)).isNotPresent();
assertThat(distributionSetManagement.findDistributionSetTypeById(NOT_EXIST_IDL)).isNotPresent();
assertThat(distributionSetManagement.findDistributionSetTypeByKey(NOT_EXIST_ID)).isNotPresent();
assertThat(distributionSetManagement.findDistributionSetTypeByName(NOT_EXIST_ID)).isNotPresent();
}
@Test
@@ -91,22 +88,11 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
final DistributionSetTag dsTag = testdataFactory.createDistributionSetTags(1).get(0);
final SoftwareModule module = testdataFactory.createSoftwareModuleApp();
verifyThrownExceptionBy(() -> distributionSetManagement.assignMandatorySoftwareModuleTypes(NOT_EXIST_IDL,
Lists.newArrayList(osType.getId())), "DistributionSetType");
verifyThrownExceptionBy(() -> distributionSetManagement.assignMandatorySoftwareModuleTypes(
testdataFactory.findOrCreateDistributionSetType("xxx", "xxx").getId(),
Lists.newArrayList(NOT_EXIST_IDL)), "SoftwareModuleType");
verifyThrownExceptionBy(() -> distributionSetManagement.assignOptionalSoftwareModuleTypes(1234L,
Lists.newArrayList(osType.getId())), "DistributionSetType");
verifyThrownExceptionBy(() -> distributionSetManagement.assignOptionalSoftwareModuleTypes(
testdataFactory.findOrCreateDistributionSetType("xxx", "xxx").getId(),
Lists.newArrayList(NOT_EXIST_IDL)), "SoftwareModuleType");
verifyThrownExceptionBy(() -> distributionSetManagement.assignSoftwareModules(NOT_EXIST_IDL,
Lists.newArrayList(module.getId())), "DistributionSet");
verifyThrownExceptionBy(
() -> distributionSetManagement.assignSoftwareModules(set.getId(), Lists.newArrayList(NOT_EXIST_IDL)),
() -> distributionSetManagement.assignSoftwareModules(NOT_EXIST_IDL, Arrays.asList(module.getId())),
"DistributionSet");
verifyThrownExceptionBy(
() -> distributionSetManagement.assignSoftwareModules(set.getId(), Arrays.asList(NOT_EXIST_IDL)),
"SoftwareModule");
verifyThrownExceptionBy(() -> distributionSetManagement.unassignSoftwareModule(NOT_EXIST_IDL, module.getId()),
@@ -114,12 +100,10 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> distributionSetManagement.unassignSoftwareModule(set.getId(), NOT_EXIST_IDL),
"SoftwareModule");
verifyThrownExceptionBy(
() -> distributionSetManagement.assignTag(Lists.newArrayList(set.getId()), NOT_EXIST_IDL),
verifyThrownExceptionBy(() -> distributionSetManagement.assignTag(Arrays.asList(set.getId()), NOT_EXIST_IDL),
"DistributionSetTag");
verifyThrownExceptionBy(
() -> distributionSetManagement.assignTag(Lists.newArrayList(NOT_EXIST_IDL), dsTag.getId()),
verifyThrownExceptionBy(() -> distributionSetManagement.assignTag(Arrays.asList(NOT_EXIST_IDL), dsTag.getId()),
"DistributionSet");
verifyThrownExceptionBy(() -> distributionSetManagement.findDistributionSetsByTag(PAGE, NOT_EXIST_IDL),
@@ -129,10 +113,10 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
"DistributionSetTag");
verifyThrownExceptionBy(
() -> distributionSetManagement.toggleTagAssignment(Lists.newArrayList(NOT_EXIST_IDL), dsTag.getName()),
() -> distributionSetManagement.toggleTagAssignment(Arrays.asList(NOT_EXIST_IDL), dsTag.getName()),
"DistributionSet");
verifyThrownExceptionBy(
() -> distributionSetManagement.toggleTagAssignment(Lists.newArrayList(set.getId()), NOT_EXIST_ID),
() -> distributionSetManagement.toggleTagAssignment(Arrays.asList(set.getId()), NOT_EXIST_ID),
"DistributionSetTag");
verifyThrownExceptionBy(() -> distributionSetManagement.unAssignTag(set.getId(), NOT_EXIST_IDL),
@@ -141,19 +125,15 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> distributionSetManagement.unAssignTag(NOT_EXIST_IDL, dsTag.getId()),
"DistributionSet");
verifyThrownExceptionBy(() -> distributionSetManagement.countDistributionSetsByType(NOT_EXIST_IDL),
"DistributionSet");
verifyThrownExceptionBy(
() -> distributionSetManagement
.createDistributionSet(entityFactory.distributionSet().create().name("xxx").type(NOT_EXIST_ID)),
"DistributionSetType");
verifyThrownExceptionBy(() -> distributionSetManagement.createDistributionSetMetadata(NOT_EXIST_IDL,
Lists.newArrayList(entityFactory.generateMetadata("123", "123"))), "DistributionSet");
Arrays.asList(entityFactory.generateMetadata("123", "123"))), "DistributionSet");
verifyThrownExceptionBy(
() -> distributionSetManagement.deleteDistributionSet(Lists.newArrayList(NOT_EXIST_IDL)),
verifyThrownExceptionBy(() -> distributionSetManagement.deleteDistributionSet(Arrays.asList(NOT_EXIST_IDL)),
"DistributionSet");
verifyThrownExceptionBy(() -> distributionSetManagement.deleteDistributionSet(NOT_EXIST_IDL),
"DistributionSet");
@@ -163,9 +143,6 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
() -> distributionSetManagement.deleteDistributionSetMetadata(set.getId(), NOT_EXIST_ID),
"DistributionSetMetadata");
verifyThrownExceptionBy(() -> distributionSetManagement.deleteDistributionSetType(NOT_EXIST_IDL),
"DistributionSetType");
verifyThrownExceptionBy(() -> distributionSetManagement.findDistributionSetByAction(NOT_EXIST_IDL), "Action");
verifyThrownExceptionBy(() -> distributionSetManagement.findDistributionSetMetadata(NOT_EXIST_IDL, "xxx"),
@@ -192,124 +169,6 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> distributionSetManagement.updateDistributionSetMetadata(set.getId(),
entityFactory.generateMetadata(NOT_EXIST_ID, "xxx")), "DistributionSetMetadata");
verifyThrownExceptionBy(
() -> distributionSetManagement
.updateDistributionSetType(entityFactory.distributionSetType().update(NOT_EXIST_IDL)),
"DistributionSet");
}
@Test
@Description("Tests the successfull module update of unused distribution set type which is in fact allowed.")
public void updateUnassignedDistributionSetTypeModules() {
final DistributionSetType updatableType = distributionSetManagement.createDistributionSetType(
entityFactory.distributionSetType().create().key("updatableType").name("to be deleted"));
assertThat(
distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes())
.isEmpty();
// add OS
distributionSetManagement.assignMandatorySoftwareModuleTypes(updatableType.getId(),
Sets.newHashSet(osType.getId()));
assertThat(
distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes())
.containsOnly(osType);
// add JVM
distributionSetManagement.assignMandatorySoftwareModuleTypes(updatableType.getId(),
Sets.newHashSet(runtimeType.getId()));
assertThat(
distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes())
.containsOnly(osType, runtimeType);
// remove OS
distributionSetManagement.unassignSoftwareModuleType(updatableType.getId(), osType.getId());
assertThat(
distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes())
.containsOnly(runtimeType);
}
@Test
@Description("Tests the successfull update of used distribution set type meta data which is in fact allowed.")
public void updateAssignedDistributionSetTypeMetaData() {
final DistributionSetType nonUpdatableType = distributionSetManagement.createDistributionSetType(entityFactory
.distributionSetType().create().key("updatableType").name("to be deleted").colour("test123"));
assertThat(
distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes())
.isEmpty();
distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft")
.version("1").type(nonUpdatableType.getKey()));
distributionSetManagement.updateDistributionSetType(
entityFactory.distributionSetType().update(nonUpdatableType.getId()).description("a new description"));
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getDescription())
.isEqualTo("a new description");
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getColour())
.isEqualTo("test123");
}
@Test
@Description("Tests the unsuccessfull update of used distribution set type (module addition).")
public void addModuleToAssignedDistributionSetTypeFails() {
final DistributionSetType nonUpdatableType = distributionSetManagement.createDistributionSetType(
entityFactory.distributionSetType().create().key("updatableType").name("to be deleted"));
assertThat(
distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes())
.isEmpty();
distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft")
.version("1").type(nonUpdatableType.getKey()));
assertThatThrownBy(() -> distributionSetManagement.assignMandatorySoftwareModuleTypes(nonUpdatableType.getId(),
Sets.newHashSet(osType.getId()))).isInstanceOf(EntityReadOnlyException.class);
}
@Test
@Description("Tests the unsuccessfull update of used distribution set type (module removal).")
public void removeModuleToAssignedDistributionSetTypeFails() {
DistributionSetType nonUpdatableType = distributionSetManagement.createDistributionSetType(
entityFactory.distributionSetType().create().key("updatableType").name("to be deleted"));
assertThat(
distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes())
.isEmpty();
nonUpdatableType = distributionSetManagement.assignMandatorySoftwareModuleTypes(nonUpdatableType.getId(),
Sets.newHashSet(osType.getId()));
distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft")
.version("1").type(nonUpdatableType.getKey()));
final Long typeId = nonUpdatableType.getId();
assertThatThrownBy(() -> distributionSetManagement.unassignSoftwareModuleType(typeId, osType.getId()))
.isInstanceOf(EntityReadOnlyException.class);
}
@Test
@Description("Tests the successfull deletion of unused (hard delete) distribution set types.")
public void deleteUnassignedDistributionSetType() {
final JpaDistributionSetType hardDelete = (JpaDistributionSetType) distributionSetManagement
.createDistributionSetType(
entityFactory.distributionSetType().create().key("delete").name("to be deleted"));
assertThat(distributionSetTypeRepository.findAll()).contains(hardDelete);
distributionSetManagement.deleteDistributionSetType(hardDelete.getId());
assertThat(distributionSetTypeRepository.findAll()).doesNotContain(hardDelete);
}
@Test
@Description("Tests the successfull deletion of used (soft delete) distribution set types.")
public void deleteAssignedDistributionSetType() {
final JpaDistributionSetType softDelete = (JpaDistributionSetType) distributionSetManagement
.createDistributionSetType(
entityFactory.distributionSetType().create().key("softdeleted").name("to be deleted"));
assertThat(distributionSetTypeRepository.findAll()).contains(softDelete);
distributionSetManagement.createDistributionSet(
entityFactory.distributionSet().create().name("softdeleted").version("1").type(softDelete.getKey()));
distributionSetManagement.deleteDistributionSetType(softDelete.getId());
assertThat(distributionSetManagement.findDistributionSetTypeByKey("softdeleted").get().isDeleted())
.isEqualTo(true);
}
@Test
@@ -451,12 +310,14 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
@Description("Ensures that it is not possible to add a software module that is not defined of the DS's type.")
public void updateDistributionSetUnsupportedModuleFails() {
final DistributionSet set = distributionSetManagement
.createDistributionSet(entityFactory.distributionSet().create().name("agent-hub2").version("1.0.5")
.type(distributionSetManagement.createDistributionSetType(entityFactory.distributionSetType()
.create().key("test").name("test").mandatory(Lists.newArrayList(osType.getId())))
.createDistributionSet(
entityFactory.distributionSet().create().name("agent-hub2").version("1.0.5")
.type(distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create()
.key("test").name("test").mandatory(Arrays.asList(osType.getId())))
.getKey()));
final SoftwareModule module = softwareManagement.createSoftwareModule(
final SoftwareModule module = softwareModuleManagement.createSoftwareModule(
entityFactory.softwareModule().create().name("agent-hub2").version("1.0.5").type(appType.getKey()));
// update data
@@ -554,7 +415,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assignDistributionSet(dsThree.getId(), tFirst.getControllerId());
// set installed
testdataFactory.sendUpdateActionStatusToTargets(Collections.singleton(tSecond), Status.FINISHED,
Lists.newArrayList("some message"));
Arrays.asList("some message"));
assignDistributionSet(dsFour.getId(), tSecond.getControllerId());
@@ -593,19 +454,19 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet dsInComplete = distributionSetManagement.createDistributionSet(entityFactory
.distributionSet().create().name("notcomplete").version("1").type(standardDsType.getKey()));
DistributionSetType newType = distributionSetManagement.createDistributionSetType(
DistributionSetType newType = distributionSetTypeManagement.createDistributionSetType(
entityFactory.distributionSetType().create().key("foo").name("bar").description("test"));
distributionSetManagement.assignMandatorySoftwareModuleTypes(newType.getId(),
Lists.newArrayList(osType.getId()));
newType = distributionSetManagement.assignOptionalSoftwareModuleTypes(newType.getId(),
Lists.newArrayList(appType.getId(), runtimeType.getId()));
distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(newType.getId(),
Arrays.asList(osType.getId()));
newType = distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(newType.getId(),
Arrays.asList(appType.getId(), runtimeType.getId()));
final DistributionSet dsNewType = distributionSetManagement.createDistributionSet(
entityFactory.distributionSet().create().name("newtype").version("1").type(newType.getKey()).modules(
dsDeleted.getModules().stream().map(SoftwareModule::getId).collect(Collectors.toList())));
assignDistributionSet(dsDeleted, Lists.newArrayList(testdataFactory.createTargets(5)));
assignDistributionSet(dsDeleted, testdataFactory.createTargets(5));
distributionSetManagement.deleteDistributionSet(dsDeleted.getId());
dsDeleted = distributionSetManagement.findDistributionSetById(dsDeleted.getId()).get();
@@ -635,13 +496,12 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
// search for not deleted
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(1);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(false);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(202);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(202);
// search for completed
expected = new ArrayList<>();
@@ -651,62 +511,51 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
expected.add(dsNewType);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(202)
.containsOnly(expected.toArray(new DistributionSet[0]));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(202).containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE);
expected = new ArrayList<>();
expected.add(dsInComplete);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0]));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(1).containsOnly(expected.toArray(new DistributionSet[0]));
// search for type
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(newType);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(1);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(202);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(202);
// search for text
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setSearchText("%test2");
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(100);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(100);
// search for tags
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagA.getName()));
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(200);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setTagNames(Arrays.asList(dsTagA.getName()));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(200);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setTagNames(Arrays.asList(dsTagB.getName()));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(100);
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagB.getName()));
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(100);
.setTagNames(Arrays.asList(dsTagA.getName(), dsTagB.getName()));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(200);
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagA.getName(), dsTagB.getName()));
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(200);
.setTagNames(Arrays.asList(dsTagC.getName(), dsTagB.getName()));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(100);
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagC.getName(), dsTagB.getName()));
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(100);
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagC.getName()));
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setTagNames(Arrays.asList(dsTagC.getName()));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(0);
// combine deleted and complete
expected = new ArrayList<>();
@@ -716,29 +565,26 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setIsDeleted(Boolean.FALSE);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(201)
.containsOnly(expected.toArray(new DistributionSet[0]));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(201).containsOnly(expected.toArray(new DistributionSet[0]));
expected = new ArrayList<>();
expected.add(dsInComplete);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0]));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(1).containsOnly(expected.toArray(new DistributionSet[0]));
expected = new ArrayList<>();
expected.add(dsDeleted);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setIsDeleted(Boolean.TRUE);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0]));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(1).containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE)
.setIsComplete(Boolean.FALSE);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(0);
// combine deleted and complete and type
expected = new ArrayList<>();
@@ -746,68 +592,62 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
expected.addAll(ds100Group2);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.FALSE)
.setIsComplete(Boolean.TRUE).setType(standardDsType);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(200)
.containsOnly(expected.toArray(new DistributionSet[0]));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(200).containsOnly(expected.toArray(new DistributionSet[0]));
expected = new ArrayList<>();
expected.add(dsDeleted);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setType(standardDsType).setIsDeleted(Boolean.TRUE);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0]));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(1).containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE)
.setIsComplete(Boolean.FALSE).setType(standardDsType);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(0);
expected = new ArrayList<>();
expected.add(dsNewType);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE).setType(newType);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0]));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(1).containsOnly(expected.toArray(new DistributionSet[0]));
// combine deleted and complete and type and text
expected = new ArrayList<>();
expected.addAll(ds100Group2);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setType(standardDsType).setSearchText("%test2");
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(100)
.containsOnly(expected.toArray(new DistributionSet[0]));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(100).containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setIsDeleted(Boolean.TRUE).setType(standardDsType).setSearchText("%test2");
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(0);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType).setSearchText("%test2")
.setIsComplete(false).setIsDeleted(false);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(0);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(newType).setSearchText("%test2")
.setIsComplete(Boolean.TRUE).setIsDeleted(false);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(0);
// combine deleted and complete and type and text and tag
expected = new ArrayList<>();
expected.addAll(ds100Group2);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true).setType(standardDsType)
.setSearchText("%test2").setTagNames(Lists.newArrayList(dsTagA.getName()));
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(100)
.containsOnly(expected.toArray(new DistributionSet[0]));
.setSearchText("%test2").setTagNames(Arrays.asList(dsTagA.getName()));
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(100).containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType).setSearchText("%test2")
.setTagNames(Lists.newArrayList(dsTagA.getName())).setIsComplete(Boolean.FALSE)
.setIsDeleted(Boolean.FALSE);
assertThat(distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
.setTagNames(Arrays.asList(dsTagA.getName())).setIsComplete(Boolean.FALSE).setIsDeleted(Boolean.FALSE);
assertThat(distributionSetManagement.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build())
.getContent()).hasSize(0);
}
@@ -891,7 +731,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
// delete assigned ds
assertThat(distributionSetRepository.findAll()).hasSize(4);
distributionSetManagement
.deleteDistributionSet(Lists.newArrayList(dsToTargetAssigned.getId(), dsToRolloutAssigned.getId()));
.deleteDistributionSet(Arrays.asList(dsToTargetAssigned.getId(), dsToRolloutAssigned.getId()));
// not assigned so not marked as deleted
assertThat(distributionSetRepository.findAll()).hasSize(4);

View File

@@ -0,0 +1,186 @@
/**
* 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.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Arrays;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.Test;
import com.google.common.collect.Sets;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
/**
* {@link DistributionSetManagement} tests.
*
*/
@Features("Component Tests - Repository")
@Stories("DistributionSet Management")
public class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that management get access react as specfied on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = DistributionSetCreatedEvent.class, count = 0) })
public void nonExistingEntityAccessReturnsNotPresent() {
assertThat(distributionSetTypeManagement.findDistributionSetTypeById(NOT_EXIST_IDL)).isNotPresent();
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey(NOT_EXIST_ID)).isNotPresent();
assertThat(distributionSetTypeManagement.findDistributionSetTypeByName(NOT_EXIST_ID)).isNotPresent();
}
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({ @Expect(type = DistributionSetCreatedEvent.class, count = 0) })
public void entityQueriesReferringToNotExistingEntitiesThrowsException() {
verifyThrownExceptionBy(() -> distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(NOT_EXIST_IDL,
Arrays.asList(osType.getId())), "DistributionSetType");
verifyThrownExceptionBy(() -> distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(
testdataFactory.findOrCreateDistributionSetType("xxx", "xxx").getId(), Arrays.asList(NOT_EXIST_IDL)),
"SoftwareModuleType");
verifyThrownExceptionBy(() -> distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(1234L,
Arrays.asList(osType.getId())), "DistributionSetType");
verifyThrownExceptionBy(() -> distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(
testdataFactory.findOrCreateDistributionSetType("xxx", "xxx").getId(), Arrays.asList(NOT_EXIST_IDL)),
"SoftwareModuleType");
verifyThrownExceptionBy(() -> distributionSetTypeManagement.countDistributionSetsByType(NOT_EXIST_IDL),
"DistributionSet");
verifyThrownExceptionBy(() -> distributionSetTypeManagement.deleteDistributionSetType(NOT_EXIST_IDL),
"DistributionSetType");
verifyThrownExceptionBy(
() -> distributionSetTypeManagement
.updateDistributionSetType(entityFactory.distributionSetType().update(NOT_EXIST_IDL)),
"DistributionSet");
}
@Test
@Description("Tests the successfull module update of unused distribution set type which is in fact allowed.")
public void updateUnassignedDistributionSetTypeModules() {
final DistributionSetType updatableType = distributionSetTypeManagement.createDistributionSetType(
entityFactory.distributionSetType().create().key("updatableType").name("to be deleted"));
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("updatableType").get()
.getMandatoryModuleTypes()).isEmpty();
// add OS
distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(updatableType.getId(),
Sets.newHashSet(osType.getId()));
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("updatableType").get()
.getMandatoryModuleTypes()).containsOnly(osType);
// add JVM
distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(updatableType.getId(),
Sets.newHashSet(runtimeType.getId()));
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("updatableType").get()
.getMandatoryModuleTypes()).containsOnly(osType, runtimeType);
// remove OS
distributionSetTypeManagement.unassignSoftwareModuleType(updatableType.getId(), osType.getId());
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("updatableType").get()
.getMandatoryModuleTypes()).containsOnly(runtimeType);
}
@Test
@Description("Tests the successfull update of used distribution set type meta data which is in fact allowed.")
public void updateAssignedDistributionSetTypeMetaData() {
final DistributionSetType nonUpdatableType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("updatableType")
.name("to be deleted").colour("test123"));
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("updatableType").get()
.getMandatoryModuleTypes()).isEmpty();
distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft")
.version("1").type(nonUpdatableType.getKey()));
distributionSetTypeManagement.updateDistributionSetType(
entityFactory.distributionSetType().update(nonUpdatableType.getId()).description("a new description"));
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("updatableType").get().getDescription())
.isEqualTo("a new description");
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("updatableType").get().getColour())
.isEqualTo("test123");
}
@Test
@Description("Tests the unsuccessfull update of used distribution set type (module addition).")
public void addModuleToAssignedDistributionSetTypeFails() {
final DistributionSetType nonUpdatableType = distributionSetTypeManagement.createDistributionSetType(
entityFactory.distributionSetType().create().key("updatableType").name("to be deleted"));
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("updatableType").get()
.getMandatoryModuleTypes()).isEmpty();
distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft")
.version("1").type(nonUpdatableType.getKey()));
assertThatThrownBy(() -> distributionSetTypeManagement
.assignMandatorySoftwareModuleTypes(nonUpdatableType.getId(), Sets.newHashSet(osType.getId())))
.isInstanceOf(EntityReadOnlyException.class);
}
@Test
@Description("Tests the unsuccessfull update of used distribution set type (module removal).")
public void removeModuleToAssignedDistributionSetTypeFails() {
DistributionSetType nonUpdatableType = distributionSetTypeManagement.createDistributionSetType(
entityFactory.distributionSetType().create().key("updatableType").name("to be deleted"));
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("updatableType").get()
.getMandatoryModuleTypes()).isEmpty();
nonUpdatableType = distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(nonUpdatableType.getId(),
Sets.newHashSet(osType.getId()));
distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft")
.version("1").type(nonUpdatableType.getKey()));
final Long typeId = nonUpdatableType.getId();
assertThatThrownBy(() -> distributionSetTypeManagement.unassignSoftwareModuleType(typeId, osType.getId()))
.isInstanceOf(EntityReadOnlyException.class);
}
@Test
@Description("Tests the successfull deletion of unused (hard delete) distribution set types.")
public void deleteUnassignedDistributionSetType() {
final JpaDistributionSetType hardDelete = (JpaDistributionSetType) distributionSetTypeManagement
.createDistributionSetType(
entityFactory.distributionSetType().create().key("delete").name("to be deleted"));
assertThat(distributionSetTypeRepository.findAll()).contains(hardDelete);
distributionSetTypeManagement.deleteDistributionSetType(hardDelete.getId());
assertThat(distributionSetTypeRepository.findAll()).doesNotContain(hardDelete);
}
@Test
@Description("Tests the successfull deletion of used (soft delete) distribution set types.")
public void deleteAssignedDistributionSetType() {
final JpaDistributionSetType softDelete = (JpaDistributionSetType) distributionSetTypeManagement
.createDistributionSetType(
entityFactory.distributionSetType().create().key("softdeleted").name("to be deleted"));
assertThat(distributionSetTypeRepository.findAll()).contains(softDelete);
distributionSetManagement.createDistributionSet(
entityFactory.distributionSet().create().name("softdeleted").version("1").type(softDelete.getKey()));
distributionSetTypeManagement.deleteDistributionSetType(softDelete.getId());
assertThat(distributionSetTypeManagement.findDistributionSetTypeByKey("softdeleted").get().isDeleted())
.isEqualTo(true);
}
}

View File

@@ -26,6 +26,7 @@ import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.builder.RolloutCreate;
import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate;
import org.eclipse.hawkbit.repository.event.remote.RolloutDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.RolloutGroupDeletedEvent;
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.ActionUpdatedEvent;
@@ -69,8 +70,6 @@ import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import com.google.common.collect.Lists;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
@@ -282,12 +281,12 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
// finish group one by finishing targets and deleting targets
final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
createdRollout.getId(), Status.RUNNING);
final List<JpaAction> runningActions = Lists.newArrayList(runningActionsSlice.iterator());
final List<JpaAction> runningActions = runningActionsSlice.getContent();
finishAction(runningActions.get(0));
finishAction(runningActions.get(1));
finishAction(runningActions.get(2));
targetManagement.deleteTargets(Lists.newArrayList(runningActions.get(3).getTarget().getId(),
runningActions.get(4).getTarget().getId()));
targetManagement.deleteTargets(
Arrays.asList(runningActions.get(3).getTarget().getId(), runningActions.get(4).getTarget().getId()));
}
@Step("Check the status of the rollout groups, second group should be in running status")
@@ -304,10 +303,10 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
private void finishActionAndDeleteTargetsOfSecondRunningGroup(final Rollout createdRollout) {
final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
createdRollout.getId(), Status.RUNNING);
final List<JpaAction> runningActions = Lists.newArrayList(runningActionsSlice.iterator());
final List<JpaAction> runningActions = runningActionsSlice.getContent();
finishAction(runningActions.get(0));
targetManagement.deleteTargets(
Lists.newArrayList(runningActions.get(1).getTarget().getId(), runningActions.get(2).getTarget().getId(),
Arrays.asList(runningActions.get(1).getTarget().getId(), runningActions.get(2).getTarget().getId(),
runningActions.get(3).getTarget().getId(), runningActions.get(4).getTarget().getId()));
}
@@ -316,8 +315,8 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
private void deleteAllTargetsFromThirdGroup(final Rollout createdRollout) {
final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
createdRollout.getId(), Status.SCHEDULED);
final List<JpaAction> runningActions = Lists.newArrayList(runningActionsSlice.iterator());
targetManagement.deleteTargets(Lists.newArrayList(runningActions.get(0).getTarget().getId(),
final List<JpaAction> runningActions = runningActionsSlice.getContent();
targetManagement.deleteTargets(Arrays.asList(runningActions.get(0).getTarget().getId(),
runningActions.get(1).getTarget().getId(), runningActions.get(2).getTarget().getId(),
runningActions.get(3).getTarget().getId(), runningActions.get(4).getTarget().getId()));
}
@@ -1417,6 +1416,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 25), @Expect(type = RolloutUpdatedEvent.class, count = 2),
@Expect(type = RolloutGroupCreatedEvent.class, count = 5),
@Expect(type = RolloutGroupDeletedEvent.class, count = 5),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = RolloutGroupUpdatedEvent.class, count = 5) })
public void deleteRolloutWhichHasNeverStartedIsHardDeleted() {
@@ -1447,6 +1447,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
@Expect(type = TargetCreatedEvent.class, count = 25), @Expect(type = TargetUpdatedEvent.class, count = 2),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 2),
@Expect(type = RolloutGroupCreatedEvent.class, count = 5),
@Expect(type = RolloutGroupDeletedEvent.class, count = 5),
@Expect(type = ActionCreatedEvent.class, count = 10), @Expect(type = ActionUpdatedEvent.class, count = 2),
@Expect(type = RolloutDeletedEvent.class, count = 1) })
public void deleteRolloutWhichHasBeenStartedBeforeIsSoftDeleted() {

View File

@@ -14,20 +14,17 @@ import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.validation.ConstraintViolationException;
import org.apache.commons.lang3.RandomUtils;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.jpa.model.JpaArtifact;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Artifact;
@@ -54,8 +51,8 @@ import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Repository")
@Stories("Software Management")
public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
@Stories("Software Module Management")
public class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that management get access reacts as specfied on calls for non existing entities by means "
@@ -64,16 +61,13 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
public void nonExistingEntityAccessReturnsNotPresent() {
final SoftwareModule module = testdataFactory.createSoftwareModuleApp();
assertThat(softwareManagement.findSoftwareModuleById(1234L)).isNotPresent();
assertThat(softwareModuleManagement.findSoftwareModuleById(1234L)).isNotPresent();
assertThat(softwareManagement.findSoftwareModuleTypeById(NOT_EXIST_IDL)).isNotPresent();
assertThat(softwareManagement.findSoftwareModuleTypeByKey(NOT_EXIST_ID)).isNotPresent();
assertThat(softwareManagement.findSoftwareModuleTypeByName(NOT_EXIST_ID)).isNotPresent();
assertThat(softwareManagement.findSoftwareModuleByNameAndVersion(NOT_EXIST_ID, NOT_EXIST_ID, osType.getId()))
assertThat(
softwareModuleManagement.findSoftwareModuleByNameAndVersion(NOT_EXIST_ID, NOT_EXIST_ID, osType.getId()))
.isNotPresent();
assertThat(softwareManagement.findSoftwareModuleMetadata(module.getId(), NOT_EXIST_ID)).isNotPresent();
assertThat(softwareModuleManagement.findSoftwareModuleMetadata(module.getId(), NOT_EXIST_ID)).isNotPresent();
}
@Test
@@ -84,87 +78,53 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule module = testdataFactory.createSoftwareModuleApp();
verifyThrownExceptionBy(
() -> softwareManagement.createSoftwareModule(
Lists.newArrayList(entityFactory.softwareModule().create().name("xxx").type(NOT_EXIST_ID))),
() -> softwareModuleManagement.createSoftwareModule(
Arrays.asList(entityFactory.softwareModule().create().name("xxx").type(NOT_EXIST_ID))),
"SoftwareModuleType");
verifyThrownExceptionBy(
() -> softwareManagement
() -> softwareModuleManagement
.createSoftwareModule(entityFactory.softwareModule().create().name("xxx").type(NOT_EXIST_ID)),
"SoftwareModuleType");
verifyThrownExceptionBy(() -> softwareManagement.createSoftwareModuleMetadata(NOT_EXIST_IDL,
verifyThrownExceptionBy(() -> softwareModuleManagement.createSoftwareModuleMetadata(NOT_EXIST_IDL,
entityFactory.generateMetadata("xxx", "xxx")), "SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.createSoftwareModuleMetadata(NOT_EXIST_IDL,
Lists.newArrayList(entityFactory.generateMetadata("xxx", "xxx"))), "SoftwareModule");
verifyThrownExceptionBy(() -> softwareModuleManagement.createSoftwareModuleMetadata(NOT_EXIST_IDL,
Arrays.asList(entityFactory.generateMetadata("xxx", "xxx"))), "SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.deleteSoftwareModule(NOT_EXIST_IDL), "SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.deleteSoftwareModules(Lists.newArrayList(NOT_EXIST_IDL)),
verifyThrownExceptionBy(() -> softwareModuleManagement.deleteSoftwareModule(NOT_EXIST_IDL), "SoftwareModule");
verifyThrownExceptionBy(() -> softwareModuleManagement.deleteSoftwareModules(Arrays.asList(NOT_EXIST_IDL)),
"SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.deleteSoftwareModuleMetadata(NOT_EXIST_IDL, "xxx"),
verifyThrownExceptionBy(() -> softwareModuleManagement.deleteSoftwareModuleMetadata(NOT_EXIST_IDL, "xxx"),
"SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.deleteSoftwareModuleMetadata(module.getId(), NOT_EXIST_ID),
verifyThrownExceptionBy(
() -> softwareModuleManagement.deleteSoftwareModuleMetadata(module.getId(), NOT_EXIST_ID),
"SoftwareModuleMetadata");
verifyThrownExceptionBy(() -> softwareManagement.updateSoftwareModuleMetadata(NOT_EXIST_IDL,
verifyThrownExceptionBy(() -> softwareModuleManagement.updateSoftwareModuleMetadata(NOT_EXIST_IDL,
entityFactory.generateMetadata("xxx", "xxx")), "SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.updateSoftwareModuleMetadata(module.getId(),
verifyThrownExceptionBy(() -> softwareModuleManagement.updateSoftwareModuleMetadata(module.getId(),
entityFactory.generateMetadata(NOT_EXIST_ID, "xxx")), "SoftwareModuleMetadata");
verifyThrownExceptionBy(() -> softwareManagement.deleteSoftwareModuleType(NOT_EXIST_IDL), "SoftwareModuleType");
verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleByAssignedTo(PAGE, NOT_EXIST_IDL),
verifyThrownExceptionBy(() -> softwareModuleManagement.findSoftwareModuleByAssignedTo(PAGE, NOT_EXIST_IDL),
"DistributionSet");
verifyThrownExceptionBy(
() -> softwareManagement.findSoftwareModuleByNameAndVersion("xxx", "xxx", NOT_EXIST_IDL),
() -> softwareModuleManagement.findSoftwareModuleByNameAndVersion("xxx", "xxx", NOT_EXIST_IDL),
"SoftwareModuleType");
verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleMetadata(NOT_EXIST_IDL, NOT_EXIST_ID),
verifyThrownExceptionBy(() -> softwareModuleManagement.findSoftwareModuleMetadata(NOT_EXIST_IDL, NOT_EXIST_ID),
"SoftwareModule");
verifyThrownExceptionBy(
() -> softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(PAGE, NOT_EXIST_IDL),
() -> softwareModuleManagement.findSoftwareModuleMetadataBySoftwareModuleId(PAGE, NOT_EXIST_IDL),
"SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(NOT_EXIST_IDL,
"name==*", PAGE), "SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModulesByType(PAGE, NOT_EXIST_IDL),
verifyThrownExceptionBy(() -> softwareModuleManagement
.findSoftwareModuleMetadataBySoftwareModuleId(NOT_EXIST_IDL, "name==*", PAGE), "SoftwareModule");
verifyThrownExceptionBy(() -> softwareModuleManagement.findSoftwareModulesByType(PAGE, NOT_EXIST_IDL),
"SoftwareModule");
verifyThrownExceptionBy(
() -> softwareManagement.updateSoftwareModule(entityFactory.softwareModule().update(NOT_EXIST_IDL)),
"SoftwareModule");
verifyThrownExceptionBy(
() -> softwareManagement.updateSoftwareModuleType(entityFactory.softwareModuleType().update(1234L)),
"SoftwareModuleType");
}
@Test
@Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.")
public void updateNothingResultsInUnchangedRepositoryForType() {
final SoftwareModuleType created = softwareManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("test-key").name("test-name"));
final SoftwareModuleType updated = softwareManagement
.updateSoftwareModuleType(entityFactory.softwareModuleType().update(created.getId()));
assertThat(updated.getOptLockRevision())
.as("Expected version number of updated entitity to be equal to created version")
.isEqualTo(created.getOptLockRevision());
}
@Test
@Description("Calling update for changed fields results in change in the repository.")
public void updateSoftareModuleTypeFieldsToNewValue() {
final SoftwareModuleType created = softwareManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("test-key").name("test-name"));
final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(
entityFactory.softwareModuleType().update(created.getId()).description("changed").colour("changed"));
assertThat(updated.getOptLockRevision()).as("Expected version number of updated entitity is")
.isEqualTo(created.getOptLockRevision() + 1);
assertThat(updated.getDescription()).as("Updated description is").isEqualTo("changed");
assertThat(updated.getColour()).as("Updated vendor is").isEqualTo("changed");
verifyThrownExceptionBy(() -> softwareModuleManagement
.updateSoftwareModule(entityFactory.softwareModule().update(NOT_EXIST_IDL)), "SoftwareModule");
}
@Test
@@ -172,7 +132,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
public void updateNothingResultsInUnchangedRepository() {
final SoftwareModule ah = testdataFactory.createSoftwareModuleOs();
final SoftwareModule updated = softwareManagement
final SoftwareModule updated = softwareModuleManagement
.updateSoftwareModule(entityFactory.softwareModule().update(ah.getId()));
assertThat(updated.getOptLockRevision())
@@ -185,7 +145,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
public void updateSoftareModuleFieldsToNewValue() {
final SoftwareModule ah = testdataFactory.createSoftwareModuleOs();
final SoftwareModule updated = softwareManagement.updateSoftwareModule(
final SoftwareModule updated = softwareModuleManagement.updateSoftwareModule(
entityFactory.softwareModule().update(ah.getId()).description("changed").vendor("changed"));
assertThat(updated.getOptLockRevision()).as("Expected version number of updated entitity is")
@@ -206,65 +166,51 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Create Software Module Types call fails when called for existing entities.")
public void createModuleTypesCallFailsForExistingTypes() {
final List<SoftwareModuleTypeCreate> created = Lists.newArrayList(
entityFactory.softwareModuleType().create().key("test-key").name("test-name"),
entityFactory.softwareModuleType().create().key("test-key2").name("test-name2"));
softwareManagement.createSoftwareModuleType(created);
try {
softwareManagement.createSoftwareModuleType(created);
fail("Should not have worked as module already exists.");
} catch (final EntityAlreadyExistsException e) {
}
}
@Test
@Description("searched for software modules based on the various filter options, e.g. name,desc,type, version.")
public void findSoftwareModuleByFilters() {
final SoftwareModule ah = softwareManagement.createSoftwareModule(
final SoftwareModule ah = softwareModuleManagement.createSoftwareModule(
entityFactory.softwareModule().create().type(appType).name("agent-hub").version("1.0.1"));
final SoftwareModule jvm = softwareManagement.createSoftwareModule(
final SoftwareModule jvm = softwareModuleManagement.createSoftwareModule(
entityFactory.softwareModule().create().type(runtimeType).name("oracle-jre").version("1.7.2"));
final SoftwareModule os = softwareManagement.createSoftwareModule(
final SoftwareModule os = softwareModuleManagement.createSoftwareModule(
entityFactory.softwareModule().create().type(osType).name("poky").version("3.0.2"));
final SoftwareModule ah2 = softwareManagement.createSoftwareModule(
final SoftwareModule ah2 = softwareModuleManagement.createSoftwareModule(
entityFactory.softwareModule().create().type(appType).name("agent-hub").version("1.0.2"));
JpaDistributionSet ds = (JpaDistributionSet) distributionSetManagement
.createDistributionSet(entityFactory.distributionSet().create().name("ds-1").version("1.0.1")
.type(standardDsType).modules(Lists.newArrayList(os.getId(), jvm.getId(), ah2.getId())));
.type(standardDsType).modules(Arrays.asList(os.getId(), jvm.getId(), ah2.getId())));
final JpaTarget target = (JpaTarget) testdataFactory.createTarget();
ds = (JpaDistributionSet) assignSet(target, ds).getDistributionSet();
// standard searches
assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "poky", osType.getId()).getContent())
.hasSize(1);
assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "poky", osType.getId()).getContent().get(0))
.isEqualTo(os);
assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "oracle%", runtimeType.getId()).getContent())
.hasSize(1);
assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "oracle%", runtimeType.getId()).getContent()
.get(0)).isEqualTo(jvm);
assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0.1", appType.getId()).getContent())
assertThat(softwareModuleManagement.findSoftwareModuleByFilters(PAGE, "poky", osType.getId()).getContent())
.hasSize(1);
assertThat(
softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0.1", appType.getId()).getContent().get(0))
.isEqualTo(ah);
assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0%", appType.getId()).getContent())
softwareModuleManagement.findSoftwareModuleByFilters(PAGE, "poky", osType.getId()).getContent().get(0))
.isEqualTo(os);
assertThat(
softwareModuleManagement.findSoftwareModuleByFilters(PAGE, "oracle%", runtimeType.getId()).getContent())
.hasSize(1);
assertThat(softwareModuleManagement.findSoftwareModuleByFilters(PAGE, "oracle%", runtimeType.getId())
.getContent().get(0)).isEqualTo(jvm);
assertThat(softwareModuleManagement.findSoftwareModuleByFilters(PAGE, "1.0.1", appType.getId()).getContent())
.hasSize(1);
assertThat(softwareModuleManagement.findSoftwareModuleByFilters(PAGE, "1.0.1", appType.getId()).getContent()
.get(0)).isEqualTo(ah);
assertThat(softwareModuleManagement.findSoftwareModuleByFilters(PAGE, "1.0%", appType.getId()).getContent())
.hasSize(2);
// no we search with on entity marked as deleted
softwareManagement.deleteSoftwareModule(
softwareModuleManagement.deleteSoftwareModule(
softwareModuleRepository.findByAssignedToAndType(PAGE, ds, appType).getContent().get(0).getId());
assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0%", appType.getId()).getContent())
assertThat(softwareModuleManagement.findSoftwareModuleByFilters(PAGE, "1.0%", appType.getId()).getContent())
.hasSize(1);
assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0%", appType.getId()).getContent().get(0))
assertThat(
softwareModuleManagement.findSoftwareModuleByFilters(PAGE, "1.0%", appType.getId()).getContent().get(0))
.isEqualTo(ah);
}
@@ -282,10 +228,10 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
@Description("Searches for software modules based on a list of IDs.")
public void findSoftwareModulesById() {
final List<Long> modules = Lists.newArrayList(testdataFactory.createSoftwareModuleOs().getId(),
final List<Long> modules = Arrays.asList(testdataFactory.createSoftwareModuleOs().getId(),
testdataFactory.createSoftwareModuleApp().getId(), 624355263L);
assertThat(softwareManagement.findSoftwareModulesById(modules)).hasSize(2);
assertThat(softwareModuleManagement.findSoftwareModulesById(modules)).hasSize(2);
}
@Test
@@ -295,10 +241,10 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule one = testdataFactory.createSoftwareModuleOs("one");
final SoftwareModule two = testdataFactory.createSoftwareModuleOs("two");
// ignored
softwareManagement.deleteSoftwareModule(testdataFactory.createSoftwareModuleOs("deleted").getId());
softwareModuleManagement.deleteSoftwareModule(testdataFactory.createSoftwareModuleOs("deleted").getId());
testdataFactory.createSoftwareModuleApp();
assertThat(softwareManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent())
assertThat(softwareModuleManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent())
.as("Expected to find the following number of modules:").hasSize(2).as("with the following elements")
.contains(two, one);
}
@@ -311,48 +257,10 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule two = testdataFactory.createSoftwareModuleOs("two");
final SoftwareModule deleted = testdataFactory.createSoftwareModuleOs("deleted");
// ignored
softwareManagement.deleteSoftwareModule(deleted.getId());
softwareModuleManagement.deleteSoftwareModule(deleted.getId());
assertThat(softwareManagement.countSoftwareModulesAll()).as("Expected to find the following number of modules:")
.isEqualTo(2);
}
@Test
@Description("Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).")
public void deleteAssignedAndUnassignedSoftwareModuleTypes() {
assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(3).contains(osType, runtimeType,
appType);
SoftwareModuleType type = softwareManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("bundle").name("OSGi Bundle"));
assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(4).contains(osType, runtimeType,
appType, type);
// delete unassigned
softwareManagement.deleteSoftwareModuleType(type.getId());
assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(3).contains(osType, runtimeType,
appType);
assertThat(softwareModuleTypeRepository.findAll()).hasSize(3).contains((JpaSoftwareModuleType) osType,
(JpaSoftwareModuleType) runtimeType, (JpaSoftwareModuleType) appType);
type = softwareManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("bundle2").name("OSGi Bundle2"));
assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(4).contains(osType, runtimeType,
appType, type);
softwareManagement.createSoftwareModule(
entityFactory.softwareModule().create().type(type).name("Test SM").version("1.0"));
// delete assigned
softwareManagement.deleteSoftwareModuleType(type.getId());
assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(3).contains(osType, runtimeType,
appType);
assertThat(softwareModuleTypeRepository.findAll()).hasSize(4).contains((JpaSoftwareModuleType) osType,
(JpaSoftwareModuleType) runtimeType, (JpaSoftwareModuleType) appType,
softwareModuleTypeRepository.findOne(type.getId()));
assertThat(softwareModuleManagement.countSoftwareModulesAll())
.as("Expected to find the following number of modules:").isEqualTo(2);
}
@Test
@@ -366,12 +274,12 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
final Artifact artifact2 = artifactsIt.next();
// [STEP2]: Delete unassigned SoftwareModule
softwareManagement.deleteSoftwareModule(unassignedModule.getId());
softwareModuleManagement.deleteSoftwareModule(unassignedModule.getId());
// [VERIFY EXPECTED RESULT]:
// verify: SoftwareModule is deleted
assertThat(softwareModuleRepository.findAll()).hasSize(0);
assertThat(softwareManagement.findSoftwareModuleById(unassignedModule.getId())).isNotPresent();
assertThat(softwareModuleManagement.findSoftwareModuleById(unassignedModule.getId())).isNotPresent();
// verify: binary data of artifact is deleted
assertArtfiactNull(artifact1, artifact2);
@@ -392,13 +300,13 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
testdataFactory.createDistributionSet(Sets.newHashSet(assignedModule));
// [STEP3]: Delete the assigned SoftwareModule
softwareManagement.deleteSoftwareModule(assignedModule.getId());
softwareModuleManagement.deleteSoftwareModule(assignedModule.getId());
// [VERIFY EXPECTED RESULT]:
// verify: assignedModule is marked as deleted
assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()).get();
assignedModule = softwareModuleManagement.findSoftwareModuleById(assignedModule.getId()).get();
assertTrue("The module should be flagged as deleted", assignedModule.isDeleted());
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleRepository.findAll()).hasSize(1);
// verify: binary data is deleted
@@ -426,19 +334,19 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet disSet = testdataFactory.createDistributionSet(Sets.newHashSet(assignedModule));
// [STEP3]: Assign DistributionSet to a Device
assignDistributionSet(disSet, Lists.newArrayList(target));
assignDistributionSet(disSet, Arrays.asList(target));
// [STEP4]: Delete the DistributionSet
distributionSetManagement.deleteDistributionSet(disSet.getId());
// [STEP5]: Delete the assigned SoftwareModule
softwareManagement.deleteSoftwareModule(assignedModule.getId());
softwareModuleManagement.deleteSoftwareModule(assignedModule.getId());
// [VERIFY EXPECTED RESULT]:
// verify: assignedModule is marked as deleted
assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()).get();
assignedModule = softwareModuleManagement.findSoftwareModuleById(assignedModule.getId()).get();
assertTrue("The found module should be flagged deleted", assignedModule.isDeleted());
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleRepository.findAll()).hasSize(1);
// verify: binary data is deleted
@@ -464,7 +372,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
// [STEP2]: Create newArtifactX and add it to SoftwareModuleX
artifactManagement.createArtifact(new ByteArrayInputStream(source), moduleX.getId(), "artifactx", false);
moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId()).get();
moduleX = softwareModuleManagement.findSoftwareModuleById(moduleX.getId()).get();
final Artifact artifactX = moduleX.getArtifacts().iterator().next();
// [STEP3]: Create SoftwareModuleY and add the same ArtifactX
@@ -472,17 +380,17 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
// [STEP4]: Assign the same ArtifactX to SoftwareModuleY
artifactManagement.createArtifact(new ByteArrayInputStream(source), moduleY.getId(), "artifactx", false);
moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId()).get();
moduleY = softwareModuleManagement.findSoftwareModuleById(moduleY.getId()).get();
final Artifact artifactY = moduleY.getArtifacts().iterator().next();
// [STEP5]: Delete SoftwareModuleX
softwareManagement.deleteSoftwareModule(moduleX.getId());
softwareModuleManagement.deleteSoftwareModule(moduleX.getId());
// [VERIFY EXPECTED RESULT]:
// verify: SoftwareModuleX is deleted, and ModuelY still exists
assertThat(softwareModuleRepository.findAll()).hasSize(1);
assertThat(softwareManagement.findSoftwareModuleById(moduleX.getId())).isNotPresent();
assertThat(softwareManagement.findSoftwareModuleById(moduleY.getId())).isPresent();
assertThat(softwareModuleManagement.findSoftwareModuleById(moduleX.getId())).isNotPresent();
assertThat(softwareModuleManagement.findSoftwareModuleById(moduleY.getId())).isPresent();
// verify: binary data of artifact is not deleted
assertArtfiactNotNull(artifactY);
@@ -506,40 +414,40 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0);
artifactManagement.createArtifact(new ByteArrayInputStream(source), moduleX.getId(), "artifactx", false);
moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId()).get();
moduleX = softwareModuleManagement.findSoftwareModuleById(moduleX.getId()).get();
final Artifact artifactX = moduleX.getArtifacts().iterator().next();
// [STEP2]: Create SoftwareModuleY and add the same ArtifactX
SoftwareModule moduleY = createSoftwareModuleWithArtifacts(osType, "moduley", "v1.0", 0);
artifactManagement.createArtifact(new ByteArrayInputStream(source), moduleY.getId(), "artifactx", false);
moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId()).get();
moduleY = softwareModuleManagement.findSoftwareModuleById(moduleY.getId()).get();
final Artifact artifactY = moduleY.getArtifacts().iterator().next();
// [STEP3]: Assign SoftwareModuleX to DistributionSetX and to target
final DistributionSet disSetX = testdataFactory.createDistributionSet(Sets.newHashSet(moduleX), "X");
assignDistributionSet(disSetX, Lists.newArrayList(target));
assignDistributionSet(disSetX, Arrays.asList(target));
// [STEP4]: Assign SoftwareModuleY to DistributionSet and to target
final DistributionSet disSetY = testdataFactory.createDistributionSet(Sets.newHashSet(moduleY), "Y");
assignDistributionSet(disSetY, Lists.newArrayList(target));
assignDistributionSet(disSetY, Arrays.asList(target));
// [STEP5]: Delete SoftwareModuleX
softwareManagement.deleteSoftwareModule(moduleX.getId());
softwareModuleManagement.deleteSoftwareModule(moduleX.getId());
// [STEP6]: Delete SoftwareModuleY
softwareManagement.deleteSoftwareModule(moduleY.getId());
softwareModuleManagement.deleteSoftwareModule(moduleY.getId());
// [VERIFY EXPECTED RESULT]:
moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId()).get();
moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId()).get();
moduleX = softwareModuleManagement.findSoftwareModuleById(moduleX.getId()).get();
moduleY = softwareModuleManagement.findSoftwareModuleById(moduleY.getId()).get();
// verify: SoftwareModuleX and SofwtareModule are marked as deleted
assertThat(moduleX).isNotNull();
assertThat(moduleY).isNotNull();
assertTrue("The module should be flagged deleted", moduleX.isDeleted());
assertTrue("The module should be flagged deleted", moduleY.isDeleted());
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleRepository.findAll()).hasSize(2);
// verify: binary data of artifact is deleted
@@ -555,8 +463,8 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
final long countSoftwareModule = softwareModuleRepository.count();
// create SoftwareModule
SoftwareModule softwareModule = softwareManagement.createSoftwareModule(entityFactory.softwareModule().create()
.type(type).name(name).version(version).description("description of artifact " + name));
SoftwareModule softwareModule = softwareModuleManagement.createSoftwareModule(entityFactory.softwareModule()
.create().type(type).name(name).version(version).description("description of artifact " + name));
for (int i = 0; i < numberArtifacts; i++) {
artifactManagement.createArtifact(new RandomGeneratedInputStream(5 * 1024), softwareModule.getId(),
@@ -564,7 +472,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
}
// Verify correct Creation of SoftwareModule and corresponding artifacts
softwareModule = softwareManagement.findSoftwareModuleById(softwareModule.getId()).get();
softwareModule = softwareModuleManagement.findSoftwareModuleById(softwareModule.getId()).get();
assertThat(softwareModuleRepository.findAll()).hasSize((int) countSoftwareModule + 1);
final List<Artifact> artifacts = softwareModule.getArtifacts();
@@ -596,15 +504,15 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
@Description("Test verfies that results are returned based on given filter parameters and in the specified order.")
public void findSoftwareModuleOrderByDistributionModuleNameAscModuleVersionAsc() {
// test meta data
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
final SoftwareModuleType testType = softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("thetype").name("thename").maxAssignments(100));
DistributionSetType testDsType = distributionSetManagement
DistributionSetType testDsType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("key").name("name"));
distributionSetManagement.assignMandatorySoftwareModuleTypes(testDsType.getId(),
Lists.newArrayList(osType.getId()));
testDsType = distributionSetManagement.assignOptionalSoftwareModuleTypes(testDsType.getId(),
Lists.newArrayList(testType.getId()));
distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(testDsType.getId(),
Arrays.asList(osType.getId()));
testDsType = distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(testDsType.getId(),
Arrays.asList(testType.getId()));
// found in test
final SoftwareModule unassigned = testdataFactory.createSoftwareModule("thetype", "unassignedfound");
@@ -619,25 +527,26 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet set = distributionSetManagement.createDistributionSet(
entityFactory.distributionSet().create().name("set").version("1").type(testDsType).modules(Lists
.newArrayList(one.getId(), two.getId(), deleted.getId(), four.getId(), differentName.getId())));
softwareManagement.deleteSoftwareModule(deleted.getId());
softwareModuleManagement.deleteSoftwareModule(deleted.getId());
// with filter on name, version and module type
assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(PAGE,
assertThat(softwareModuleManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(PAGE,
set.getId(), "%found%", testType.getId()).getContent())
.as("Found modules with given name, given module type and the assigned ones first")
.containsExactly(new AssignedSoftwareModule(one, true), new AssignedSoftwareModule(two, true),
new AssignedSoftwareModule(unassigned, false));
// with filter on module type only
assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(PAGE,
assertThat(softwareModuleManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(PAGE,
set.getId(), null, testType.getId()).getContent())
.as("Found modules with given module type and the assigned ones first").containsExactly(
new AssignedSoftwareModule(differentName, true), new AssignedSoftwareModule(one, true),
new AssignedSoftwareModule(two, true), new AssignedSoftwareModule(unassigned, false));
// without any filter
assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(PAGE,
set.getId(), null, null).getContent()).as("Found modules with the assigned ones first").containsExactly(
assertThat(softwareModuleManagement
.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(PAGE, set.getId(), null, null)
.getContent()).as("Found modules with the assigned ones first").containsExactly(
new AssignedSoftwareModule(differentName, true), new AssignedSoftwareModule(one, true),
new AssignedSoftwareModule(two, true), new AssignedSoftwareModule(four, true),
new AssignedSoftwareModule(unassigned, false));
@@ -647,15 +556,15 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
@Description("Checks that number of modules is returned as expected based on given filters.")
public void countSoftwareModuleByFilters() {
// test meta data
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
final SoftwareModuleType testType = softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("thetype").name("thename").maxAssignments(100));
DistributionSetType testDsType = distributionSetManagement
DistributionSetType testDsType = distributionSetTypeManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("key").name("name"));
distributionSetManagement.assignMandatorySoftwareModuleTypes(testDsType.getId(),
Lists.newArrayList(osType.getId()));
testDsType = distributionSetManagement.assignOptionalSoftwareModuleTypes(testDsType.getId(),
Lists.newArrayList(testType.getId()));
distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(testDsType.getId(),
Arrays.asList(osType.getId()));
testDsType = distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(testDsType.getId(),
Arrays.asList(testType.getId()));
// found in test
testdataFactory.createSoftwareModule("thetype", "unassignedfound");
@@ -670,14 +579,14 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
distributionSetManagement.createDistributionSet(
entityFactory.distributionSet().create().name("set").version("1").type(testDsType).modules(Lists
.newArrayList(one.getId(), two.getId(), deleted.getId(), four.getId(), differentName.getId())));
softwareManagement.deleteSoftwareModule(deleted.getId());
softwareModuleManagement.deleteSoftwareModule(deleted.getId());
// test
assertThat(softwareManagement.countSoftwareModuleByFilters("%found%", testType.getId()))
assertThat(softwareModuleManagement.countSoftwareModuleByFilters("%found%", testType.getId()))
.as("Number of modules with given name or version and type").isEqualTo(3);
assertThat(softwareManagement.countSoftwareModuleByFilters(null, testType.getId()))
assertThat(softwareModuleManagement.countSoftwareModuleByFilters(null, testType.getId()))
.as("Number of modules with given type").isEqualTo(4);
assertThat(softwareManagement.countSoftwareModuleByFilters(null, null)).as("Number of modules overall")
assertThat(softwareModuleManagement.countSoftwareModuleByFilters(null, null)).as("Number of modules overall")
.isEqualTo(5);
}
@@ -688,79 +597,13 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
// one soft deleted
final SoftwareModule deleted = testdataFactory.createSoftwareModuleApp();
testdataFactory.createDistributionSet(Lists.newArrayList(deleted));
softwareManagement.deleteSoftwareModule(deleted.getId());
testdataFactory.createDistributionSet(Arrays.asList(deleted));
softwareModuleManagement.deleteSoftwareModule(deleted.getId());
assertThat(softwareManagement.countSoftwareModulesAll()).as("Number of undeleted modules").isEqualTo(1);
assertThat(softwareModuleManagement.countSoftwareModulesAll()).as("Number of undeleted modules").isEqualTo(1);
assertThat(softwareModuleRepository.count()).as("Number of all modules").isEqualTo(2);
}
@Test
@Description("Checks that software module typeis found based on given name.")
public void findSoftwareModuleTypeByName() {
testdataFactory.createSoftwareModuleOs();
final SoftwareModuleType found = softwareManagement
.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
softwareManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("thetype2").name("anothername"));
assertThat(softwareManagement.findSoftwareModuleTypeByName("thename").get()).as("Type with given name")
.isEqualTo(found);
}
@Test
@Description("Verfies that it is not possible to create a type that alrady exists.")
public void createSoftwareModuleTypeFailsWithExistingEntity() {
final SoftwareModuleType created = softwareManagement
.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
try {
softwareManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("thetype").name("thename"));
fail("should not have worked as module type already exists");
} catch (final EntityAlreadyExistsException e) {
}
}
@Test
@Description("Verfies that it is not possible to create a list of types where one already exists.")
public void createSoftwareModuleTypesFailsWithExistingEntity() {
final SoftwareModuleType created = softwareManagement
.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
try {
softwareManagement.createSoftwareModuleType(
Lists.newArrayList(entityFactory.softwareModuleType().create().key("thetype").name("thename"),
entityFactory.softwareModuleType().create().key("anothertype").name("anothername")));
fail("should not have worked as module type already exists");
} catch (final EntityAlreadyExistsException e) {
}
}
@Test
@Description("Verifies that the creation of a softwareModuleType is failing because of invalid max assignment")
public void createSoftwareModuleTypesFailsWithInvalidMaxAssignment() {
try {
softwareManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("type").name("name").maxAssignments(0));
fail("should not have worked as max assignment is invalid. Should be greater than 0.");
} catch (final ConstraintViolationException e) {
}
}
@Test
@Description("Verfies that multiple types are created as requested.")
public void createMultipleSoftwareModuleTypes() {
final List<SoftwareModuleType> created = softwareManagement.createSoftwareModuleType(
Lists.newArrayList(entityFactory.softwareModuleType().create().key("thetype").name("thename"),
entityFactory.softwareModuleType().create().key("thetype2").name("thename2")));
assertThat(created.size()).as("Number of created types").isEqualTo(2);
assertThat(softwareManagement.countSoftwareModuleTypesAll()).as("Number of types in repository").isEqualTo(5);
}
@Test
@Description("Verfies that software modules are resturned that are assigned to given DS.")
public void findSoftwareModuleByAssignedTo() {
@@ -771,10 +614,10 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
// one soft deleted
final SoftwareModule deleted = testdataFactory.createSoftwareModuleApp();
final DistributionSet set = distributionSetManagement.createDistributionSet(entityFactory.distributionSet()
.create().name("set").version("1").modules(Lists.newArrayList(one.getId(), deleted.getId())));
softwareManagement.deleteSoftwareModule(deleted.getId());
.create().name("set").version("1").modules(Arrays.asList(one.getId(), deleted.getId())));
softwareModuleManagement.deleteSoftwareModule(deleted.getId());
assertThat(softwareManagement.findSoftwareModuleByAssignedTo(PAGE, set.getId()).getContent())
assertThat(softwareModuleManagement.findSoftwareModuleByAssignedTo(PAGE, set.getId()).getContent())
.as("Found this number of modules").hasSize(2);
}
@@ -796,10 +639,11 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModuleMetadata swMetadata2 = new JpaSoftwareModuleMetadata(knownKey2, ah, knownValue2);
final List<SoftwareModuleMetadata> softwareModuleMetadata = softwareManagement
.createSoftwareModuleMetadata(ah.getId(), Lists.newArrayList(swMetadata1, swMetadata2));
final List<SoftwareModuleMetadata> softwareModuleMetadata = softwareModuleManagement
.createSoftwareModuleMetadata(ah.getId(), Arrays.asList(swMetadata1, swMetadata2));
final SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()).get();
final SoftwareModule changedLockRevisionModule = softwareModuleManagement.findSoftwareModuleById(ah.getId())
.get();
assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2);
assertThat(softwareModuleMetadata).hasSize(2);
@@ -819,11 +663,11 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule ah = testdataFactory.createSoftwareModuleApp();
softwareManagement.createSoftwareModuleMetadata(ah.getId(),
softwareModuleManagement.createSoftwareModuleMetadata(ah.getId(),
entityFactory.generateMetadata(knownKey1, knownValue1));
try {
softwareManagement.createSoftwareModuleMetadata(ah.getId(),
softwareModuleManagement.createSoftwareModuleMetadata(ah.getId(),
entityFactory.generateMetadata(knownKey1, knownValue2));
fail("should not have worked as module metadata already exists");
} catch (final EntityAlreadyExistsException e) {
@@ -845,23 +689,24 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
assertThat(ah.getOptLockRevision()).isEqualTo(1);
// create an software module meta data entry
final List<SoftwareModuleMetadata> softwareModuleMetadata = softwareManagement.createSoftwareModuleMetadata(
ah.getId(), Collections.singleton(entityFactory.generateMetadata(knownKey, knownValue)));
final List<SoftwareModuleMetadata> softwareModuleMetadata = softwareModuleManagement
.createSoftwareModuleMetadata(ah.getId(),
Collections.singleton(entityFactory.generateMetadata(knownKey, knownValue)));
assertThat(softwareModuleMetadata).hasSize(1);
// base software module should have now the opt lock revision one
// because we are modifying the
// base software module
SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()).get();
SoftwareModule changedLockRevisionModule = softwareModuleManagement.findSoftwareModuleById(ah.getId()).get();
assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2);
// update the software module metadata
Thread.sleep(100);
final SoftwareModuleMetadata updated = softwareManagement.updateSoftwareModuleMetadata(ah.getId(),
final SoftwareModuleMetadata updated = softwareModuleManagement.updateSoftwareModuleMetadata(ah.getId(),
entityFactory.generateMetadata(knownKey, knownUpdateValue));
// we are updating the sw meta data so also modiying the base software
// module so opt lock
// revision must be two
changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()).get();
changedLockRevisionModule = softwareModuleManagement.findSoftwareModuleById(ah.getId()).get();
assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(3);
// verify updated meta data contains the updated value
@@ -879,17 +724,19 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
SoftwareModule ah = testdataFactory.createSoftwareModuleApp();
ah = softwareManagement
ah = softwareModuleManagement
.createSoftwareModuleMetadata(ah.getId(), entityFactory.generateMetadata(knownKey1, knownValue1))
.getSoftwareModule();
assertThat(softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(new PageRequest(0, 100), ah.getId())
.getContent()).as("Contains the created metadata element")
assertThat(softwareModuleManagement
.findSoftwareModuleMetadataBySoftwareModuleId(new PageRequest(0, 100), ah.getId()).getContent())
.as("Contains the created metadata element")
.containsExactly(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1));
softwareManagement.deleteSoftwareModuleMetadata(ah.getId(), knownKey1);
assertThat(softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(new PageRequest(0, 100), ah.getId())
.getContent()).as("Metadata elemenets are").isEmpty();
softwareModuleManagement.deleteSoftwareModuleMetadata(ah.getId(), knownKey1);
assertThat(softwareModuleManagement
.findSoftwareModuleMetadataBySoftwareModuleId(new PageRequest(0, 100), ah.getId()).getContent())
.as("Metadata elemenets are").isEmpty();
}
@Test
@@ -900,11 +747,11 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
SoftwareModule ah = testdataFactory.createSoftwareModuleApp();
ah = softwareManagement
ah = softwareModuleManagement
.createSoftwareModuleMetadata(ah.getId(), entityFactory.generateMetadata(knownKey1, knownValue1))
.getSoftwareModule();
assertThat(softwareManagement.findSoftwareModuleMetadata(ah.getId(), "doesnotexist")).isNotPresent();
assertThat(softwareModuleManagement.findSoftwareModuleMetadata(ah.getId(), "doesnotexist")).isNotPresent();
}
@Test
@@ -916,19 +763,19 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
SoftwareModule sw2 = testdataFactory.createSoftwareModuleOs();
for (int index = 0; index < 10; index++) {
sw1 = softwareManagement.createSoftwareModuleMetadata(sw1.getId(),
sw1 = softwareModuleManagement.createSoftwareModuleMetadata(sw1.getId(),
entityFactory.generateMetadata("key" + index, "value" + index)).getSoftwareModule();
}
for (int index = 0; index < 20; index++) {
sw2 = softwareManagement.createSoftwareModuleMetadata(sw2.getId(),
sw2 = softwareModuleManagement.createSoftwareModuleMetadata(sw2.getId(),
new JpaSoftwareModuleMetadata("key" + index, sw2, "value" + index)).getSoftwareModule();
}
final Page<SoftwareModuleMetadata> metadataOfSw1 = softwareManagement
final Page<SoftwareModuleMetadata> metadataOfSw1 = softwareModuleManagement
.findSoftwareModuleMetadataBySoftwareModuleId(sw1.getId(), new PageRequest(0, 100));
final Page<SoftwareModuleMetadata> metadataOfSw2 = softwareManagement
final Page<SoftwareModuleMetadata> metadataOfSw2 = softwareModuleManagement
.findSoftwareModuleMetadataBySoftwareModuleId(sw2.getId(), new PageRequest(0, 100));
assertThat(metadataOfSw1.getNumberOfElements()).isEqualTo(10);

View File

@@ -0,0 +1,211 @@
/**
* 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.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.List;
import javax.validation.ConstraintViolationException;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.Test;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Repository")
@Stories("Software Module Management")
public class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that management get access reacts as specfied on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 0) })
public void nonExistingEntityAccessReturnsNotPresent() {
assertThat(softwareModuleTypeManagement.findSoftwareModuleTypeById(NOT_EXIST_IDL)).isNotPresent();
assertThat(softwareModuleTypeManagement.findSoftwareModuleTypeByKey(NOT_EXIST_ID)).isNotPresent();
assertThat(softwareModuleTypeManagement.findSoftwareModuleTypeByName(NOT_EXIST_ID)).isNotPresent();
}
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 0) })
public void entityQueriesReferringToNotExistingEntitiesThrowsException() {
verifyThrownExceptionBy(() -> softwareModuleTypeManagement.deleteSoftwareModuleType(NOT_EXIST_IDL),
"SoftwareModuleType");
verifyThrownExceptionBy(
() -> softwareModuleTypeManagement
.updateSoftwareModuleType(entityFactory.softwareModuleType().update(1234L)),
"SoftwareModuleType");
}
@Test
@Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.")
public void updateNothingResultsInUnchangedRepositoryForType() {
final SoftwareModuleType created = softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("test-key").name("test-name"));
final SoftwareModuleType updated = softwareModuleTypeManagement
.updateSoftwareModuleType(entityFactory.softwareModuleType().update(created.getId()));
assertThat(updated.getOptLockRevision())
.as("Expected version number of updated entitity to be equal to created version")
.isEqualTo(created.getOptLockRevision());
}
@Test
@Description("Calling update for changed fields results in change in the repository.")
public void updateSoftareModuleTypeFieldsToNewValue() {
final SoftwareModuleType created = softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("test-key").name("test-name"));
final SoftwareModuleType updated = softwareModuleTypeManagement.updateSoftwareModuleType(
entityFactory.softwareModuleType().update(created.getId()).description("changed").colour("changed"));
assertThat(updated.getOptLockRevision()).as("Expected version number of updated entitity is")
.isEqualTo(created.getOptLockRevision() + 1);
assertThat(updated.getDescription()).as("Updated description is").isEqualTo("changed");
assertThat(updated.getColour()).as("Updated vendor is").isEqualTo("changed");
}
@Test
@Description("Create Software Module Types call fails when called for existing entities.")
public void createModuleTypesCallFailsForExistingTypes() {
final List<SoftwareModuleTypeCreate> created = Arrays.asList(
entityFactory.softwareModuleType().create().key("test-key").name("test-name"),
entityFactory.softwareModuleType().create().key("test-key2").name("test-name2"));
softwareModuleTypeManagement.createSoftwareModuleType(created);
try {
softwareModuleTypeManagement.createSoftwareModuleType(created);
fail("Should not have worked as module already exists.");
} catch (final EntityAlreadyExistsException e) {
}
}
@Test
@Description("Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).")
public void deleteAssignedAndUnassignedSoftwareModuleTypes() {
assertThat(softwareModuleTypeManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(3).contains(osType,
runtimeType, appType);
SoftwareModuleType type = softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("bundle").name("OSGi Bundle"));
assertThat(softwareModuleTypeManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(4).contains(osType,
runtimeType, appType, type);
// delete unassigned
softwareModuleTypeManagement.deleteSoftwareModuleType(type.getId());
assertThat(softwareModuleTypeManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(3).contains(osType,
runtimeType, appType);
assertThat(softwareModuleTypeRepository.findAll()).hasSize(3).contains((JpaSoftwareModuleType) osType,
(JpaSoftwareModuleType) runtimeType, (JpaSoftwareModuleType) appType);
type = softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("bundle2").name("OSGi Bundle2"));
assertThat(softwareModuleTypeManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(4).contains(osType,
runtimeType, appType, type);
softwareModuleManagement.createSoftwareModule(
entityFactory.softwareModule().create().type(type).name("Test SM").version("1.0"));
// delete assigned
softwareModuleTypeManagement.deleteSoftwareModuleType(type.getId());
assertThat(softwareModuleTypeManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(3).contains(osType,
runtimeType, appType);
assertThat(softwareModuleTypeRepository.findAll()).hasSize(4).contains((JpaSoftwareModuleType) osType,
(JpaSoftwareModuleType) runtimeType, (JpaSoftwareModuleType) appType,
softwareModuleTypeRepository.findOne(type.getId()));
}
@Test
@Description("Checks that software module typeis found based on given name.")
public void findSoftwareModuleTypeByName() {
testdataFactory.createSoftwareModuleOs();
final SoftwareModuleType found = softwareModuleTypeManagement
.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("thetype2").name("anothername"));
assertThat(softwareModuleTypeManagement.findSoftwareModuleTypeByName("thename").get())
.as("Type with given name").isEqualTo(found);
}
@Test
@Description("Verfies that it is not possible to create a type that alrady exists.")
public void createSoftwareModuleTypeFailsWithExistingEntity() {
softwareModuleTypeManagement
.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
try {
softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("thetype").name("thename"));
fail("should not have worked as module type already exists");
} catch (final EntityAlreadyExistsException e) {
}
}
@Test
@Description("Verfies that it is not possible to create a list of types where one already exists.")
public void createSoftwareModuleTypesFailsWithExistingEntity() {
softwareModuleTypeManagement
.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
try {
softwareModuleTypeManagement.createSoftwareModuleType(
Arrays.asList(entityFactory.softwareModuleType().create().key("thetype").name("thename"),
entityFactory.softwareModuleType().create().key("anothertype").name("anothername")));
fail("should not have worked as module type already exists");
} catch (final EntityAlreadyExistsException e) {
}
}
@Test
@Description("Verifies that the creation of a softwareModuleType is failing because of invalid max assignment")
public void createSoftwareModuleTypesFailsWithInvalidMaxAssignment() {
try {
softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("type").name("name").maxAssignments(0));
fail("should not have worked as max assignment is invalid. Should be greater than 0.");
} catch (final ConstraintViolationException e) {
}
}
@Test
@Description("Verfies that multiple types are created as requested.")
public void createMultipleSoftwareModuleTypes() {
final List<SoftwareModuleType> created = softwareModuleTypeManagement.createSoftwareModuleType(
Arrays.asList(entityFactory.softwareModuleType().create().key("thetype").name("thename"),
entityFactory.softwareModuleType().create().key("thetype2").name("thename2")));
assertThat(created.size()).as("Number of created types").isEqualTo(2);
assertThat(softwareModuleTypeManagement.countSoftwareModuleTypesAll()).as("Number of types in repository")
.isEqualTo(5);
}
}

View File

@@ -140,7 +140,7 @@ public class SystemManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet("deleted garbage", true);
ds.getModules().stream().forEach(module -> {
artifactManagement.createArtifact(new ByteArrayInputStream(random), module.getId(), "file1", false);
softwareManagement.deleteSoftwareModule(module.getId());
softwareModuleManagement.deleteSoftwareModule(module.getId());
});
}

View File

@@ -36,8 +36,6 @@ import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.Test;
import com.google.common.collect.Lists;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@@ -119,7 +117,7 @@ public class TagManagementTest extends AbstractJpaIntegrationTest {
// search for not deleted
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true)
.setTagNames(Lists.newArrayList(tagA.getName()));
.setTagNames(Arrays.asList(tagA.getName()));
assertEquals("filter works not correct",
dsAs.spliterator().getExactSizeIfKnown() + dsABs.spliterator().getExactSizeIfKnown()
+ dsACs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),
@@ -127,7 +125,7 @@ public class TagManagementTest extends AbstractJpaIntegrationTest {
.getTotalElements());
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true)
.setTagNames(Lists.newArrayList(tagB.getName()));
.setTagNames(Arrays.asList(tagB.getName()));
assertEquals("filter works not correct",
dsBs.spliterator().getExactSizeIfKnown() + dsABs.spliterator().getExactSizeIfKnown()
+ dsBCs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),
@@ -135,7 +133,7 @@ public class TagManagementTest extends AbstractJpaIntegrationTest {
.getTotalElements());
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true)
.setTagNames(Lists.newArrayList(tagC.getName()));
.setTagNames(Arrays.asList(tagC.getName()));
assertEquals("filter works not correct",
dsCs.spliterator().getExactSizeIfKnown() + dsACs.spliterator().getExactSizeIfKnown()
+ dsBCs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),
@@ -143,7 +141,7 @@ public class TagManagementTest extends AbstractJpaIntegrationTest {
.getTotalElements());
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true)
.setTagNames(Lists.newArrayList(tagX.getName()));
.setTagNames(Arrays.asList(tagX.getName()));
assertEquals("filter works not correct", 0, distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getTotalElements());
@@ -158,7 +156,7 @@ public class TagManagementTest extends AbstractJpaIntegrationTest {
assertEquals("wrong tag size", 2, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown());
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setTagNames(Lists.newArrayList(tagA.getName()));
.setTagNames(Arrays.asList(tagA.getName()));
assertEquals("filter works not correct",
dsAs.spliterator().getExactSizeIfKnown() + dsABs.spliterator().getExactSizeIfKnown()
+ dsACs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),
@@ -166,12 +164,12 @@ public class TagManagementTest extends AbstractJpaIntegrationTest {
.getTotalElements());
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setTagNames(Lists.newArrayList(tagB.getName()));
.setTagNames(Arrays.asList(tagB.getName()));
assertEquals("filter works not correct", 0, distributionSetManagement
.findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getTotalElements());
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setTagNames(Lists.newArrayList(tagC.getName()));
.setTagNames(Arrays.asList(tagC.getName()));
assertEquals("filter works not correct",
dsCs.spliterator().getExactSizeIfKnown() + dsACs.spliterator().getExactSizeIfKnown()
+ dsBCs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),

View File

@@ -100,9 +100,9 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
entityFactory.actionStatus().create(actionId).status(Status.FINISHED).message("message"));
assignDistributionSet(setA.getId(), installedC);
final List<TargetUpdateStatus> unknown = Lists.newArrayList(TargetUpdateStatus.UNKNOWN);
final List<TargetUpdateStatus> pending = Lists.newArrayList(TargetUpdateStatus.PENDING);
final List<TargetUpdateStatus> both = Lists.newArrayList(TargetUpdateStatus.UNKNOWN,
final List<TargetUpdateStatus> unknown = Arrays.asList(TargetUpdateStatus.UNKNOWN);
final List<TargetUpdateStatus> pending = Arrays.asList(TargetUpdateStatus.PENDING);
final List<TargetUpdateStatus> both = Arrays.asList(TargetUpdateStatus.UNKNOWN,
TargetUpdateStatus.PENDING);
// get final updated version of targets
@@ -123,14 +123,14 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
verifyThat0TargetsWithTagAndDescOrNameHasDS(targTagW, setA);
verifyThat0TargetsWithNameOrdescAndDSHaveTag(targTagX, setA);
verifyThat3TargetsHaveDSAssigned(setA,
targetManagement.findTargetsByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC)));
targetManagement.findTargetsByControllerID(Arrays.asList(assignedA, assignedB, assignedC)));
verifyThat1TargetWithDescOrNameHasDS(setA, targetManagement.findTargetByControllerID(assignedA).get());
List<Target> expected = concat(targAs, targBs, targCs, targDs);
expected.removeAll(
targetManagement.findTargetsByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC)));
targetManagement.findTargetsByControllerID(Arrays.asList(assignedA, assignedB, assignedC)));
verifyThat397TargetsAreInStatusUnknown(unknown, expected);
expected = concat(targBs, targCs);
expected.removeAll(targetManagement.findTargetsByControllerID(Lists.newArrayList(assignedB, assignedC)));
expected.removeAll(targetManagement.findTargetsByControllerID(Arrays.asList(assignedB, assignedC)));
verifyThat198TargetsAreInStatusUnknownAndHaveGivenTags(targTagY, targTagW, unknown, expected);
verfyThat0TargetsAreInStatusUnknownAndHaveDSAssigned(setA, unknown);
expected = concat(targAs);
@@ -140,23 +140,23 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
expected.remove(targetManagement.findTargetByControllerID(assignedB).get());
verifyThat99TargetsWithGivenNameOrDescAndTagAreInStatusUnknown(targTagW, unknown, expected);
verifyThat3TargetsAreInStatusPending(pending,
targetManagement.findTargetsByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC)));
targetManagement.findTargetsByControllerID(Arrays.asList(assignedA, assignedB, assignedC)));
verifyThat3TargetsWithGivenDSAreInPending(setA, pending,
targetManagement.findTargetsByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC)));
targetManagement.findTargetsByControllerID(Arrays.asList(assignedA, assignedB, assignedC)));
verifyThat1TargetWithGivenNameOrDescAndDSIsInPending(setA, pending,
targetManagement.findTargetByControllerID(assignedA).get());
verifyThat1TargetWithGivenNameOrDescAndTagAndDSIsInPending(targTagW, setA, pending,
targetManagement.findTargetByControllerID(assignedB).get());
verifyThat2TargetsWithGivenTagAndDSIsInPending(targTagW, setA, pending,
targetManagement.findTargetsByControllerID(Lists.newArrayList(assignedB, assignedC)));
targetManagement.findTargetsByControllerID(Arrays.asList(assignedB, assignedC)));
verifyThat2TargetsWithGivenTagAreInPending(targTagW, pending,
targetManagement.findTargetsByControllerID(Lists.newArrayList(assignedB, assignedC)));
targetManagement.findTargetsByControllerID(Arrays.asList(assignedB, assignedC)));
verifyThat200targetsWithGivenTagAreInStatusPendingorUnknown(targTagW, both, concat(targBs, targCs));
verfiyThat1TargetAIsInStatusPendingAndHasDSInstalled(installedSet, pending,
targetManagement.findTargetByControllerID(installedC).get());
expected = concat(targBs, targCs);
expected.removeAll(targetManagement.findTargetsByControllerID(Lists.newArrayList(assignedB, assignedC)));
expected.removeAll(targetManagement.findTargetsByControllerID(Arrays.asList(assignedB, assignedC)));
verifyThat198TargetsAreInStatusUnknownAndOverdue(unknown, expected);
}

View File

@@ -15,6 +15,8 @@ import static org.junit.Assert.fail;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -50,7 +52,6 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
@@ -79,14 +80,11 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest {
final Target target = testdataFactory.createTarget();
verifyThrownExceptionBy(
() -> targetManagement.assignTag(Lists.newArrayList(target.getControllerId()), NOT_EXIST_IDL),
"TargetTag");
verifyThrownExceptionBy(() -> targetManagement.assignTag(Lists.newArrayList(NOT_EXIST_ID), tag.getId()),
"Target");
() -> targetManagement.assignTag(Arrays.asList(target.getControllerId()), NOT_EXIST_IDL), "TargetTag");
verifyThrownExceptionBy(() -> targetManagement.assignTag(Arrays.asList(NOT_EXIST_ID), tag.getId()), "Target");
verifyThrownExceptionBy(() -> targetManagement.findTargetsByTag(PAGE, NOT_EXIST_IDL), "TargetTag");
verifyThrownExceptionBy(() -> targetManagement.findTargetsByTag(PAGE, "name==*", NOT_EXIST_IDL),
"TargetTag");
verifyThrownExceptionBy(() -> targetManagement.findTargetsByTag(PAGE, "name==*", NOT_EXIST_IDL), "TargetTag");
verifyThrownExceptionBy(() -> targetManagement.countTargetByAssignedDistributionSet(NOT_EXIST_IDL),
"DistributionSet");
@@ -100,13 +98,12 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest {
"DistributionSet");
verifyThrownExceptionBy(() -> targetManagement.deleteTarget(NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> targetManagement.deleteTargets(Lists.newArrayList(NOT_EXIST_IDL)), "Target");
verifyThrownExceptionBy(() -> targetManagement.deleteTargets(Arrays.asList(NOT_EXIST_IDL)), "Target");
verifyThrownExceptionBy(
() -> targetManagement.findAllTargetsByTargetFilterQueryAndNonDS(PAGE, NOT_EXIST_IDL, "name==*"),
"DistributionSet");
verifyThrownExceptionBy(
() -> targetManagement.findAllTargetsInRolloutGroupWithoutAction(PAGE, NOT_EXIST_IDL),
verifyThrownExceptionBy(() -> targetManagement.findAllTargetsInRolloutGroupWithoutAction(PAGE, NOT_EXIST_IDL),
"RolloutGroup");
verifyThrownExceptionBy(() -> targetManagement.findTargetByAssignedDistributionSet(NOT_EXIST_IDL, PAGE),
"DistributionSet");
@@ -121,10 +118,10 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest {
"DistributionSet");
verifyThrownExceptionBy(
() -> targetManagement.toggleTagAssignment(Lists.newArrayList(target.getControllerId()), NOT_EXIST_ID),
() -> targetManagement.toggleTagAssignment(Arrays.asList(target.getControllerId()), NOT_EXIST_ID),
"TargetTag");
verifyThrownExceptionBy(
() -> targetManagement.toggleTagAssignment(Lists.newArrayList(NOT_EXIST_ID), tag.getName()), "Target");
verifyThrownExceptionBy(() -> targetManagement.toggleTagAssignment(Arrays.asList(NOT_EXIST_ID), tag.getName()),
"Target");
verifyThrownExceptionBy(() -> targetManagement.unAssignTag(NOT_EXIST_ID, tag.getId()), "Target");
verifyThrownExceptionBy(() -> targetManagement.unAssignTag(target.getControllerId(), NOT_EXIST_IDL),
@@ -302,12 +299,12 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest {
public void deleteAndCreateTargets() {
Target target = targetManagement.createTarget(entityFactory.target().create().controllerId("targetId123"));
assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(1);
targetManagement.deleteTargets(Lists.newArrayList(target.getId()));
targetManagement.deleteTargets(Arrays.asList(target.getId()));
assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(0);
target = createTargetWithAttributes("4711");
assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(1);
targetManagement.deleteTargets(Lists.newArrayList(target.getId()));
targetManagement.deleteTargets(Arrays.asList(target.getId()));
assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(0);
final List<Long> targets = new ArrayList<>();
@@ -546,10 +543,9 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest {
targetManagement.deleteTarget(extra.getControllerId());
final int numberToDelete = 50;
final Iterable<Target> targetsToDelete = Iterables.limit(firstList, numberToDelete);
final Collection<Target> targetsToDelete = firstList.subList(0, numberToDelete);
final Target[] deletedTargets = Iterables.toArray(targetsToDelete, Target.class);
final List<Long> targetsIdsToDelete = Lists.newArrayList(targetsToDelete.iterator()).stream().map(Target::getId)
.collect(Collectors.toList());
final List<Long> targetsIdsToDelete = targetsToDelete.stream().map(Target::getId).collect(Collectors.toList());
targetManagement.deleteTargets(targetsIdsToDelete);
@@ -571,11 +567,11 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest {
final int noT1Tags = 3;
final List<TargetTag> t1Tags = testdataFactory.createTargetTags(noT1Tags, "tag1");
t1Tags.forEach(tag -> targetManagement.assignTag(Lists.newArrayList(t1.getControllerId()), tag.getId()));
t1Tags.forEach(tag -> targetManagement.assignTag(Arrays.asList(t1.getControllerId()), tag.getId()));
final Target t2 = testdataFactory.createTarget("id-2");
final List<TargetTag> t2Tags = testdataFactory.createTargetTags(noT2Tags, "tag2");
t2Tags.forEach(tag -> targetManagement.assignTag(Lists.newArrayList(t2.getControllerId()), tag.getId()));
t2Tags.forEach(tag -> targetManagement.assignTag(Arrays.asList(t2.getControllerId()), tag.getId()));
final Target t11 = targetManagement.findTargetByControllerID(t1.getControllerId()).get();
assertThat(tagManagement.findAllTargetTags(PAGE, t11.getControllerId()).getContent()).as("Tag size is wrong")
@@ -777,7 +773,7 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest {
@Description("Verify that the find all targets by ids method contains the entities that we are looking for")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 12) })
public void verifyFindTargetAllById() {
final List<Long> searchIds = Lists.newArrayList(testdataFactory.createTarget("target-4").getId(),
final List<Long> searchIds = Arrays.asList(testdataFactory.createTarget("target-4").getId(),
testdataFactory.createTarget("target-5").getId(), testdataFactory.createTarget("target-6").getId());
for (int i = 0; i < 9; i++) {
testdataFactory.createTarget("test" + i);

View File

@@ -155,7 +155,7 @@ public class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
@Description("Verifies that the software module update event is published when a software module has been updated")
public void softwareModuleUpdateEventIsPublished() throws InterruptedException {
final SoftwareModule softwareModule = testdataFactory.createSoftwareModuleApp();
softwareManagement
softwareModuleManagement
.updateSoftwareModule(entityFactory.softwareModule().update(softwareModule.getId()).description("New"));
final SoftwareModuleUpdatedEvent softwareModuleUpdatedEvent = eventListener
@@ -168,7 +168,7 @@ public class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
@Description("Verifies that the software module deleted event is published when a software module has been deleted")
public void softwareModuleDeletedEventIsPublished() throws InterruptedException {
final SoftwareModule softwareModule = testdataFactory.createSoftwareModuleApp();
softwareManagement.deleteSoftwareModule(softwareModule.getId());
softwareModuleManagement.deleteSoftwareModule(softwareModule.getId());
final SoftwareModuleDeletedEvent softwareModuleDeletedEvent = eventListener
.waitForEvent(SoftwareModuleDeletedEvent.class, 1, TimeUnit.SECONDS);

View File

@@ -103,10 +103,10 @@ public class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest {
private void executeDeleteAndAssertCallbackResult(final AbstractEntityListener entityInterceptor) {
EntityInterceptorHolder.getInstance().getEntityInterceptors().add(entityInterceptor);
final SoftwareModuleType type = softwareManagement
final SoftwareModuleType type = softwareModuleTypeManagement
.createSoftwareModuleType(entityFactory.softwareModuleType().create().name("test").key("test"));
softwareManagement.deleteSoftwareModuleType(type.getId());
softwareModuleTypeManagement.deleteSoftwareModuleType(type.getId());
assertThat(entityInterceptor.getEntity()).isNotNull();
assertThat(entityInterceptor.getEntity()).isEqualTo(type);
}

View File

@@ -55,12 +55,12 @@ public class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verfies that updated entities are not equal.")
public void changedEntitiesAreNotEqual() {
final SoftwareModuleType type = softwareManagement
final SoftwareModuleType type = softwareModuleTypeManagement
.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test").name("test"));
assertThat(type).as("persited entity is not equal to regular object")
.isNotEqualTo(entityFactory.softwareModuleType().create().key("test").name("test").build());
final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(
final SoftwareModuleType updated = softwareModuleTypeManagement.updateSoftwareModuleType(
entityFactory.softwareModuleType().update(type.getId()).description("another"));
assertThat(type).as("Changed entity is not equal to the previous version").isNotEqualTo(updated);
}
@@ -68,7 +68,7 @@ public class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verify that no proxy of the entity manager has an influence on the equals or hashcode result.")
public void managedEntityIsEqualToUnamangedObjectWithSameKey() {
final SoftwareModuleType type = softwareManagement.createSoftwareModuleType(
final SoftwareModuleType type = softwareModuleTypeManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("test").name("test").description("test"));
final JpaSoftwareModuleType mock = new JpaSoftwareModuleType("test", "test", "test", 1);

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