Refactoring/Improving source: rest (lombok) (#1613)

Signed-off-by: Marinov Avgustin <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2024-02-04 12:26:21 +02:00
committed by GitHub
parent c320a45b55
commit 47f20886c1
33 changed files with 221 additions and 935 deletions

View File

@@ -21,6 +21,7 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.api.ArtifactUrlHandler; import org.eclipse.hawkbit.api.ArtifactUrlHandler;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.ddi.json.model.DdiActionFeedback; import org.eclipse.hawkbit.ddi.json.model.DdiActionFeedback;
@@ -70,8 +71,6 @@ import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder;
import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.eclipse.hawkbit.security.HawkbitSecurityProperties;
import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.TenantAware;
import org.eclipse.hawkbit.util.IpUtil; import org.eclipse.hawkbit.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.bus.BusProperties; import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.bus.ServiceMatcher; import org.springframework.cloud.bus.ServiceMatcher;
@@ -96,11 +95,11 @@ import org.springframework.web.context.WebApplicationContext;
* *
* Transactional (read-write) as all queries at least update the last poll time. * Transactional (read-write) as all queries at least update the last poll time.
*/ */
@Slf4j
@RestController @RestController
@Scope(value = WebApplicationContext.SCOPE_REQUEST) @Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class DdiRootController implements DdiRootControllerRestApi { public class DdiRootController implements DdiRootControllerRestApi {
private static final Logger LOG = LoggerFactory.getLogger(DdiRootController.class);
private static final String GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET = "given action ({}) is not assigned to given target ({})."; private static final String GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET = "given action ({}) is not assigned to given target ({}).";
private static final String FALLBACK_REMARK = "Initiated using the Device Direct Integration API without providing a remark."; private static final String FALLBACK_REMARK = "Initiated using the Device Direct Integration API without providing a remark.";
@@ -144,7 +143,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
public ResponseEntity<List<DdiArtifact>> getSoftwareModulesArtifacts(@PathVariable("tenant") final String tenant, public ResponseEntity<List<DdiArtifact>> getSoftwareModulesArtifacts(@PathVariable("tenant") final String tenant,
@PathVariable("controllerId") final String controllerId, @PathVariable("controllerId") final String controllerId,
@PathVariable("softwareModuleId") final Long softwareModuleId) { @PathVariable("softwareModuleId") final Long softwareModuleId) {
LOG.debug("getSoftwareModulesArtifacts({})", controllerId); log.debug("getSoftwareModulesArtifacts({})", controllerId);
final Target target = findTarget(controllerId); final Target target = findTarget(controllerId);
@@ -160,7 +159,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
@Override @Override
public ResponseEntity<DdiControllerBase> getControllerBase(@PathVariable("tenant") final String tenant, public ResponseEntity<DdiControllerBase> getControllerBase(@PathVariable("tenant") final String tenant,
@PathVariable("controllerId") final String controllerId) { @PathVariable("controllerId") final String controllerId) {
LOG.debug("getControllerBase({})", controllerId); log.debug("getControllerBase({})", controllerId);
final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotExist(controllerId, IpUtil final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotExist(controllerId, IpUtil
.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties)); .getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties));
@@ -189,7 +188,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId)); .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (checkModule(fileName, module)) { if (checkModule(fileName, module)) {
LOG.warn("Software module with id {} could not be found.", softwareModuleId); log.warn("Software module with id {} could not be found.", softwareModuleId);
result = ResponseEntity.notFound().build(); result = ResponseEntity.notFound().build();
} else { } else {
// Artifact presence is ensured in 'checkModule' // Artifact presence is ensured in 'checkModule'
@@ -239,7 +238,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
} }
private static boolean checkModule(final String fileName, final SoftwareModule module) { private static boolean checkModule(final String fileName, final SoftwareModule module) {
return null == module || !module.getArtifactByFilename(fileName).isPresent(); return module == null || module.getArtifactByFilename(fileName).isEmpty();
} }
@Override @Override
@@ -256,7 +255,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId)); .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (checkModule(fileName, module)) { if (checkModule(fileName, module)) {
LOG.warn("Software module with id {} could not be found.", softwareModuleId); log.warn("Software module with id {} could not be found.", softwareModuleId);
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }
@@ -269,7 +268,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
FileStreamingUtil.writeMD5FileResponse(requestResponseContextHolder.getHttpServletResponse(), FileStreamingUtil.writeMD5FileResponse(requestResponseContextHolder.getHttpServletResponse(),
artifact.getMd5Hash(), fileName); artifact.getMd5Hash(), fileName);
} catch (final IOException e) { } catch (final IOException e) {
LOG.error("Failed to stream MD5 File", e); log.error("Failed to stream MD5 File", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} }
@@ -283,7 +282,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
@PathVariable("actionId") final Long actionId, @PathVariable("actionId") final Long actionId,
@RequestParam(value = "c", required = false, defaultValue = "-1") final int resource, @RequestParam(value = "c", required = false, defaultValue = "-1") final int resource,
@RequestParam(value = "actionHistory", defaultValue = DdiRestConstants.NO_ACTION_HISTORY) final Integer actionHistoryMessageCount) { @RequestParam(value = "actionHistory", defaultValue = DdiRestConstants.NO_ACTION_HISTORY) final Integer actionHistoryMessageCount) {
LOG.debug("getControllerBasedeploymentAction({},{})", controllerId, resource); log.debug("getControllerBasedeploymentAction({},{})", controllerId, resource);
final Target target = findTarget(controllerId); final Target target = findTarget(controllerId);
final Action action = findActionForTarget(actionId, target); final Action action = findActionForTarget(actionId, target);
@@ -294,7 +293,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
final DdiDeploymentBase base = generateDdiDeploymentBase(target, action, actionHistoryMessageCount); final DdiDeploymentBase base = generateDdiDeploymentBase(target, action, actionHistoryMessageCount);
LOG.debug("Found an active UpdateAction for target {}. returning deployment: {}", controllerId, base); log.debug("Found an active UpdateAction for target {}. returning deployment: {}", controllerId, base);
controllerManagement.registerRetrieved(action.getId(), RepositoryConstants.SERVER_MESSAGE_PREFIX controllerManagement.registerRetrieved(action.getId(), RepositoryConstants.SERVER_MESSAGE_PREFIX
+ "Target retrieved update action and should start now the download."); + "Target retrieved update action and should start now the download.");
@@ -333,7 +332,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
public ResponseEntity<Void> postBasedeploymentActionFeedback(@Valid @RequestBody final DdiActionFeedback feedback, public ResponseEntity<Void> postBasedeploymentActionFeedback(@Valid @RequestBody final DdiActionFeedback feedback,
@PathVariable("tenant") final String tenant, @PathVariable("controllerId") final String controllerId, @PathVariable("tenant") final String tenant, @PathVariable("controllerId") final String controllerId,
@PathVariable("actionId") @NotNull final Long actionId) { @PathVariable("actionId") @NotNull final Long actionId) {
LOG.debug("provideBasedeploymentActionFeedback for target [{},{}]: {}", controllerId, actionId, feedback); log.debug("provideBasedeploymentActionFeedback for target [{},{}]: {}", controllerId, actionId, feedback);
final Target target = findTarget(controllerId); final Target target = findTarget(controllerId);
final Action action = findActionForTarget(actionId, target); final Action action = findActionForTarget(actionId, target);
@@ -343,7 +342,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
} }
if (!action.isActive()) { if (!action.isActive()) {
LOG.warn("Updating action {} with feedback {} not possible since action not active anymore.", log.warn("Updating action {} with feedback {} not possible since action not active anymore.",
action.getId(), feedback.getStatus()); action.getId(), feedback.getStatus());
return new ResponseEntity<>(HttpStatus.GONE); return new ResponseEntity<>(HttpStatus.GONE);
} }
@@ -374,13 +373,13 @@ public class DdiRootController implements DdiRootControllerRestApi {
final Status status; final Status status;
switch (feedback.getStatus().getExecution()) { switch (feedback.getStatus().getExecution()) {
case CANCELED: case CANCELED:
LOG.debug("Controller confirmed cancel (actionId: {}, controllerId: {}) as we got {} report.", actionId, log.debug("Controller confirmed cancel (actionId: {}, controllerId: {}) as we got {} report.", actionId,
controllerId, feedback.getStatus().getExecution()); controllerId, feedback.getStatus().getExecution());
status = Status.CANCELED; status = Status.CANCELED;
addMessageIfEmpty("Target confirmed cancellation.", messages); addMessageIfEmpty("Target confirmed cancellation.", messages);
break; break;
case REJECTED: case REJECTED:
LOG.info("Controller reported internal error (actionId: {}, controllerId: {}) as we got {} report.", log.info("Controller reported internal error (actionId: {}, controllerId: {}) as we got {} report.",
actionId, controllerId, feedback.getStatus().getExecution()); actionId, controllerId, feedback.getStatus().getExecution());
status = Status.WARNING; status = Status.WARNING;
addMessageIfEmpty("Target REJECTED update", messages); addMessageIfEmpty("Target REJECTED update", messages);
@@ -389,13 +388,13 @@ public class DdiRootController implements DdiRootControllerRestApi {
status = handleClosedCase(feedback, controllerId, actionId, messages); status = handleClosedCase(feedback, controllerId, actionId, messages);
break; break;
case DOWNLOAD: case DOWNLOAD:
LOG.debug("Controller confirmed status of download (actionId: {}, controllerId: {}) as we got {} report.", log.debug("Controller confirmed status of download (actionId: {}, controllerId: {}) as we got {} report.",
actionId, controllerId, feedback.getStatus().getExecution()); actionId, controllerId, feedback.getStatus().getExecution());
status = Status.DOWNLOAD; status = Status.DOWNLOAD;
addMessageIfEmpty("Target confirmed download start", messages); addMessageIfEmpty("Target confirmed download start", messages);
break; break;
case DOWNLOADED: case DOWNLOADED:
LOG.debug("Controller confirmed download (actionId: {}, controllerId: {}) as we got {} report.", actionId, log.debug("Controller confirmed download (actionId: {}, controllerId: {}) as we got {} report.", actionId,
controllerId, feedback.getStatus().getExecution()); controllerId, feedback.getStatus().getExecution());
status = Status.DOWNLOADED; status = Status.DOWNLOADED;
addMessageIfEmpty("Target confirmed download finished", messages); addMessageIfEmpty("Target confirmed download finished", messages);
@@ -417,7 +416,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
private Status handleDefaultCase(final DdiActionFeedback feedback, final String controllerId, final Long actionId, private Status handleDefaultCase(final DdiActionFeedback feedback, final String controllerId, final Long actionId,
final List<String> messages) { final List<String> messages) {
final Status status; final Status status;
LOG.debug("Controller reported intermediate status (actionId: {}, controllerId: {}) as we got {} report.", log.debug("Controller reported intermediate status (actionId: {}, controllerId: {}) as we got {} report.",
actionId, controllerId, feedback.getStatus().getExecution()); actionId, controllerId, feedback.getStatus().getExecution());
status = Status.RUNNING; status = Status.RUNNING;
addMessageIfEmpty("Target reported " + feedback.getStatus().getExecution(), messages); addMessageIfEmpty("Target reported " + feedback.getStatus().getExecution(), messages);
@@ -427,7 +426,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
private Status handleClosedCase(final DdiActionFeedback feedback, final String controllerId, final Long actionId, private Status handleClosedCase(final DdiActionFeedback feedback, final String controllerId, final Long actionId,
final List<String> messages) { final List<String> messages) {
final Status status; final Status status;
LOG.debug("Controller reported closed (actionId: {}, controllerId: {}) as we got {} report.", actionId, log.debug("Controller reported closed (actionId: {}, controllerId: {}) as we got {} report.", actionId,
controllerId, feedback.getStatus().getExecution()); controllerId, feedback.getStatus().getExecution());
if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) { if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) {
status = Status.ERROR; status = Status.ERROR;
@@ -451,7 +450,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
public ResponseEntity<DdiCancel> getControllerCancelAction(@PathVariable("tenant") final String tenant, public ResponseEntity<DdiCancel> getControllerCancelAction(@PathVariable("tenant") final String tenant,
@PathVariable("controllerId") @NotEmpty final String controllerId, @PathVariable("controllerId") @NotEmpty final String controllerId,
@PathVariable("actionId") @NotNull final Long actionId) { @PathVariable("actionId") @NotNull final Long actionId) {
LOG.debug("getControllerCancelAction({})", controllerId); log.debug("getControllerCancelAction({})", controllerId);
final Target target = findTarget(controllerId); final Target target = findTarget(controllerId);
final Action action = findActionForTarget(actionId, target); final Action action = findActionForTarget(actionId, target);
@@ -460,7 +459,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
final DdiCancel cancel = new DdiCancel(String.valueOf(action.getId()), final DdiCancel cancel = new DdiCancel(String.valueOf(action.getId()),
new DdiCancelActionToStop(String.valueOf(action.getId()))); new DdiCancelActionToStop(String.valueOf(action.getId())));
LOG.debug("Found an active CancelAction for target {}. returning cancel: {}", controllerId, cancel); log.debug("Found an active CancelAction for target {}. returning cancel: {}", controllerId, cancel);
controllerManagement.registerRetrieved(action.getId(), RepositoryConstants.SERVER_MESSAGE_PREFIX controllerManagement.registerRetrieved(action.getId(), RepositoryConstants.SERVER_MESSAGE_PREFIX
+ "Target retrieved cancel action and should start now the cancellation."); + "Target retrieved cancel action and should start now the cancellation.");
@@ -476,7 +475,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
@PathVariable("tenant") final String tenant, @PathVariable("tenant") final String tenant,
@PathVariable("controllerId") @NotEmpty final String controllerId, @PathVariable("controllerId") @NotEmpty final String controllerId,
@PathVariable("actionId") @NotNull final Long actionId) { @PathVariable("actionId") @NotNull final Long actionId) {
LOG.debug("provideCancelActionFeedback for target [{}]: {}", controllerId, feedback); log.debug("provideCancelActionFeedback for target [{}]: {}", controllerId, feedback);
final Target target = findTarget(controllerId); final Target target = findTarget(controllerId);
final Action action = findActionForTarget(actionId, target); final Action action = findActionForTarget(actionId, target);
@@ -490,7 +489,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
public ResponseEntity<DdiDeploymentBase> getControllerInstalledAction(@PathVariable("tenant") final String tenant, public ResponseEntity<DdiDeploymentBase> getControllerInstalledAction(@PathVariable("tenant") final String tenant,
@PathVariable("controllerId") final String controllerId, @PathVariable("actionId") final Long actionId, @PathVariable("controllerId") final String controllerId, @PathVariable("actionId") final Long actionId,
@RequestParam(value = "actionHistory", defaultValue = DdiRestConstants.NO_ACTION_HISTORY) final Integer actionHistoryMessageCount) { @RequestParam(value = "actionHistory", defaultValue = DdiRestConstants.NO_ACTION_HISTORY) final Integer actionHistoryMessageCount) {
LOG.debug("getControllerInstalledAction({})", controllerId); log.debug("getControllerInstalledAction({})", controllerId);
final Target target = findTarget(controllerId); final Target target = findTarget(controllerId);
final Action action = findActionForTarget(actionId, target); final Action action = findActionForTarget(actionId, target);
@@ -501,7 +500,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
final DdiDeploymentBase base = generateDdiDeploymentBase(target, action, actionHistoryMessageCount); final DdiDeploymentBase base = generateDdiDeploymentBase(target, action, actionHistoryMessageCount);
LOG.debug("Found an installed UpdateAction for target {}. returning deployment: {}", controllerId, base); log.debug("Found an installed UpdateAction for target {}. returning deployment: {}", controllerId, base);
return new ResponseEntity<>(base, HttpStatus.OK); return new ResponseEntity<>(base, HttpStatus.OK);
} }
@@ -518,7 +517,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
status = handleCaseCancelCanceled(feedback, target, actionId, messages); status = handleCaseCancelCanceled(feedback, target, actionId, messages);
break; break;
case REJECTED: case REJECTED:
LOG.info("Target rejected the cancellation request (actionId: {}, controllerId: {}).", actionId, log.info("Target rejected the cancellation request (actionId: {}, controllerId: {}).", actionId,
target.getControllerId()); target.getControllerId());
status = Status.CANCEL_REJECTED; status = Status.CANCEL_REJECTED;
messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target rejected the cancellation request."); messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target rejected the cancellation request.");
@@ -560,7 +559,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
private static Status handleCaseCancelCanceled(final DdiActionFeedback feedback, final Target target, private static Status handleCaseCancelCanceled(final DdiActionFeedback feedback, final Target target,
final Long actionId, final List<String> messages) { final Long actionId, final List<String> messages) {
final Status status; final Status status;
LOG.error( log.error(
"Target reported cancel for a cancel which is not supported by the server (actionId: {}, controllerId: {}) as we got {} report.", "Target reported cancel for a cancel which is not supported by the server (actionId: {}, controllerId: {}) as we got {} report.",
actionId, target.getControllerId(), feedback.getStatus().getExecution()); actionId, target.getControllerId(), feedback.getStatus().getExecution());
status = Status.WARNING; status = Status.WARNING;
@@ -582,7 +581,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
private Action verifyActionBelongsToTarget(final Action action, final Target target) { private Action verifyActionBelongsToTarget(final Action action, final Target target) {
if (!action.getTarget().getId().equals(target.getId())) { if (!action.getTarget().getId().equals(target.getId())) {
LOG.debug(GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET, action.getId(), target.getId()); log.debug(GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET, action.getId(), target.getId());
throw new EntityNotFoundException( throw new EntityNotFoundException(
"Not a valid action (" + action.getId() + ") for target: " + target.getControllerId(), null); "Not a valid action (" + action.getId() + ") for target: " + target.getControllerId(), null);
} }
@@ -601,7 +600,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
try { try {
controllerManagement.cancelAction(action.getId()); controllerManagement.cancelAction(action.getId());
} catch (final CancelActionNotAllowedException e) { } catch (final CancelActionNotAllowedException e) {
LOG.info("Cancel action not allowed: {}", e.getMessage()); log.info("Cancel action not allowed: {}", e.getMessage());
} }
} }
} }
@@ -624,7 +623,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
@PathVariable("actionId") final Long actionId, @PathVariable("actionId") final Long actionId,
@RequestParam(value = "c", required = false, defaultValue = "-1") final int resource, @RequestParam(value = "c", required = false, defaultValue = "-1") final int resource,
@RequestParam(value = "actionHistory", defaultValue = DdiRestConstants.NO_ACTION_HISTORY) final Integer actionHistoryMessageCount) { @RequestParam(value = "actionHistory", defaultValue = DdiRestConstants.NO_ACTION_HISTORY) final Integer actionHistoryMessageCount) {
LOG.debug("getConfirmationBaseAction({},{})", controllerId, resource); log.debug("getConfirmationBaseAction({},{})", controllerId, resource);
final Target target = findTarget(controllerId); final Target target = findTarget(controllerId);
final Action action = findActionForTarget(actionId, target); final Action action = findActionForTarget(actionId, target);
@@ -636,7 +635,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
final DdiConfirmationBaseAction base = generateDdiConfirmationBase(target, action, final DdiConfirmationBaseAction base = generateDdiConfirmationBase(target, action,
actionHistoryMessageCount); actionHistoryMessageCount);
LOG.debug("Found an active UpdateAction for target {}. Returning confirmation: {}", controllerId, base); log.debug("Found an active UpdateAction for target {}. Returning confirmation: {}", controllerId, base);
return new ResponseEntity<>(base, HttpStatus.OK); return new ResponseEntity<>(base, HttpStatus.OK);
} }
@@ -682,7 +681,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
@Valid @RequestBody final DdiConfirmationFeedback feedback, @PathVariable("tenant") final String tenant, @Valid @RequestBody final DdiConfirmationFeedback feedback, @PathVariable("tenant") final String tenant,
@PathVariable("controllerId") final String controllerId, @PathVariable("controllerId") final String controllerId,
@PathVariable("actionId") @NotNull final Long actionId) { @PathVariable("actionId") @NotNull final Long actionId) {
LOG.debug("provideConfirmationActionFeedback with feedback [controllerId={}, actionId={}]: {}", controllerId, log.debug("provideConfirmationActionFeedback with feedback [controllerId={}, actionId={}]: {}", controllerId,
actionId, feedback); actionId, feedback);
final Target target = findTarget(controllerId); final Target target = findTarget(controllerId);
@@ -692,24 +691,24 @@ public class DdiRootController implements DdiRootControllerRestApi {
switch (feedback.getConfirmation()) { switch (feedback.getConfirmation()) {
case CONFIRMED: case CONFIRMED:
LOG.info("Controller confirmed the action (actionId: {}, controllerId: {}) as we got {} report.", log.info("Controller confirmed the action (actionId: {}, controllerId: {}) as we got {} report.",
actionId, controllerId, feedback.getConfirmation()); actionId, controllerId, feedback.getConfirmation());
confirmationManagement.confirmAction(actionId, feedback.getCode(), feedback.getDetails()); confirmationManagement.confirmAction(actionId, feedback.getCode(), feedback.getDetails());
break; break;
case DENIED: case DENIED:
default: default:
LOG.debug("Controller denied the action (actionId: {}, controllerId: {}) as we got {} report.", log.debug("Controller denied the action (actionId: {}, controllerId: {}) as we got {} report.",
actionId, controllerId, feedback.getConfirmation()); actionId, controllerId, feedback.getConfirmation());
confirmationManagement.denyAction(actionId, feedback.getCode(), feedback.getDetails()); confirmationManagement.denyAction(actionId, feedback.getCode(), feedback.getDetails());
break; break;
} }
} catch (final InvalidConfirmationFeedbackException e) { } catch (final InvalidConfirmationFeedbackException e) {
if (e.getReason() == InvalidConfirmationFeedbackException.Reason.ACTION_CLOSED) { if (e.getReason() == InvalidConfirmationFeedbackException.Reason.ACTION_CLOSED) {
LOG.warn("Updating action {} with confirmation {} not possible since action not active anymore.", log.warn("Updating action {} with confirmation {} not possible since action not active anymore.",
action.getId(), feedback.getConfirmation()); action.getId(), feedback.getConfirmation());
return new ResponseEntity<>(HttpStatus.GONE); return new ResponseEntity<>(HttpStatus.GONE);
} else if (e.getReason() == InvalidConfirmationFeedbackException.Reason.NOT_AWAITING_CONFIRMATION) { } else if (e.getReason() == InvalidConfirmationFeedbackException.Reason.NOT_AWAITING_CONFIRMATION) {
LOG.debug("Action is not waiting for confirmation, deny request."); log.debug("Action is not waiting for confirmation, deny request.");
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }
} }
@@ -719,7 +718,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
@Override @Override
public ResponseEntity<DdiConfirmationBase> getConfirmationBase(final String tenant, final String controllerId) { public ResponseEntity<DdiConfirmationBase> getConfirmationBase(final String tenant, final String controllerId) {
LOG.debug("getConfirmationBase is called [controllerId={}].", controllerId); log.debug("getConfirmationBase is called [controllerId={}].", controllerId);
final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotExist(controllerId, IpUtil final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotExist(controllerId, IpUtil
.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties)); .getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties));
final Action activeAction = controllerManagement.findActiveActionWithHighestWeight(controllerId).orElse(null); final Action activeAction = controllerManagement.findActiveActionWithHighestWeight(controllerId).orElse(null);
@@ -736,11 +735,11 @@ public class DdiRootController implements DdiRootControllerRestApi {
final DdiAutoConfirmationState state = DdiAutoConfirmationState.active(status.getActivatedAt()); final DdiAutoConfirmationState state = DdiAutoConfirmationState.active(status.getActivatedAt());
state.setInitiator(status.getInitiator()); state.setInitiator(status.getInitiator());
state.setRemark(status.getRemark()); state.setRemark(status.getRemark());
LOG.trace("Returning state auto-conf state active [initiator='{}' | activatedAt={}] for device {}", log.trace("Returning state auto-conf state active [initiator='{}' | activatedAt={}] for device {}",
controllerId, status.getInitiator(), status.getActivatedAt()); controllerId, status.getInitiator(), status.getActivatedAt());
return state; return state;
}).orElseGet(() -> { }).orElseGet(() -> {
LOG.trace("Returning state auto-conf state disabled for device {}", controllerId); log.trace("Returning state auto-conf state disabled for device {}", controllerId);
return DdiAutoConfirmationState.disabled(); return DdiAutoConfirmationState.disabled();
}); });
} }
@@ -750,7 +749,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
final DdiActivateAutoConfirmation body) { final DdiActivateAutoConfirmation body) {
final String initiator = body == null ? null : body.getInitiator(); final String initiator = body == null ? null : body.getInitiator();
final String remark = body == null ? FALLBACK_REMARK : body.getRemark(); final String remark = body == null ? FALLBACK_REMARK : body.getRemark();
LOG.debug("Activate auto-confirmation request for device '{}' with payload: [initiator='{}' | remark='{}'", log.debug("Activate auto-confirmation request for device '{}' with payload: [initiator='{}' | remark='{}'",
controllerId, initiator, remark); controllerId, initiator, remark);
confirmationManagement.activateAutoConfirmation(controllerId, initiator, remark); confirmationManagement.activateAutoConfirmation(controllerId, initiator, remark);
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
@@ -758,7 +757,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
@Override @Override
public ResponseEntity<Void> deactivateAutoConfirmation(final String tenant, final String controllerId) { public ResponseEntity<Void> deactivateAutoConfirmation(final String tenant, final String controllerId) {
LOG.debug("Deactivate auto-confirmation request for device {}", controllerId); log.debug("Deactivate auto-confirmation request for device {}", controllerId);
confirmationManagement.deactivateAutoConfirmation(controllerId); confirmationManagement.deactivateAutoConfirmation(controllerId);
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }

View File

@@ -10,6 +10,8 @@
package org.eclipse.hawkbit.mgmt.json.model.action; package org.eclipse.hawkbit.mgmt.json.model.action;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.eclipse.hawkbit.mgmt.json.model.MgmtBaseEntity; import org.eclipse.hawkbit.mgmt.json.model.MgmtBaseEntity;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMaintenanceWindow; import org.eclipse.hawkbit.mgmt.json.model.MgmtMaintenanceWindow;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType; import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType;
@@ -21,8 +23,9 @@ import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* A json annotated rest model for Action to RESTful API representation. * A json annotated rest model for Action to RESTful API representation.
*
*/ */
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtAction extends MgmtBaseEntity { public class MgmtAction extends MgmtBaseEntity {
@@ -31,17 +34,14 @@ public class MgmtAction extends MgmtBaseEntity {
* API definition for action in update mode. * API definition for action in update mode.
*/ */
public static final String ACTION_UPDATE = "update"; public static final String ACTION_UPDATE = "update";
/** /**
* API definition for action in canceling. * API definition for action in canceling.
*/ */
public static final String ACTION_CANCEL = "cancel"; public static final String ACTION_CANCEL = "cancel";
/** /**
* API definition for action completed. * API definition for action completed.
*/ */
public static final String ACTION_FINISHED = "finished"; public static final String ACTION_FINISHED = "finished";
/** /**
* API definition for action still active. * API definition for action still active.
*/ */
@@ -50,132 +50,33 @@ public class MgmtAction extends MgmtBaseEntity {
@JsonProperty("id") @JsonProperty("id")
@Schema(example = "7") @Schema(example = "7")
private Long actionId; private Long actionId;
@JsonProperty @JsonProperty
@Schema(example = "update") @Schema(example = "update")
private String type; private String type;
@JsonProperty @JsonProperty
@Schema(example = "finished") @Schema(example = "finished")
private String status; private String status;
@JsonProperty @JsonProperty
@Schema(example = "finished") @Schema(example = "finished")
private String detailStatus; private String detailStatus;
@JsonProperty @JsonProperty
@Schema(example = "1691065903238") @Schema(example = "1691065903238")
private Long forceTime; private Long forceTime;
@JsonProperty(value = "forceType") @JsonProperty(value = "forceType")
private MgmtActionType actionType; private MgmtActionType actionType;
@JsonProperty @JsonProperty
@Schema(example = "600") @Schema(example = "600")
private Integer weight; private Integer weight;
@JsonProperty @JsonProperty
@Schema(hidden = true) @Schema(hidden = true)
private MgmtMaintenanceWindow maintenanceWindow; private MgmtMaintenanceWindow maintenanceWindow;
@JsonProperty @JsonProperty
@Schema(example = "1") @Schema(example = "1")
private Long rollout; private Long rollout;
@JsonProperty @JsonProperty
@Schema(example = "rollout") @Schema(example = "rollout")
private String rolloutName; private String rolloutName;
@JsonProperty @JsonProperty
@Schema(example = "200") @Schema(example = "200")
private Integer lastStatusCode; private Integer lastStatusCode;
public MgmtMaintenanceWindow getMaintenanceWindow() {
return maintenanceWindow;
}
public void setMaintenanceWindow(final MgmtMaintenanceWindow maintenanceWindow) {
this.maintenanceWindow = maintenanceWindow;
}
public Long getForceTime() {
return forceTime;
}
public void setForceTime(final Long forceTime) {
this.forceTime = forceTime;
}
public Integer getWeight() {
return weight;
}
public void setWeight(final Integer weight) {
this.weight = weight;
}
public MgmtActionType getActionType() {
return actionType;
}
public void setActionType(final MgmtActionType actionType) {
this.actionType = actionType;
}
public String getStatus() {
return status;
}
public void setStatus(final String status) {
this.status = status;
}
public Long getActionId() {
return actionId;
}
public void setActionId(final Long actionId) {
this.actionId = actionId;
}
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
public Long getRollout() {
return rollout;
}
public void setRollout(final Long rollout) {
this.rollout = rollout;
}
public String getRolloutName() {
return rolloutName;
}
public void setRolloutName(final String rolloutName) {
this.rolloutName = rolloutName;
}
public String getDetailStatus() {
return detailStatus;
}
public void setDetailStatus(final String detailStatus) {
this.detailStatus = detailStatus;
}
public Integer getLastStatusCode() {
return lastStatusCode;
}
public void setLastStatusCode(final Integer lastStatusCode) {
this.lastStatusCode = lastStatusCode;
}
} }

View File

@@ -9,25 +9,17 @@
*/ */
package org.eclipse.hawkbit.mgmt.json.model.action; package org.eclipse.hawkbit.mgmt.json.model.action;
import lombok.Data;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType; import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* A json annotated model for Action updates in RESTful API representation. * A json annotated model for Action updates in RESTful API representation.
*
*/ */
@Data
public class MgmtActionRequestBodyPut { public class MgmtActionRequestBodyPut {
@JsonProperty(value="forceType") @JsonProperty(value="forceType")
private MgmtActionType actionType; private MgmtActionType actionType;
public MgmtActionType getActionType() {
return actionType;
}
public void setActionType(final MgmtActionType actionType) {
this.actionType = actionType;
}
} }

View File

@@ -16,11 +16,12 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/** /**
* A json annotated rest model for ActionStatus to RESTful API representation. * A json annotated rest model for ActionStatus to RESTful API representation.
*
*/ */
@Data
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtActionStatus { public class MgmtActionStatus {
@@ -28,94 +29,15 @@ public class MgmtActionStatus {
@JsonProperty("id") @JsonProperty("id")
@Schema(example = "21") @Schema(example = "21")
private Long statusId; private Long statusId;
@JsonProperty @JsonProperty
@Schema(example = "running") @Schema(example = "running")
private String type; private String type;
@JsonProperty @JsonProperty
private List<String> messages; private List<String> messages;
@JsonProperty @JsonProperty
@Schema(example = "1691065929524") @Schema(example = "1691065929524")
private Long reportedAt; private Long reportedAt;
@JsonProperty @JsonProperty
@Schema(example = "200") @Schema(example = "200")
private Integer code; private Integer code;
/**
* @return the statusId
*/
public Long getStatusId() {
return statusId;
}
/**
* @param statusId
* the statusId to set
*/
public void setStatusId(final Long statusId) {
this.statusId = statusId;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type
* the type to set
*/
public void setType(final String type) {
this.type = type;
}
/**
* @return the messages
*/
public List<String> getMessages() {
return messages;
}
/**
* @param messages
* the messages to set
*/
public void setMessages(final List<String> messages) {
this.messages = messages;
}
/**
* @return the reportedAt
*/
public Long getReportedAt() {
return reportedAt;
}
/**
* @param reportedAt
* the reportedAt to set
*/
public void setReportedAt(final Long reportedAt) {
this.reportedAt = reportedAt;
}
/**
* @return the code
*/
public Integer getCode() {
return code;
}
/**
* @param code
* the reported code to set
*/
public void setCode(final Integer code) {
this.code = code;
}
} }

View File

@@ -10,6 +10,8 @@
package org.eclipse.hawkbit.mgmt.json.model.artifact; package org.eclipse.hawkbit.mgmt.json.model.artifact;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.eclipse.hawkbit.mgmt.json.model.MgmtBaseEntity; import org.eclipse.hawkbit.mgmt.json.model.MgmtBaseEntity;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -21,6 +23,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* A json annotated rest model for Artifact to RESTful API representation. * A json annotated rest model for Artifact to RESTful API representation.
*/ */
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtArtifact extends MgmtBaseEntity { public class MgmtArtifact extends MgmtBaseEntity {
@@ -28,84 +32,12 @@ public class MgmtArtifact extends MgmtBaseEntity {
@JsonProperty("id") @JsonProperty("id")
@Schema(example = "3") @Schema(example = "3")
private Long artifactId; private Long artifactId;
@JsonProperty @JsonProperty
private MgmtArtifactHash hashes; private MgmtArtifactHash hashes;
@JsonProperty @JsonProperty
@Schema(example = "file1") @Schema(example = "file1")
private String providedFilename; private String providedFilename;
@JsonProperty @JsonProperty
@Schema(example = "3") @Schema(example = "3")
private Long size; private Long size;
public MgmtArtifact() {
// need for json encoder
}
/**
* @param hashes
* the hashes to set
*/
@JsonIgnore
public void setHashes(final MgmtArtifactHash hashes) {
this.hashes = hashes;
}
/**
* @param artifactId
* the artifactId to set
*/
@JsonIgnore
public void setArtifactId(final Long artifactId) {
this.artifactId = artifactId;
}
/**
* @return the artifactId
*/
public Long getArtifactId() {
return artifactId;
}
/**
* @return the hashes
*/
public MgmtArtifactHash getHashes() {
return hashes;
}
/**
* @return the providedFilename
*/
public String getProvidedFilename() {
return providedFilename;
}
/**
* @param providedFilename
* the providedFilename to set
*/
@JsonIgnore
public void setProvidedFilename(final String providedFilename) {
this.providedFilename = providedFilename;
}
/**
* @return the size
*/
public Long getSize() {
return size;
}
/**
* @param size
* the size to set
*/
@JsonIgnore
public void setSize(final Long size) {
this.size = size;
}
} }

View File

@@ -11,33 +11,28 @@ package org.eclipse.hawkbit.mgmt.json.model.artifact;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
/** /**
* Hashes for given Artifact. * Hashes for given Artifact.
*
*
*/ */
@NoArgsConstructor // used for jackson to instantiate
@Getter
@EqualsAndHashCode
public class MgmtArtifactHash { public class MgmtArtifactHash {
@JsonProperty @JsonProperty
@Schema(example = "2d86c2a659e364e9abba49ea6ffcd53dd5559f05") @Schema(example = "2d86c2a659e364e9abba49ea6ffcd53dd5559f05")
private String sha1; private String sha1;
@JsonProperty @JsonProperty
@Schema(example = "0d1b08c34858921bc7c662b228acb7ba") @Schema(example = "0d1b08c34858921bc7c662b228acb7ba")
private String md5; private String md5;
@JsonProperty @JsonProperty
@Schema(example = "a03b221c6c6eae7122ca51695d456d5222e524889136394944b2f9763b483615") @Schema(example = "a03b221c6c6eae7122ca51695d456d5222e524889136394944b2f9763b483615")
private String sha256; private String sha256;
/**
* Default constructor.
*/
public MgmtArtifactHash() {
// used for jackson to instantiate
}
/** /**
* Public constructor. * Public constructor.
*/ */
@@ -46,17 +41,4 @@ public class MgmtArtifactHash {
this.md5 = md5; this.md5 = md5;
this.sha256 = sha256; this.sha256 = sha256;
} }
public String getSha1() {
return sha1;
}
public String getMd5() {
return md5;
}
public String getSha256() {
return sha256;
}
} }

View File

@@ -9,41 +9,14 @@
*/ */
package org.eclipse.hawkbit.mgmt.json.model.auth; package org.eclipse.hawkbit.mgmt.json.model.auth;
import lombok.Data;
/** /**
* A json annotated rest model for Userinfo to RESTful API representation. * A json annotated rest model for Userinfo to RESTful API representation.
*
*/ */
@Data
public class MgmtUserInfo { public class MgmtUserInfo {
private String username; private String username;
private String tenant; private String tenant;
/**
* @return Username
*/
public String getUsername() {
return username;
}
/**
* @param username Username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return Tenant
*/
public String getTenant() {
return tenant;
}
/**
* @param tenant Tenant
*/
public void setTenant(String tenant) {
this.tenant = tenant;
}
} }

View File

@@ -14,6 +14,9 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
import java.util.Objects; import java.util.Objects;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi;
import org.springframework.hateoas.RepresentationModel; import org.springframework.hateoas.RepresentationModel;
@@ -25,44 +28,23 @@ import com.fasterxml.jackson.annotation.JsonProperty;
* Representation of an Action Id as a Json Object with link to the Action * Representation of an Action Id as a Json Object with link to the Action
* resource * resource
*/ */
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtActionId extends RepresentationModel<MgmtActionId> { public class MgmtActionId extends RepresentationModel<MgmtActionId> {
private long actionId; private long actionId;
public MgmtActionId() {
}
/** /**
* Constructor * Constructor
* *
* @param actionId * @param actionId the actionId
* the actionId * @param controllerId the controller Id
* @param controllerId
* the controller Id
*/ */
public MgmtActionId(final String controllerId, final long actionId) { public MgmtActionId(final String controllerId, final long actionId) {
this.actionId = actionId; this.actionId = actionId;
add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(controllerId, actionId)).withSelfRel().expand()); add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(controllerId, actionId)).withSelfRel().expand());
} }
@JsonProperty("id")
public long getActionId() {
return actionId;
}
public void setActionId(final long actionId) {
this.actionId = actionId;
}
@Override
public boolean equals(final Object obj) {
return super.equals(obj) && this.getClass().isInstance(obj) && actionId == ((MgmtActionId) obj).getActionId();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), actionId);
}
} }

View File

@@ -13,24 +13,21 @@ import com.fasterxml.jackson.annotation.JsonValue;
/** /**
* Definition of the Action type for the REST management API. * Definition of the Action type for the REST management API.
*
*/ */
public enum MgmtActionType { public enum MgmtActionType {
/** /**
* The soft action type. * The soft action type.
*/ */
SOFT("soft"), SOFT("soft"),
/** /**
* The forced action type. * The forced action type.
*/ */
FORCED("forced"), FORCED("forced"),
/** /**
* The time forced action type. * The time forced action type.
*/ */
TIMEFORCED("timeforced"), TIMEFORCED("timeforced"),
/** /**
* The Download-Only action type. * The Download-Only action type.
*/ */
@@ -38,7 +35,7 @@ public enum MgmtActionType {
private final String name; private final String name;
private MgmtActionType(final String name) { MgmtActionType(final String name) {
this.name = name; this.name = name;
} }
@@ -46,5 +43,4 @@ public enum MgmtActionType {
public String getName() { public String getName() {
return name; return name;
} }
} }

View File

@@ -17,16 +17,15 @@ import com.fasterxml.jackson.annotation.JsonValue;
* *
*/ */
public enum MgmtCancelationType { public enum MgmtCancelationType {
/** /**
* Actions will be soft canceled. * Actions will be soft canceled.
*/ */
SOFT("soft"), SOFT("soft"),
/** /**
* Actions will be force quit. * Actions will be force quit.
*/ */
FORCE("force"), FORCE("force"),
/** /**
* No actions will be canceled. * No actions will be canceled.
*/ */
@@ -34,7 +33,7 @@ public enum MgmtCancelationType {
private final String name; private final String name;
private MgmtCancelationType(final String name) { MgmtCancelationType(final String name) {
this.name = name; this.name = name;
} }

View File

@@ -13,6 +13,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity;
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule; import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule;
@@ -26,6 +28,8 @@ import com.fasterxml.jackson.annotation.JsonProperty;
* A json annotated rest model for DistributionSet to RESTful API * A json annotated rest model for DistributionSet to RESTful API
* representation. * representation.
*/ */
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtDistributionSet extends MgmtNamedEntity { public class MgmtDistributionSet extends MgmtNamedEntity {
@@ -33,109 +37,27 @@ public class MgmtDistributionSet extends MgmtNamedEntity {
@JsonProperty(value = "id", required = true) @JsonProperty(value = "id", required = true)
@Schema(example = "51") @Schema(example = "51")
private Long dsId; private Long dsId;
@JsonProperty @JsonProperty
@Schema(example = "1.4.2") @Schema(example = "1.4.2")
private String version; private String version;
@JsonProperty @JsonProperty
private List<MgmtSoftwareModule> modules = new ArrayList<>(); private List<MgmtSoftwareModule> modules = new ArrayList<>();
@JsonProperty @JsonProperty
@Schema(example = "false") @Schema(example = "false")
private boolean requiredMigrationStep; private boolean requiredMigrationStep;
@JsonProperty @JsonProperty
@Schema(example = "test_default_ds_type") @Schema(example = "test_default_ds_type")
private String type; private String type;
@JsonProperty @JsonProperty
@Schema(example = "OS (FW) mandatory, runtime (FW) and app (SW) optional") @Schema(example = "OS (FW) mandatory, runtime (FW) and app (SW) optional")
private String typeName; private String typeName;
@JsonProperty @JsonProperty
@Schema(example = "true") @Schema(example = "true")
private Boolean complete; private Boolean complete;
@JsonProperty @JsonProperty
@Schema(example = "false") @Schema(example = "false")
private boolean deleted; private boolean deleted;
@JsonProperty @JsonProperty
@Schema(example = "true") @Schema(example = "true")
private boolean valid; private boolean valid;
public boolean isValid() {
return valid;
}
public void setValid(final boolean valid) {
this.valid = valid;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(final boolean deleted) {
this.deleted = deleted;
}
public Long getDsId() {
return dsId;
}
@JsonIgnore
public void setDsId(final Long id) {
dsId = id;
}
public String getVersion() {
return version;
}
public void setVersion(final String version) {
this.version = version;
}
public boolean isRequiredMigrationStep() {
return requiredMigrationStep;
}
public void setRequiredMigrationStep(final boolean requiredMigrationStep) {
this.requiredMigrationStep = requiredMigrationStep;
}
public List<MgmtSoftwareModule> getModules() {
return modules;
}
public void setModules(final List<MgmtSoftwareModule> modules) {
this.modules = modules;
}
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(final String typeName) {
this.typeName = typeName;
}
public Boolean getComplete() {
return complete;
}
public void setComplete(final Boolean complete) {
this.complete = complete;
}
} }

View File

@@ -12,6 +12,9 @@ package org.eclipse.hawkbit.mgmt.json.model.distributionset;
import java.util.List; import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment; import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@@ -21,8 +24,10 @@ import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* A json annotated rest model for DistributionSet for POST. * A json annotated rest model for DistributionSet for POST.
*
*/ */
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtDistributionSetRequestBodyPost extends MgmtDistributionSetRequestBodyPut { public class MgmtDistributionSetRequestBodyPost extends MgmtDistributionSetRequestBodyPut {
@@ -32,115 +37,16 @@ public class MgmtDistributionSetRequestBodyPost extends MgmtDistributionSetReque
@JsonProperty @JsonProperty
@Schema(hidden = true) @Schema(hidden = true)
private MgmtSoftwareModuleAssigment os; private MgmtSoftwareModuleAssigment os;
@JsonProperty @JsonProperty
@Schema(hidden = true) @Schema(hidden = true)
private MgmtSoftwareModuleAssigment runtime; private MgmtSoftwareModuleAssigment runtime;
@JsonProperty @JsonProperty
@Schema(hidden = true) @Schema(hidden = true)
private MgmtSoftwareModuleAssigment application; private MgmtSoftwareModuleAssigment application;
// deprecated format - END // deprecated format - END
@JsonProperty @JsonProperty
private List<MgmtSoftwareModuleAssigment> modules; private List<MgmtSoftwareModuleAssigment> modules;
@JsonProperty @JsonProperty
@Schema(example = "test_default_ds_type") @Schema(example = "test_default_ds_type")
private String type; private String type;
/**
* @return the os
*/
public MgmtSoftwareModuleAssigment getOs() {
return os;
}
/**
* @param os
* the os to set
*
* @return updated body
*/
public MgmtDistributionSetRequestBodyPost setOs(final MgmtSoftwareModuleAssigment os) {
this.os = os;
return this;
}
/**
* @return the runtime
*/
public MgmtSoftwareModuleAssigment getRuntime() {
return runtime;
}
/**
* @param runtime
* the runtime to set
*
* @return updated body
*/
public MgmtDistributionSetRequestBodyPost setRuntime(final MgmtSoftwareModuleAssigment runtime) {
this.runtime = runtime;
return this;
}
/**
* @return the application
*/
public MgmtSoftwareModuleAssigment getApplication() {
return application;
}
/**
* @param application
* the application to set
*
* @return updated body
*/
public MgmtDistributionSetRequestBodyPost setApplication(final MgmtSoftwareModuleAssigment application) {
this.application = application;
return this;
}
/**
* @return the modules
*/
public List<MgmtSoftwareModuleAssigment> getModules() {
return modules;
}
/**
* @param modules
* the modules to set
*
* @return updated body
*/
public MgmtDistributionSetRequestBodyPost setModules(final List<MgmtSoftwareModuleAssigment> modules) {
this.modules = modules;
return this;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type
* the type to set
*
* @return updated body
*/
public MgmtDistributionSetRequestBodyPost setType(final String type) {
this.type = type;
return this;
}
} }

View File

@@ -14,11 +14,14 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.experimental.Accessors;
/** /**
* A json annotated rest model for DistributionSet for PUT/POST. * A json annotated rest model for DistributionSet for PUT/POST.
*
*/ */
@Data
@Accessors(chain = true)
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtDistributionSetRequestBodyPut { public class MgmtDistributionSetRequestBodyPut {
@@ -26,91 +29,13 @@ public class MgmtDistributionSetRequestBodyPut {
@JsonProperty @JsonProperty
@Schema(example = "dsOne") @Schema(example = "dsOne")
private String name; private String name;
@JsonProperty @JsonProperty
@Schema(example = "Description of the distribution set.") @Schema(example = "Description of the distribution set.")
private String description; private String description;
@JsonProperty @JsonProperty
@Schema(example = "1.0.0") @Schema(example = "1.0.0")
private String version; private String version;
@JsonProperty @JsonProperty
@Schema(example = "false") @Schema(example = "false")
private Boolean requiredMigrationStep; private Boolean requiredMigrationStep;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*
* @return updated body
*/
public MgmtDistributionSetRequestBodyPut setName(final String name) {
this.name = name;
return this;
}
/**
* @return the requiredMigrationStep
*/
public Boolean isRequiredMigrationStep() {
return requiredMigrationStep;
}
/**
* @param requiredMigrationStep
* the requiredMigrationStep to set
*
* @return updated body
*/
public MgmtDistributionSetRequestBodyPut setRequiredMigrationStep(final Boolean requiredMigrationStep) {
this.requiredMigrationStep = requiredMigrationStep;
return this;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description
* the description to set
*
* @return updated body
*/
public MgmtDistributionSetRequestBodyPut setDescription(final String description) {
this.description = description;
return this;
}
/**
* @return the version
*/
public String getVersion() {
return version;
}
/**
* @param version
* the version to set
*
* @return updated body
*/
public MgmtDistributionSetRequestBodyPut setVersion(final String version) {
this.version = version;
return this;
}
} }

View File

@@ -14,40 +14,32 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
@EqualsAndHashCode
@JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtDistributionSetStatistics { public class MgmtDistributionSetStatistics {
private static final String TOTAL = "total"; private static final String TOTAL = "total";
@JsonProperty("actions") @JsonProperty("actions")
private Map<String, Long> totalActionsPerStatus; private Map<String, Long> totalActionsPerStatus;
@JsonProperty("rollouts") @JsonProperty("rollouts")
private Map<String, Long> totalRolloutsPerStatus; private Map<String, Long> totalRolloutsPerStatus;
@JsonProperty @JsonProperty
private Long totalAutoAssignments; private Long totalAutoAssignments;
private MgmtDistributionSetStatistics() {
// Private constructor to enforce the use of the builder pattern
}
public Map<String, Long> getTotalActionsPerStatus() {
return totalActionsPerStatus;
}
public Map<String, Long> getTotalRolloutsPerStatus() {
return totalRolloutsPerStatus;
}
public Long getTotalAutoAssignments() {
return totalAutoAssignments;
}
public static class Builder { public static class Builder {
private final Map<String, Long> totalActionsPerStatus; private final Map<String, Long> totalActionsPerStatus;
private final Map<String, Long> totalRolloutsPerStatus; private final Map<String, Long> totalRolloutsPerStatus;
private Long totalAutoAssignments; private Long totalAutoAssignments;
@@ -101,4 +93,3 @@ public class MgmtDistributionSetStatistics {
} }
} }
} }

View File

@@ -13,11 +13,14 @@ import jakarta.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.experimental.Accessors;
/** /**
* A json annotated rest model for invalidate DistributionSet requests. * A json annotated rest model for invalidate DistributionSet requests.
*
*/ */
@Data
@Accessors(chain = true)
public class MgmtInvalidateDistributionSetRequestBody { public class MgmtInvalidateDistributionSetRequestBody {
@NotNull @NotNull
@@ -26,21 +29,4 @@ public class MgmtInvalidateDistributionSetRequestBody {
@JsonProperty @JsonProperty
@Schema(example = "true") @Schema(example = "true")
private boolean cancelRollouts; private boolean cancelRollouts;
public MgmtCancelationType getActionCancelationType() {
return actionCancelationType;
}
public void setActionCancelationType(final MgmtCancelationType actionCancelationType) {
this.actionCancelationType = actionCancelationType;
}
public boolean isCancelRollouts() {
return cancelRollouts;
}
public void setCancelRollouts(final boolean cancelRollouts) {
this.cancelRollouts = cancelRollouts;
}
} }

View File

@@ -9,6 +9,8 @@
*/ */
package org.eclipse.hawkbit.mgmt.json.model.distributionset; package org.eclipse.hawkbit.mgmt.json.model.distributionset;
import lombok.Data;
import lombok.experimental.Accessors;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMaintenanceWindowRequestBody; import org.eclipse.hawkbit.mgmt.json.model.MgmtMaintenanceWindowRequestBody;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
@@ -17,8 +19,9 @@ import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* Request Body of Target for assignment operations (ID only). * Request Body of Target for assignment operations (ID only).
*
*/ */
@Data
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtTargetAssignmentRequestBody { public class MgmtTargetAssignmentRequestBody {
@@ -32,59 +35,10 @@ public class MgmtTargetAssignmentRequestBody {
/** /**
* JsonCreator Constructor * JsonCreator Constructor
* *
* @param id * @param id Mandatory ID of the target that should be assigned
* Mandatory ID of the target that should be assigned
*/ */
@JsonCreator @JsonCreator
public MgmtTargetAssignmentRequestBody(@JsonProperty(required = true, value = "id") final String id) { public MgmtTargetAssignmentRequestBody(@JsonProperty(required = true, value = "id") final String id) {
this.id = id; this.id = id;
} }
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public MgmtActionType getType() {
return type;
}
public void setType(final MgmtActionType type) {
this.type = type;
}
public long getForcetime() {
return forcetime;
}
public void setForcetime(final long forcetime) {
this.forcetime = forcetime;
}
public Integer getWeight() {
return weight;
}
public void setWeight(final Integer weight) {
this.weight = weight;
}
public MgmtMaintenanceWindowRequestBody getMaintenanceWindow() {
return maintenanceWindow;
}
public void setMaintenanceWindow(final MgmtMaintenanceWindowRequestBody maintenanceWindow) {
this.maintenanceWindow = maintenanceWindow;
}
public Boolean isConfirmationRequired() {
return confirmationRequired;
}
public void setConfirmationRequired(final boolean confirmationRequired) {
this.confirmationRequired = confirmationRequired;
}
} }

View File

@@ -10,9 +10,9 @@
package org.eclipse.hawkbit.mgmt.json.model.distributionset; package org.eclipse.hawkbit.mgmt.json.model.distributionset;
import java.util.List; import java.util.List;
import java.util.Objects;
import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.hateoas.RepresentationModel; import org.springframework.hateoas.RepresentationModel;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@@ -22,10 +22,9 @@ import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* Response Body of Target for assignment operations. * Response Body of Target for assignment operations.
*
*
*
*/ */
@Data
@EqualsAndHashCode(callSuper = true)
@JsonInclude(Include.NON_NULL) @JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtTargetAssignmentResponseBody extends RepresentationModel<MgmtTargetAssignmentResponseBody> { public class MgmtTargetAssignmentResponseBody extends RepresentationModel<MgmtTargetAssignmentResponseBody> {
@@ -41,21 +40,6 @@ public class MgmtTargetAssignmentResponseBody extends RepresentationModel<MgmtTa
return assignedActions == null ? 0 : assignedActions.size(); return assignedActions == null ? 0 : assignedActions.size();
} }
/**
* @return the alreadyAssigned
*/
public int getAlreadyAssigned() {
return alreadyAssigned;
}
/**
* @param alreadyAssigned
* the alreadyAssigned to set
*/
public void setAlreadyAssigned(final int alreadyAssigned) {
this.alreadyAssigned = alreadyAssigned;
}
/** /**
* @return the total * @return the total
*/ */
@@ -63,31 +47,4 @@ public class MgmtTargetAssignmentResponseBody extends RepresentationModel<MgmtTa
public int getTotal() { public int getTotal() {
return getAssigned() + alreadyAssigned; return getAssigned() + alreadyAssigned;
} }
/**
* @return the assignedActions
*/
public List<MgmtActionId> getAssignedActions() {
return assignedActions;
}
/**
* @param assignedActions
* the assigned actions to set
*/
public void setAssignedActions(final List<MgmtActionId> assignedActions) {
this.assignedActions = assignedActions;
}
@Override
public boolean equals(final Object obj) {
return super.equals(obj) && this.getClass().isInstance(obj)
&& ((MgmtTargetAssignmentResponseBody) obj).getAlreadyAssigned() == alreadyAssigned
&& Objects.equals(((MgmtTargetAssignmentResponseBody) obj).getAssignedActions(), assignedActions);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), alreadyAssigned, assignedActions);
}
} }

View File

@@ -9,6 +9,7 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.mgmt.json.model.PagedList; import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.action.MgmtAction; import org.eclipse.hawkbit.mgmt.json.model.action.MgmtAction;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtActionRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtActionRestApi;
@@ -17,8 +18,6 @@ import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
@@ -26,12 +25,11 @@ import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController @RestController
@ConditionalOnProperty(name = "hawkbit.rest.MgmtActionResource.enabled", matchIfMissing = true) @ConditionalOnProperty(name = "hawkbit.rest.MgmtActionResource.enabled", matchIfMissing = true)
public class MgmtActionResource implements MgmtActionRestApi { public class MgmtActionResource implements MgmtActionRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtActionResource.class);
private final DeploymentManagement deploymentManagement; private final DeploymentManagement deploymentManagement;
MgmtActionResource(final DeploymentManagement deploymentManagement) { MgmtActionResource(final DeploymentManagement deploymentManagement) {
@@ -77,7 +75,7 @@ public class MgmtActionResource implements MgmtActionRestApi {
return MgmtRepresentationMode.fromValue(representationModeParam) return MgmtRepresentationMode.fromValue(representationModeParam)
.orElseGet(() -> { .orElseGet(() -> {
// no need for a 400, just apply a safe fallback // no need for a 400, just apply a safe fallback
LOG.warn("Received an invalid representation mode: {}", representationModeParam); log.warn("Received an invalid representation mode: {}", representationModeParam);
return MgmtRepresentationMode.COMPACT; return MgmtRepresentationMode.COMPACT;
}); });
} }

View File

@@ -18,6 +18,8 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionId; import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionId;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
@@ -38,10 +40,8 @@ import org.eclipse.hawkbit.rest.data.ResponseList;
* A mapper which maps repository model to RESTful model representation and * A mapper which maps repository model to RESTful model representation and
* back. * back.
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class MgmtDistributionSetMapper { public final class MgmtDistributionSetMapper {
private MgmtDistributionSetMapper() {
// Utility class
}
/** /**
* {@link MgmtDistributionSetRequestBodyPost}s to {@link DistributionSet}s. * {@link MgmtDistributionSetRequestBodyPost}s to {@link DistributionSet}s.
@@ -86,7 +86,7 @@ public final class MgmtDistributionSetMapper {
return entityFactory.distributionSet().create().name(dsRest.getName()).version(dsRest.getVersion()) return entityFactory.distributionSet().create().name(dsRest.getName()).version(dsRest.getVersion())
.description(dsRest.getDescription()).type(dsRest.getType()).modules(modules) .description(dsRest.getDescription()).type(dsRest.getType()).modules(modules)
.requiredMigrationStep(dsRest.isRequiredMigrationStep()); .requiredMigrationStep(dsRest.getRequiredMigrationStep());
} }
static List<MetaData> fromRequestDsMetadata(final List<MgmtMetadata> metadata, final EntityFactory entityFactory) { static List<MetaData> fromRequestDsMetadata(final List<MgmtMetadata> metadata, final EntityFactory entityFactory) {

View File

@@ -21,6 +21,7 @@ import java.util.stream.Collectors;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.validation.ValidationException; import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadataBodyPut; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadataBodyPut;
import org.eclipse.hawkbit.mgmt.json.model.PagedList; import org.eclipse.hawkbit.mgmt.json.model.PagedList;
@@ -60,8 +61,6 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.utils.TenantConfigHelper; import org.eclipse.hawkbit.utils.TenantConfigHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
@@ -76,9 +75,9 @@ import org.springframework.web.bind.annotation.RestController;
/** /**
* REST Resource handling for {@link DistributionSet} CRUD operations. * REST Resource handling for {@link DistributionSet} CRUD operations.
*/ */
@Slf4j
@RestController @RestController
public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi { public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtDistributionSetResource.class);
private final SoftwareModuleManagement softwareModuleManagement; private final SoftwareModuleManagement softwareModuleManagement;
@@ -163,7 +162,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
public ResponseEntity<List<MgmtDistributionSet>> createDistributionSets( public ResponseEntity<List<MgmtDistributionSet>> createDistributionSets(
@RequestBody final List<MgmtDistributionSetRequestBodyPost> sets) { @RequestBody final List<MgmtDistributionSetRequestBodyPost> sets) {
LOG.debug("creating {} distribution sets", sets.size()); log.debug("creating {} distribution sets", sets.size());
// set default Ds type if ds type is null // set default Ds type if ds type is null
final String defaultDsKey = systemSecurityContext final String defaultDsKey = systemSecurityContext
.runAsSystem(systemManagement.getTenantMetadata().getDefaultDsType()::getKey); .runAsSystem(systemManagement.getTenantMetadata().getDefaultDsType()::getKey);
@@ -184,7 +183,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final Collection<DistributionSet> createdDSets = distributionSetManagement final Collection<DistributionSet> createdDSets = distributionSetManagement
.create(MgmtDistributionSetMapper.dsFromRequest(sets, entityFactory)); .create(MgmtDistributionSetMapper.dsFromRequest(sets, entityFactory));
LOG.debug("{} distribution sets created, return status {}", sets.size(), HttpStatus.CREATED); log.debug("{} distribution sets created, return status {}", sets.size(), HttpStatus.CREATED);
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(createdDSets), return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(createdDSets),
HttpStatus.CREATED); HttpStatus.CREATED);
} }
@@ -202,7 +201,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final DistributionSet updated = distributionSetManagement.update(entityFactory.distributionSet() final DistributionSet updated = distributionSetManagement.update(entityFactory.distributionSet()
.update(distributionSetId).name(toUpdate.getName()).description(toUpdate.getDescription()) .update(distributionSetId).name(toUpdate.getName()).description(toUpdate.getDescription())
.version(toUpdate.getVersion()).requiredMigrationStep(toUpdate.isRequiredMigrationStep())); .version(toUpdate.getVersion()).requiredMigrationStep(toUpdate.getRequiredMigrationStep()));
final MgmtDistributionSet response = MgmtDistributionSetMapper.toResponse(updated); final MgmtDistributionSet response = MgmtDistributionSetMapper.toResponse(updated);
MgmtDistributionSetMapper.addLinks(updated, response); MgmtDistributionSetMapper.addLinks(updated, response);
@@ -299,9 +298,9 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
} }
final List<DeploymentRequest> deploymentRequests = assignments.stream().map(dsAssignment -> { final List<DeploymentRequest> deploymentRequests = assignments.stream().map(dsAssignment -> {
final boolean isConfirmationRequired = dsAssignment.isConfirmationRequired() == null final boolean isConfirmationRequired = dsAssignment.getConfirmationRequired() == null
? tenantConfigHelper.isConfirmationFlowEnabled() ? tenantConfigHelper.isConfirmationFlowEnabled()
: dsAssignment.isConfirmationRequired(); : dsAssignment.getConfirmationRequired();
return MgmtDeploymentRequestMapper.createAssignmentRequestBuilder(dsAssignment, distributionSetId) return MgmtDeploymentRequestMapper.createAssignmentRequestBuilder(dsAssignment, distributionSetId)
.setConfirmationRequired(isConfirmationRequired).build(); .setConfirmationRequired(isConfirmationRequired).build();
}).collect(Collectors.toList()); }).collect(Collectors.toList());

View File

@@ -12,6 +12,7 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.mgmt.json.model.PagedList; import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedDistributionSetRequestBody; import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedDistributionSetRequestBody;
@@ -28,8 +29,6 @@ import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
@@ -43,11 +42,10 @@ import org.springframework.web.bind.annotation.RestController;
/** /**
* REST Resource handling for {@link DistributionSetTag} CRUD operations. * REST Resource handling for {@link DistributionSetTag} CRUD operations.
*
*/ */
@Slf4j
@RestController @RestController
public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRestApi { public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtDistributionSetTagResource.class);
private final DistributionSetTagManagement distributionSetTagManagement; private final DistributionSetTagManagement distributionSetTagManagement;
@@ -105,7 +103,7 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
@Override @Override
public ResponseEntity<List<MgmtTag>> createDistributionSetTags( public ResponseEntity<List<MgmtTag>> createDistributionSetTags(
@RequestBody final List<MgmtTagRequestBodyPut> tags) { @RequestBody final List<MgmtTagRequestBodyPut> tags) {
LOG.debug("creating {} ds tags", tags.size()); log.debug("creating {} ds tags", tags.size());
final List<DistributionSetTag> createdTags = distributionSetTagManagement final List<DistributionSetTag> createdTags = distributionSetTagManagement
.create(MgmtTagMapper.mapTagFromRequest(entityFactory, tags)); .create(MgmtTagMapper.mapTagFromRequest(entityFactory, tags));
@@ -131,7 +129,7 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
@Override @Override
public ResponseEntity<Void> deleteDistributionSetTag( public ResponseEntity<Void> deleteDistributionSetTag(
@PathVariable("distributionsetTagId") final Long distributionsetTagId) { @PathVariable("distributionsetTagId") final Long distributionsetTagId) {
LOG.debug("Delete {} distribution set tag", distributionsetTagId); log.debug("Delete {} distribution set tag", distributionsetTagId);
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
distributionSetTagManagement.delete(tag.getName()); distributionSetTagManagement.delete(tag.getName());
@@ -168,7 +166,7 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
public ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignment( public ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignment(
@PathVariable("distributionsetTagId") final Long distributionsetTagId, @PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestBody final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) { @RequestBody final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
LOG.debug("Toggle distribution set assignment {} for ds tag {}", assignedDSRequestBodies.size(), log.debug("Toggle distribution set assignment {} for ds tag {}", assignedDSRequestBodies.size(),
distributionsetTagId); distributionsetTagId);
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
@@ -182,7 +180,7 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
tagAssigmentResultRest.setUnassignedDistributionSets( tagAssigmentResultRest.setUnassignedDistributionSets(
MgmtDistributionSetMapper.toResponseDistributionSets(assigmentResult.getUnassignedEntity())); MgmtDistributionSetMapper.toResponseDistributionSets(assigmentResult.getUnassignedEntity()));
LOG.debug("Toggled assignedDS {} and unassignedDS{}", assigmentResult.getAssigned(), log.debug("Toggled assignedDS {} and unassignedDS{}", assigmentResult.getAssigned(),
assigmentResult.getUnassigned()); assigmentResult.getUnassigned());
return ResponseEntity.ok(tagAssigmentResultRest); return ResponseEntity.ok(tagAssigmentResultRest);
@@ -192,10 +190,10 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
public ResponseEntity<List<MgmtDistributionSet>> assignDistributionSets( public ResponseEntity<List<MgmtDistributionSet>> assignDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId, @PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestBody final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) { @RequestBody final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
LOG.debug("Assign DistributionSet {} for ds tag {}", assignedDSRequestBodies.size(), distributionsetTagId); log.debug("Assign DistributionSet {} for ds tag {}", assignedDSRequestBodies.size(), distributionsetTagId);
final List<DistributionSet> assignedDs = this.distributionSetManagement final List<DistributionSet> assignedDs = this.distributionSetManagement
.assignTag(findDistributionSetIds(assignedDSRequestBodies), distributionsetTagId); .assignTag(findDistributionSetIds(assignedDSRequestBodies), distributionsetTagId);
LOG.debug("Assigned DistributionSet {}", assignedDs.size()); log.debug("Assigned DistributionSet {}", assignedDs.size());
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDistributionSets(assignedDs)); return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDistributionSets(assignedDs));
} }
@@ -203,7 +201,7 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
public ResponseEntity<Void> unassignDistributionSet( public ResponseEntity<Void> unassignDistributionSet(
@PathVariable("distributionsetTagId") final Long distributionsetTagId, @PathVariable("distributionsetTagId") final Long distributionsetTagId,
@PathVariable("distributionsetId") final Long distributionsetId) { @PathVariable("distributionsetId") final Long distributionsetId) {
LOG.debug("Unassign ds {} for ds tag {}", distributionsetId, distributionsetTagId); log.debug("Unassign ds {} for ds tag {}", distributionsetId, distributionsetTagId);
this.distributionSetManagement.unAssignTag(distributionsetId, distributionsetTagId); this.distributionSetManagement.unAssignTag(distributionsetId, distributionsetTagId);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }

View File

@@ -11,6 +11,7 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
import java.io.InputStream; import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository; import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
import org.eclipse.hawkbit.artifact.repository.model.AbstractDbArtifact; import org.eclipse.hawkbit.artifact.repository.model.AbstractDbArtifact;
import org.eclipse.hawkbit.cache.DownloadArtifactCache; import org.eclipse.hawkbit.cache.DownloadArtifactCache;
@@ -19,8 +20,6 @@ import org.eclipse.hawkbit.cache.DownloadType;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadRestApi;
import org.eclipse.hawkbit.rest.util.FileStreamingUtil; import org.eclipse.hawkbit.rest.util.FileStreamingUtil;
import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder; import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@@ -31,12 +30,11 @@ import org.springframework.web.context.WebApplicationContext;
/** /**
* A resource for download artifacts. * A resource for download artifacts.
*/ */
@Slf4j
@RestController @RestController
@Scope(value = WebApplicationContext.SCOPE_REQUEST) @Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class MgmtDownloadResource implements MgmtDownloadRestApi { public class MgmtDownloadResource implements MgmtDownloadRestApi {
private static final Logger LOGGER = LoggerFactory.getLogger(MgmtDownloadResource.class);
private final ArtifactRepository artifactRepository; private final ArtifactRepository artifactRepository;
private final DownloadIdCache downloadIdCache; private final DownloadIdCache downloadIdCache;
@@ -58,7 +56,7 @@ public class MgmtDownloadResource implements MgmtDownloadRestApi {
try { try {
final DownloadArtifactCache artifactCache = downloadIdCache.get(downloadId); final DownloadArtifactCache artifactCache = downloadIdCache.get(downloadId);
if (artifactCache == null) { if (artifactCache == null) {
LOGGER.warn("Download Id {} could not be found", downloadId); log.warn("Download Id {} could not be found", downloadId);
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }
@@ -69,11 +67,11 @@ public class MgmtDownloadResource implements MgmtDownloadRestApi {
? artifactRepository.getArtifactBySha1(tenant, artifactCache.getId()) ? artifactRepository.getArtifactBySha1(tenant, artifactCache.getId())
: null; : null;
} else { } else {
LOGGER.warn("Download Type {} not supported", artifactCache.getDownloadType()); log.warn("Download Type {} not supported", artifactCache.getDownloadType());
} }
if (artifact == null) { if (artifact == null) {
LOGGER.warn("Artifact with cached id {} and download type {} could not be found.", log.warn("Artifact with cached id {} and download type {} could not be found.",
artifactCache.getId(), artifactCache.getDownloadType()); artifactCache.getId(), artifactCache.getDownloadType());
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }

View File

@@ -16,6 +16,7 @@ import java.util.stream.Collectors;
import jakarta.validation.ValidationException; import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.mgmt.json.model.PagedList; import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutResponseBody; import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutResponseBody;
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutRestRequestBody; import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutRestRequestBody;
@@ -44,8 +45,6 @@ import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.utils.TenantConfigHelper; import org.eclipse.hawkbit.utils.TenantConfigHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
@@ -58,13 +57,11 @@ import org.springframework.web.bind.annotation.RestController;
/** /**
* REST Resource handling rollout CRUD operations. * REST Resource handling rollout CRUD operations.
*
*/ */
@Slf4j
@RestController @RestController
public class MgmtRolloutResource implements MgmtRolloutRestApi { public class MgmtRolloutResource implements MgmtRolloutRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtRolloutResource.class);
private final RolloutManagement rolloutManagement; private final RolloutManagement rolloutManagement;
private final RolloutGroupManagement rolloutGroupManagement; private final RolloutGroupManagement rolloutGroupManagement;
@@ -336,7 +333,7 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
private static MgmtRepresentationMode parseRepresentationMode(final String representationModeParam) { private static MgmtRepresentationMode parseRepresentationMode(final String representationModeParam) {
return MgmtRepresentationMode.fromValue(representationModeParam).orElseGet(() -> { return MgmtRepresentationMode.fromValue(representationModeParam).orElseGet(() -> {
// no need for a 400, just apply a safe fallback // no need for a 400, just apply a safe fallback
LOG.warn("Received an invalid representation mode: {}", representationModeParam); log.warn("Received an invalid representation mode: {}", representationModeParam);
return MgmtRepresentationMode.COMPACT; return MgmtRepresentationMode.COMPACT;
}); });
} }

View File

@@ -18,6 +18,7 @@ import java.util.Optional;
import jakarta.validation.ValidationException; import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.api.ArtifactUrlHandler; import org.eclipse.hawkbit.api.ArtifactUrlHandler;
import org.eclipse.hawkbit.mgmt.json.model.PagedList; import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
@@ -42,8 +43,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.rest.data.ResponseList; import org.eclipse.hawkbit.rest.data.ResponseList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
@@ -62,21 +61,15 @@ import org.springframework.web.multipart.MultipartFile;
* REST Resource handling for {@link SoftwareModule} and related * REST Resource handling for {@link SoftwareModule} and related
* {@link Artifact} CRUD operations. * {@link Artifact} CRUD operations.
*/ */
@Slf4j
@RestController @RestController
public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi { public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtSoftwareModuleResource.class);
private final ArtifactManagement artifactManagement; private final ArtifactManagement artifactManagement;
private final SoftwareModuleManagement softwareModuleManagement; private final SoftwareModuleManagement softwareModuleManagement;
private final SoftwareModuleTypeManagement softwareModuleTypeManagement; private final SoftwareModuleTypeManagement softwareModuleTypeManagement;
private final ArtifactUrlHandler artifactUrlHandler; private final ArtifactUrlHandler artifactUrlHandler;
private final SystemManagement systemManagement; private final SystemManagement systemManagement;
private final EntityFactory entityFactory; private final EntityFactory entityFactory;
MgmtSoftwareModuleResource(final ArtifactManagement artifactManagement, final SoftwareModuleManagement softwareModuleManagement, MgmtSoftwareModuleResource(final ArtifactManagement artifactManagement, final SoftwareModuleManagement softwareModuleManagement,
@@ -118,7 +111,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
return ResponseEntity.status(HttpStatus.CREATED).body(reponse); return ResponseEntity.status(HttpStatus.CREATED).body(reponse);
} catch (final IOException e) { } catch (final IOException e) {
LOG.error("Failed to store artifact", e); log.error("Failed to store artifact", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@@ -146,7 +139,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
private static MgmtRepresentationMode parseRepresentationMode(final String representationModeParam) { private static MgmtRepresentationMode parseRepresentationMode(final String representationModeParam) {
return MgmtRepresentationMode.fromValue(representationModeParam).orElseGet(() -> { return MgmtRepresentationMode.fromValue(representationModeParam).orElseGet(() -> {
// no need for a 400, just apply a safe fallback // no need for a 400, just apply a safe fallback
LOG.warn("Received an invalid representation mode: {}", representationModeParam); log.warn("Received an invalid representation mode: {}", representationModeParam);
return MgmtRepresentationMode.COMPACT; return MgmtRepresentationMode.COMPACT;
}); });
} }
@@ -229,7 +222,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity<List<MgmtSoftwareModule>> createSoftwareModules( public ResponseEntity<List<MgmtSoftwareModule>> createSoftwareModules(
@RequestBody final List<MgmtSoftwareModuleRequestBodyPost> softwareModules) { @RequestBody final List<MgmtSoftwareModuleRequestBodyPost> softwareModules) {
LOG.debug("creating {} softwareModules", softwareModules.size()); log.debug("creating {} softwareModules", softwareModules.size());
for (final MgmtSoftwareModuleRequestBodyPost sm : softwareModules) { for (final MgmtSoftwareModuleRequestBodyPost sm : softwareModules) {
final Optional<SoftwareModuleType> opt = softwareModuleTypeManagement.getByKey(sm.getType()); final Optional<SoftwareModuleType> opt = softwareModuleTypeManagement.getByKey(sm.getType());
@@ -243,7 +236,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
} }
final Collection<SoftwareModule> createdSoftwareModules = softwareModuleManagement final Collection<SoftwareModule> createdSoftwareModules = softwareModuleManagement
.create(MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules)); .create(MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules));
LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED); log.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED);
return ResponseEntity.status(HttpStatus.CREATED) return ResponseEntity.status(HttpStatus.CREATED)
.body(MgmtSoftwareModuleMapper.toResponse(createdSoftwareModules)); .body(MgmtSoftwareModuleMapper.toResponse(createdSoftwareModules));

View File

@@ -14,6 +14,7 @@ import java.util.Collections;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemCache; import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemCache;
import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemStatisticsRest; import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemStatisticsRest;
@@ -22,8 +23,6 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtSystemManagementRestApi;
import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.report.model.SystemUsageReportWithTenants; import org.eclipse.hawkbit.repository.report.model.SystemUsageReportWithTenants;
import org.eclipse.hawkbit.repository.report.model.TenantUsage; import org.eclipse.hawkbit.repository.report.model.TenantUsage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@@ -32,13 +31,11 @@ import org.springframework.web.bind.annotation.RestController;
/** /**
* {@link SystemManagement} capabilities by REST. * {@link SystemManagement} capabilities by REST.
*
*/ */
@Slf4j
@RestController @RestController
public class MgmtSystemManagementResource implements MgmtSystemManagementRestApi { public class MgmtSystemManagementResource implements MgmtSystemManagementRestApi {
private static final Logger LOGGER = LoggerFactory.getLogger(MgmtSystemManagementResource.class);
private final SystemManagement systemManagement; private final SystemManagement systemManagement;
private final CacheManager cacheManager; private final CacheManager cacheManager;
@@ -120,7 +117,7 @@ public class MgmtSystemManagementResource implements MgmtSystemManagementRestApi
@Override @Override
public ResponseEntity<Collection<String>> invalidateCaches() { public ResponseEntity<Collection<String>> invalidateCaches() {
final Collection<String> cacheNames = cacheManager.getCacheNames(); final Collection<String> cacheNames = cacheManager.getCacheNames();
LOGGER.info("Invalidating caches {}", cacheNames); log.info("Invalidating caches {}", cacheNames);
cacheNames.forEach(cacheName -> cacheManager.getCache(cacheName).clear()); cacheNames.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
return ResponseEntity.ok(cacheNames); return ResponseEntity.ok(cacheNames);
} }

View File

@@ -11,6 +11,7 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.List; import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.mgmt.json.model.PagedList; import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtDistributionSetAutoAssignment; import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtDistributionSetAutoAssignment;
@@ -29,8 +30,6 @@ import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.utils.TenantConfigHelper; import org.eclipse.hawkbit.utils.TenantConfigHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
@@ -45,9 +44,9 @@ import org.springframework.web.bind.annotation.RestController;
/** /**
* REST Resource handling target CRUD operations. * REST Resource handling target CRUD operations.
*/ */
@Slf4j
@RestController @RestController
public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestApi { public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetFilterQueryResource.class);
private final TargetFilterQueryManagement filterManagement; private final TargetFilterQueryManagement filterManagement;
@@ -122,7 +121,7 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
@Override @Override
public ResponseEntity<MgmtTargetFilterQuery> updateFilter(@PathVariable("filterId") final Long filterId, public ResponseEntity<MgmtTargetFilterQuery> updateFilter(@PathVariable("filterId") final Long filterId,
@RequestBody final MgmtTargetFilterQueryRequestBody targetFilterRest) { @RequestBody final MgmtTargetFilterQueryRequestBody targetFilterRest) {
LOG.debug("updating target filter query {}", filterId); log.debug("updating target filter query {}", filterId);
final TargetFilterQuery updateFilter = filterManagement final TargetFilterQuery updateFilter = filterManagement
.update(entityFactory.targetFilterQuery().update(filterId).name(targetFilterRest.getName()) .update(entityFactory.targetFilterQuery().update(filterId).name(targetFilterRest.getName())
@@ -138,7 +137,7 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
@Override @Override
public ResponseEntity<Void> deleteFilter(@PathVariable("filterId") final Long filterId) { public ResponseEntity<Void> deleteFilter(@PathVariable("filterId") final Long filterId) {
filterManagement.delete(filterId); filterManagement.delete(filterId);
LOG.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK); log.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }
@@ -194,7 +193,7 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
private static MgmtRepresentationMode parseRepresentationMode(final String representationModeParam) { private static MgmtRepresentationMode parseRepresentationMode(final String representationModeParam) {
return MgmtRepresentationMode.fromValue(representationModeParam).orElseGet(() -> { return MgmtRepresentationMode.fromValue(representationModeParam).orElseGet(() -> {
// no need for a 400, just apply a safe fallback // no need for a 400, just apply a safe fallback
LOG.warn("Received an invalid representation mode: {}", representationModeParam); log.warn("Received an invalid representation mode: {}", representationModeParam);
return MgmtRepresentationMode.COMPACT; return MgmtRepresentationMode.COMPACT;
}); });
} }

View File

@@ -20,6 +20,7 @@ import java.util.stream.Collectors;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.validation.ValidationException; import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.mgmt.json.model.MgmtId; import org.eclipse.hawkbit.mgmt.json.model.MgmtId;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadataBodyPut; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadataBodyPut;
@@ -53,8 +54,6 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetMetadata; import org.eclipse.hawkbit.repository.model.TargetMetadata;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.utils.TenantConfigHelper; import org.eclipse.hawkbit.utils.TenantConfigHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
@@ -69,11 +68,11 @@ import org.springframework.web.bind.annotation.RestController;
/** /**
* REST Resource handling target CRUD operations. * REST Resource handling target CRUD operations.
*/ */
@Slf4j
@RestController @RestController
public class MgmtTargetResource implements MgmtTargetRestApi { public class MgmtTargetResource implements MgmtTargetRestApi {
private static final String ACTION_TARGET_MISSING_ASSIGN_WARN = "given action ({}) is not assigned to given target ({}).";
private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetResource.class); private static final String ACTION_TARGET_MISSING_ASSIGN_WARN = "given action ({}) is not assigned to given target ({}).";
private final TargetManagement targetManagement; private final TargetManagement targetManagement;
@@ -135,10 +134,10 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
@Override @Override
public ResponseEntity<List<MgmtTarget>> createTargets(@RequestBody final List<MgmtTargetRequestBody> targets) { public ResponseEntity<List<MgmtTarget>> createTargets(@RequestBody final List<MgmtTargetRequestBody> targets) {
LOG.debug("creating {} targets", targets.size()); log.debug("creating {} targets", targets.size());
final Collection<Target> createdTargets = this.targetManagement final Collection<Target> createdTargets = this.targetManagement
.create(MgmtTargetMapper.fromRequest(entityFactory, targets)); .create(MgmtTargetMapper.fromRequest(entityFactory, targets));
LOG.debug("{} targets created, return status {}", targets.size(), HttpStatus.CREATED); log.debug("{} targets created, return status {}", targets.size(), HttpStatus.CREATED);
return new ResponseEntity<>(MgmtTargetMapper.toResponse(createdTargets, tenantConfigHelper), return new ResponseEntity<>(MgmtTargetMapper.toResponse(createdTargets, tenantConfigHelper),
HttpStatus.CREATED); HttpStatus.CREATED);
} }
@@ -183,7 +182,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
@Override @Override
public ResponseEntity<Void> deleteTarget(@PathVariable("targetId") final String targetId) { public ResponseEntity<Void> deleteTarget(@PathVariable("targetId") final String targetId) {
this.targetManagement.deleteByControllerID(targetId); this.targetManagement.deleteByControllerID(targetId);
LOG.debug("{} target deleted, return status {}", targetId, HttpStatus.OK); log.debug("{} target deleted, return status {}", targetId, HttpStatus.OK);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }
@@ -248,7 +247,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final Action action = deploymentManagement.findAction(actionId) final Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(targetId)) { if (!action.getTarget().getControllerId().equals(targetId)) {
LOG.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), targetId); log.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), targetId);
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }
@@ -263,7 +262,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(targetId)) { if (!action.getTarget().getControllerId().equals(targetId)) {
LOG.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, actionId, targetId); log.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, actionId, targetId);
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }
@@ -291,7 +290,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getId().equals(target.getId())) { if (!action.getTarget().getId().equals(target.getId())) {
LOG.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), target.getId()); log.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), target.getId());
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }
@@ -382,7 +381,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
Action action = deploymentManagement.findAction(actionId) Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(targetId)) { if (!action.getTarget().getControllerId().equals(targetId)) {
LOG.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), targetId); log.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), targetId);
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }

View File

@@ -12,6 +12,7 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.mgmt.json.model.PagedList; import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedTargetRequestBody; import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedTargetRequestBody;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag; import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag;
@@ -31,8 +32,6 @@ import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.utils.TenantConfigHelper; import org.eclipse.hawkbit.utils.TenantConfigHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
@@ -45,11 +44,10 @@ import org.springframework.web.bind.annotation.RestController;
/** /**
* REST Resource handling for tag CRUD operations. * REST Resource handling for tag CRUD operations.
*
*/ */
@Slf4j
@RestController @RestController
public class MgmtTargetTagResource implements MgmtTargetTagRestApi { public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetTagResource.class);
private final TargetTagManagement tagManagement; private final TargetTagManagement tagManagement;
@@ -105,7 +103,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
@Override @Override
public ResponseEntity<List<MgmtTag>> createTargetTags(@RequestBody final List<MgmtTagRequestBodyPut> tags) { public ResponseEntity<List<MgmtTag>> createTargetTags(@RequestBody final List<MgmtTagRequestBodyPut> tags) {
LOG.debug("creating {} target tags", tags.size()); log.debug("creating {} target tags", tags.size());
final List<TargetTag> createdTargetTags = this.tagManagement final List<TargetTag> createdTargetTags = this.tagManagement
.create(MgmtTagMapper.mapTagFromRequest(entityFactory, tags)); .create(MgmtTagMapper.mapTagFromRequest(entityFactory, tags));
return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED); return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED);
@@ -114,13 +112,13 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
@Override @Override
public ResponseEntity<MgmtTag> updateTargetTag(@PathVariable("targetTagId") final Long targetTagId, public ResponseEntity<MgmtTag> updateTargetTag(@PathVariable("targetTagId") final Long targetTagId,
@RequestBody final MgmtTagRequestBodyPut restTargetTagRest) { @RequestBody final MgmtTagRequestBodyPut restTargetTagRest) {
LOG.debug("update {} target tag", restTargetTagRest); log.debug("update {} target tag", restTargetTagRest);
final TargetTag updateTargetTag = tagManagement final TargetTag updateTargetTag = tagManagement
.update(entityFactory.tag().update(targetTagId).name(restTargetTagRest.getName()) .update(entityFactory.tag().update(targetTagId).name(restTargetTagRest.getName())
.description(restTargetTagRest.getDescription()).colour(restTargetTagRest.getColour())); .description(restTargetTagRest.getDescription()).colour(restTargetTagRest.getColour()));
LOG.debug("target tag updated"); log.debug("target tag updated");
final MgmtTag response = MgmtTagMapper.toResponse(updateTargetTag); final MgmtTag response = MgmtTagMapper.toResponse(updateTargetTag);
MgmtTagMapper.addLinks(updateTargetTag, response); MgmtTagMapper.addLinks(updateTargetTag, response);
@@ -130,7 +128,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
@Override @Override
public ResponseEntity<Void> deleteTargetTag(@PathVariable("targetTagId") final Long targetTagId) { public ResponseEntity<Void> deleteTargetTag(@PathVariable("targetTagId") final Long targetTagId) {
LOG.debug("Delete {} target tag", targetTagId); log.debug("Delete {} target tag", targetTagId);
final TargetTag targetTag = findTargetTagById(targetTagId); final TargetTag targetTag = findTargetTagById(targetTagId);
this.tagManagement.delete(targetTag.getName()); this.tagManagement.delete(targetTag.getName());
@@ -165,7 +163,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
public ResponseEntity<MgmtTargetTagAssigmentResult> toggleTagAssignment( public ResponseEntity<MgmtTargetTagAssigmentResult> toggleTagAssignment(
@PathVariable("targetTagId") final Long targetTagId, @PathVariable("targetTagId") final Long targetTagId,
@RequestBody final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) { @RequestBody final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
LOG.debug("Toggle Target assignment {} for target tag {}", assignedTargetRequestBodies.size(), targetTagId); log.debug("Toggle Target assignment {} for target tag {}", assignedTargetRequestBodies.size(), targetTagId);
final TargetTag targetTag = findTargetTagById(targetTagId); final TargetTag targetTag = findTargetTagById(targetTagId);
final TargetTagAssignmentResult assigmentResult = this.targetManagement final TargetTagAssignmentResult assigmentResult = this.targetManagement
@@ -182,7 +180,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
@Override @Override
public ResponseEntity<List<MgmtTarget>> assignTargets(@PathVariable("targetTagId") final Long targetTagId, public ResponseEntity<List<MgmtTarget>> assignTargets(@PathVariable("targetTagId") final Long targetTagId,
@RequestBody final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) { @RequestBody final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
LOG.debug("Assign Targets {} for target tag {}", assignedTargetRequestBodies.size(), targetTagId); log.debug("Assign Targets {} for target tag {}", assignedTargetRequestBodies.size(), targetTagId);
final List<Target> assignedTarget = this.targetManagement final List<Target> assignedTarget = this.targetManagement
.assignTag(findTargetControllerIds(assignedTargetRequestBodies), targetTagId); .assignTag(findTargetControllerIds(assignedTargetRequestBodies), targetTagId);
return ResponseEntity.ok(MgmtTargetMapper.toResponse(assignedTarget, tenantConfigHelper)); return ResponseEntity.ok(MgmtTargetMapper.toResponse(assignedTarget, tenantConfigHelper));
@@ -191,7 +189,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
@Override @Override
public ResponseEntity<Void> unassignTarget(@PathVariable("targetTagId") final Long targetTagId, public ResponseEntity<Void> unassignTarget(@PathVariable("targetTagId") final Long targetTagId,
@PathVariable("controllerId") final String controllerId) { @PathVariable("controllerId") final String controllerId) {
LOG.debug("Unassign target {} for target tag {}", controllerId, targetTagId); log.debug("Unassign target {} for target tag {}", controllerId, targetTagId);
this.targetManagement.unassignTag(controllerId, targetTagId); this.targetManagement.unassignTag(controllerId, targetTagId);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }

View File

@@ -12,6 +12,7 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.mgmt.json.model.PagedList; import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType; import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeAssignment; import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeAssignment;
@@ -25,8 +26,6 @@ import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.TargetTypeManagement; import org.eclipse.hawkbit.repository.TargetTypeManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.TargetType; import org.eclipse.hawkbit.repository.model.TargetType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
@@ -41,9 +40,9 @@ import org.springframework.web.bind.annotation.RestController;
/** /**
* REST Resource handling for {@link TargetType} CRUD operations. * REST Resource handling for {@link TargetType} CRUD operations.
*/ */
@Slf4j
@RestController @RestController
public class MgmtTargetTypeResource implements MgmtTargetTypeRestApi { public class MgmtTargetTypeResource implements MgmtTargetTypeRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetTypeResource.class);
private final TargetTypeManagement targetTypeManagement; private final TargetTypeManagement targetTypeManagement;
private final EntityFactory entityFactory; private final EntityFactory entityFactory;
@@ -89,7 +88,7 @@ public class MgmtTargetTypeResource implements MgmtTargetTypeRestApi {
@Override @Override
public ResponseEntity<Void> deleteTargetType(@PathVariable("targetTypeId") final Long targetTypeId) { public ResponseEntity<Void> deleteTargetType(@PathVariable("targetTypeId") final Long targetTypeId) {
LOG.debug("Delete {} target type", targetTypeId); log.debug("Delete {} target type", targetTypeId);
targetTypeManagement.delete(targetTypeId); targetTypeManagement.delete(targetTypeId);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }

View File

@@ -15,6 +15,7 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValue; import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValue;
import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValueRequest; import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValueRequest;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTenantManagementRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtTenantManagementRestApi;
@@ -23,8 +24,6 @@ import org.eclipse.hawkbit.repository.TenantConfigurationManagement;
import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; import org.eclipse.hawkbit.repository.model.TenantConfigurationValue;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties;
import org.eclipse.hawkbit.tenancy.configuration.validator.TenantConfigurationValidatorException; import org.eclipse.hawkbit.tenancy.configuration.validator.TenantConfigurationValidatorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@@ -34,11 +33,10 @@ import org.springframework.web.bind.annotation.RestController;
/** /**
* REST Resource for handling tenant specific configuration operations. * REST Resource for handling tenant specific configuration operations.
*/ */
@Slf4j
@RestController @RestController
public class MgmtTenantManagementResource implements MgmtTenantManagementRestApi { public class MgmtTenantManagementResource implements MgmtTenantManagementRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtTenantManagementResource.class);
private final TenantConfigurationManagement tenantConfigurationManagement; private final TenantConfigurationManagement tenantConfigurationManagement;
private final TenantConfigurationProperties tenantConfigurationProperties; private final TenantConfigurationProperties tenantConfigurationProperties;
private final SystemManagement systemManagement; private final SystemManagement systemManagement;
@@ -61,7 +59,7 @@ public class MgmtTenantManagementResource implements MgmtTenantManagementRestApi
MgmtSystemTenantConfigurationValue defaultDsTypeId = loadTenantConfigurationValueBy(MgmtTenantManagementMapper.DEFAULT_DISTRIBUTION_SET_TYPE_KEY); MgmtSystemTenantConfigurationValue defaultDsTypeId = loadTenantConfigurationValueBy(MgmtTenantManagementMapper.DEFAULT_DISTRIBUTION_SET_TYPE_KEY);
tenantConfigurationValueMap.put(MgmtTenantManagementMapper.DEFAULT_DISTRIBUTION_SET_TYPE_KEY, defaultDsTypeId); tenantConfigurationValueMap.put(MgmtTenantManagementMapper.DEFAULT_DISTRIBUTION_SET_TYPE_KEY, defaultDsTypeId);
//return combined TenantConfiguration and TenantMetadata //return combined TenantConfiguration and TenantMetadata
LOG.debug("getTenantConfiguration, return status {}", HttpStatus.OK); log.debug("getTenantConfiguration, return status {}", HttpStatus.OK);
return ResponseEntity.ok(tenantConfigurationValueMap); return ResponseEntity.ok(tenantConfigurationValueMap);
} }
@@ -93,7 +91,7 @@ public class MgmtTenantManagementResource implements MgmtTenantManagementRestApi
tenantConfigurationManagement.deleteConfiguration(keyName); tenantConfigurationManagement.deleteConfiguration(keyName);
LOG.debug("{} config value deleted, return status {}", keyName, HttpStatus.OK); log.debug("{} config value deleted, return status {}", keyName, HttpStatus.OK);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }

View File

@@ -18,13 +18,12 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException; import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo; import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.FileStreamingFailedException; import org.eclipse.hawkbit.rest.util.FileStreamingFailedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotReadableException;
@@ -37,10 +36,10 @@ import org.springframework.web.multipart.MultipartException;
/** /**
* General controller advice for exception handling. * General controller advice for exception handling.
*/ */
@Slf4j
@ControllerAdvice @ControllerAdvice
public class ResponseExceptionHandler { public class ResponseExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(ResponseExceptionHandler.class);
private static final Map<SpServerError, HttpStatus> ERROR_TO_HTTP_STATUS = new EnumMap<>(SpServerError.class); private static final Map<SpServerError, HttpStatus> ERROR_TO_HTTP_STATUS = new EnumMap<>(SpServerError.class);
private static final HttpStatus DEFAULT_RESPONSE_STATUS = HttpStatus.INTERNAL_SERVER_ERROR; private static final HttpStatus DEFAULT_RESPONSE_STATUS = HttpStatus.INTERNAL_SERVER_ERROR;
@@ -145,7 +144,7 @@ public class ResponseExceptionHandler {
public ResponseEntity<Object> handleFileStreamingFailedException(final HttpServletRequest request, public ResponseEntity<Object> handleFileStreamingFailedException(final HttpServletRequest request,
final Exception ex) { final Exception ex) {
logRequest(request, ex); logRequest(request, ex);
LOG.warn("File streaming failed: {}", ex.getMessage()); log.warn("File streaming failed: {}", ex.getMessage());
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} }
@@ -248,7 +247,7 @@ public class ResponseExceptionHandler {
final Throwable responseCause = throwables.get(throwables.size() - 1); final Throwable responseCause = throwables.get(throwables.size() - 1);
if (responseCause.getMessage().isEmpty()) { if (responseCause.getMessage().isEmpty()) {
LOG.warn("Request {} lead to MultipartException without root cause message:\n{}", request.getRequestURL(), log.warn("Request {} lead to MultipartException without root cause message:\n{}", request.getRequestURL(),
ex.getStackTrace()); ex.getStackTrace());
} }
@@ -257,7 +256,7 @@ public class ResponseExceptionHandler {
} }
private void logRequest(final HttpServletRequest request, final Exception ex) { private void logRequest(final HttpServletRequest request, final Exception ex) {
LOG.debug("Handling exception {} of request {}", ex.getClass().getName(), request.getRequestURL()); log.debug("Handling exception {} of request {}", ex.getClass().getName(), request.getRequestURL());
} }
private ExceptionInfo createExceptionInfo(final Exception ex) { private ExceptionInfo createExceptionInfo(final Exception ex) {

View File

@@ -24,10 +24,11 @@ import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@@ -36,21 +37,16 @@ import org.springframework.http.ResponseEntity;
/** /**
* Utility class for artifact file streaming. * Utility class for artifact file streaming.
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public final class FileStreamingUtil { public final class FileStreamingUtil {
private static final Logger LOG = LoggerFactory.getLogger(FileStreamingUtil.class);
/** /**
* File suffix for MDH hash download (see Linux md5sum). * File suffix for MDH hash download (see Linux md5sum).
*/ */
public static final String ARTIFACT_MD5_DWNL_SUFFIX = ".MD5SUM"; public static final String ARTIFACT_MD5_DWNL_SUFFIX = ".MD5SUM";
private static final int BUFFER_SIZE = 0x2000; // 8k private static final int BUFFER_SIZE = 0x2000; // 8k
private FileStreamingUtil() {
}
/** /**
* Write a md5 file response. * Write a md5 file response.
* *
@@ -150,12 +146,12 @@ public final class FileStreamingUtil {
// Validate and process Range and If-Range headers. // Validate and process Range and If-Range headers.
final String range = request.getHeader("Range"); final String range = request.getHeader("Range");
if (lastModified > 0 && range != null) { if (lastModified > 0 && range != null) {
LOG.debug("range header for filename ({}) is: {}", filename, range); log.debug("range header for filename ({}) is: {}", filename, range);
// Range header matches"bytes=n-n,n-n,n-n..." // Range header matches"bytes=n-n,n-n,n-n..."
if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*+$")) { if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*+$")) {
response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length); response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length);
LOG.debug("range header for filename ({}) is not satisfiable: ", filename); log.debug("range header for filename ({}) is not satisfiable: ", filename);
return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
} }
@@ -174,17 +170,17 @@ public final class FileStreamingUtil {
// full request - no range // full request - no range
if (ranges.isEmpty() || ranges.get(0).equals(full)) { if (ranges.isEmpty() || ranges.get(0).equals(full)) {
LOG.debug("filename ({}) results into a full request: ", filename); log.debug("filename ({}) results into a full request: ", filename);
result = handleFullFileRequest(artifact, filename, response, progressListener, full); result = handleFullFileRequest(artifact, filename, response, progressListener, full);
} }
// standard range request // standard range request
else if (ranges.size() == 1) { else if (ranges.size() == 1) {
LOG.debug("filename ({}) results into a standard range request: ", filename); log.debug("filename ({}) results into a standard range request: ", filename);
result = handleStandardRangeRequest(artifact, filename, response, progressListener, ranges); result = handleStandardRangeRequest(artifact, filename, response, progressListener, ranges);
} }
// multipart range request // multipart range request
else { else {
LOG.debug("filename ({}) results into a multipart range request: ", filename); log.debug("filename ({}) results into a multipart range request: ", filename);
result = handleMultipartRangeRequest(artifact, filename, response, progressListener, ranges); result = handleMultipartRangeRequest(artifact, filename, response, progressListener, ranges);
} }
@@ -266,7 +262,7 @@ public final class FileStreamingUtil {
ranges.add(full); ranges.add(full);
} }
} catch (final IllegalArgumentException ignore) { } catch (final IllegalArgumentException ignore) {
LOG.info("Invalid if-range header field", ignore); log.info("Invalid if-range header field", ignore);
ranges.add(full); ranges.add(full);
} }
} }
@@ -318,7 +314,7 @@ public final class FileStreamingUtil {
final ServletOutputStream to = response.getOutputStream(); final ServletOutputStream to = response.getOutputStream();
copyStreams(from, to, progressListener, r.getStart(), r.getLength(), filename); copyStreams(from, to, progressListener, r.getStart(), r.getLength(), filename);
} catch (final IOException e) { } catch (final IOException e) {
LOG.error("standardRangeRequest of file ({}) failed!", filename, e); log.error("standardRangeRequest of file ({}) failed!", filename, e);
throw new FileStreamingFailedException(filename); throw new FileStreamingFailedException(filename);
} }
@@ -330,7 +326,7 @@ public final class FileStreamingUtil {
final String filename) throws IOException { final String filename) throws IOException {
final long startMillis = System.currentTimeMillis(); final long startMillis = System.currentTimeMillis();
LOG.trace("Start of copy-streams of file {} from {} to {}", filename, start, length); log.trace("Start of copy-streams of file {} from {} to {}", filename, start, length);
Objects.requireNonNull(from); Objects.requireNonNull(from);
Objects.requireNonNull(to); Objects.requireNonNull(to);
@@ -381,7 +377,7 @@ public final class FileStreamingUtil {
+ " bytes could not be written to client, total time on write: !" + totalTime + " ms"); + " bytes could not be written to client, total time on write: !" + totalTime + " ms");
} }
LOG.trace("Finished copy-stream of file {} with length {} in {} ms", filename, length, totalTime); log.trace("Finished copy-stream of file {} with length {} in {} ms", filename, length, totalTime);
return total; return total;
} }

View File

@@ -9,18 +9,17 @@
*/ */
package org.eclipse.hawkbit.rest.util; package org.eclipse.hawkbit.rest.util;
import org.slf4j.Logger; import lombok.AccessLevel;
import org.slf4j.LoggerFactory; import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler; import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.result.PrintingResultHandler; import org.springframework.test.web.servlet.result.PrintingResultHandler;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public abstract class MockMvcResultPrinter { public abstract class MockMvcResultPrinter {
private static final Logger LOG = LoggerFactory.getLogger(MockMvcResultPrinter.class);
private MockMvcResultPrinter() {
}
/** /**
* Print {@link MvcResult} details to logger. * Print {@link MvcResult} details to logger.
@@ -39,7 +38,7 @@ public abstract class MockMvcResultPrinter {
@Override @Override
public void printHeading(final String heading) { public void printHeading(final String heading) {
LOG.debug(String.format("%20s:", heading)); log.debug(String.format("%20s:", heading));
} }
@Override @Override
@@ -49,7 +48,7 @@ public abstract class MockMvcResultPrinter {
if (value != null && value.getClass().isArray()) { if (value != null && value.getClass().isArray()) {
value = CollectionUtils.arrayToList(value); value = CollectionUtils.arrayToList(value);
} }
LOG.debug(String.format("%20s = %s", label, value)); log.debug(String.format("%20s = %s", label, value));
} }
}); });
} }