@org.springframework.stereotype.Component()

Here are the examples of the java api @org.springframework.stereotype.Component() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

35 Examples 7

19 Source : DemoSmsCodeGenerator.java
with MIT License
from ZeroOrInfinity

/**
 * 推荐实现此接口 {@link SmsCodeSender}。
 * @author YongWu zheng
 * @version V1.0  Created by 2020-05-14 22:23
 */
@Component()
@Slf4j
public clreplaced DemoSmsCodeGenerator extends SmsCodeGenerator {

    public DemoSmsCodeGenerator(SmsCodeSender smsCodeSender, ValidateCodeProperties validateCodeProperties) {
        super(validateCodeProperties, smsCodeSender);
    }

    @Override
    public ValidateCode generate(ServletRequest request) {
        ValidateCode validateCode = smsCodeSender.getCode();
        if (log.isDebugEnabled()) {
            log.debug("Demo =======>: {} = {}", this.validateCodeProperties.getSms().getRequestParamSmsCodeName(), validateCode.getCode());
        }
        return validateCode;
    }
}

19 Source : DemoImageCodeGenerator.java
with MIT License
from ZeroOrInfinity

/**
 * 推荐实现此接口 {@link ImageCodeFactory}。
 * @author YongWu zheng
 * @version V1.0  Created by  2020-05-14 22:24
 */
@Component()
@Slf4j
public clreplaced DemoImageCodeGenerator extends ImageCodeGenerator {

    public DemoImageCodeGenerator(ImageCodeFactory imageCodeFactory, ValidateCodeProperties validateCodeProperties) {
        super(validateCodeProperties, imageCodeFactory);
    }

    @Override
    public ImageCode generate(ServletRequest request) {
        ImageCode imageCode = imageCodeFactory.getImageCode(request);
        if (log.isDebugEnabled()) {
            log.debug("Demo =====>: {} = {}", this.validateCodeProperties.getImage().getRequestParamImageCodeName(), imageCode.getCode());
        }
        return imageCode;
    }
}

19 Source : RestProcessor.java
with Apache License 2.0
from tmobile

@Component()
public clreplaced RestProcessor {

    private static Logger log = LogManager.getLogger(RestProcessor.clreplaced);

    @Value("${vault.api.url}")
    private String vaultApiUrl;

    @Value("${vault.ssl.verify:true}")
    private boolean sslVerify;

    public RestProcessor() {
    }

    public ResponseEnreplacedy<String> post(String endpoint, String token, String payload) {
        RestTemplate restTemplate = getRestTemplate(sslVerify, token);
        String _endpoint = formURL(endpoint);
        ResponseEnreplacedy<String> response;
        log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder().put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()).put(LogMessage.ACTION, "Invoke Vault API").put(LogMessage.MESSAGE, String.format("Calling the vault end point [%s] using POST method", _endpoint)).put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()).build()));
        try {
            response = restTemplate.postForEnreplacedy(_endpoint, payload, String.clreplaced);
        } catch (HttpStatusCodeException e) {
            return ResponseEnreplacedy.status(e.getStatusCode()).body(e.getResponseBodyreplacedtring());
        } catch (RestClientException e) {
            return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
        return response;
    }

    public ResponseEnreplacedy<String> get(String endpoint, String token) {
        String _endpoint = formURL(endpoint);
        RestTemplate restTemplate = getRestTemplate(sslVerify, token);
        log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder().put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()).put(LogMessage.ACTION, "Invoke Vault API").put(LogMessage.MESSAGE, String.format("Calling the vault end point [%s] using GET method", _endpoint)).put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()).build()));
        ResponseEnreplacedy<String> response;
        try {
            response = restTemplate.getForEnreplacedy(_endpoint, String.clreplaced);
        } catch (HttpStatusCodeException e) {
            return ResponseEnreplacedy.status(e.getStatusCode()).body(e.getResponseBodyreplacedtring());
        } catch (RestClientException e) {
            return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
        return response;
    }

    public ResponseEnreplacedy<String> delete(String endpoint, String token) {
        String _endpoint = formURL(endpoint);
        RestTemplate restTemplate = getRestTemplate(sslVerify, token);
        ResponseEnreplacedy<String> response = null;
        log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder().put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()).put(LogMessage.ACTION, "Invoke Vault API").put(LogMessage.MESSAGE, String.format("Calling the vault end point [%s] using DELETE method", _endpoint)).put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()).build()));
        try {
            // restTemplate.delete(vaultApiUrl+endpoint);
            response = restTemplate.exchange(_endpoint, HttpMethod.DELETE, null, String.clreplaced);
        } catch (HttpStatusCodeException e) {
            return ResponseEnreplacedy.status(e.getStatusCode()).body(e.getResponseBodyreplacedtring());
        } catch (RestClientException e) {
            return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        return response;
    }

    private static RestTemplate getRestTemplate(boolean sslVerify, String token) {
        HttpClient httpClient = null;
        try {
            if (!sslVerify)
                httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).setRedirectStrategy(new LaxRedirectStrategy()).build();
            else
                httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e1) {
            // TODO Auto-generated catch block
            log.debug(e1.getMessage());
        }
        RestTemplate restTemplate = new RestTemplate();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        restTemplate.setRequestFactory(factory);
        HttpRequestInterceptor interceptor = new HttpRequestInterceptor(token);
        restTemplate.getInterceptors().add(interceptor);
        return restTemplate;
    }

    private String formURL(String endpoint) {
        String _endpoint;
        if (endpoint.startsWith("http")) {
            _endpoint = endpoint;
        } else {
            _endpoint = vaultApiUrl + endpoint;
        }
        return _endpoint;
    }
}

19 Source : CertRestProcessor.java
with Apache License 2.0
from tmobile

@Component()
public clreplaced CertRestProcessor {

    private static Logger log = LogManager.getLogger(CertRestProcessor.clreplaced);

    @Value("${vault.ssl.verify:true}")
    private boolean sslVerify;

    public CertRestProcessor() {
    }

    /**
     * Perform the post rest call
     * @param endpoint
     * @param token
     * @param payload
     * @return
     */
    public ResponseEnreplacedy<String> post(String endpoint, String token, Object payload) {
        RestTemplate restTemplate = getRestTemplate(sslVerify, token);
        ResponseEnreplacedy<String> response;
        log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder().put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()).put(LogMessage.ACTION, "Invoke Vault API").put(LogMessage.MESSAGE, String.format("Calling the Cert end point [%s] using POST method", endpoint)).put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()).build()));
        try {
            response = restTemplate.postForEnreplacedy(endpoint, payload, String.clreplaced);
        } catch (HttpStatusCodeException e) {
            return ResponseEnreplacedy.status(e.getStatusCode()).body(e.getResponseBodyreplacedtring());
        } catch (RestClientException e) {
            return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
        return response;
    }

    /**
     * Put the Post rest call
     * @param endpoint
     * @param token
     * @param payload
     * @return
     */
    public ResponseEnreplacedy<String> put(String endpoint, String token, Object payload) {
        RestTemplate restTemplate = getRestTemplate(sslVerify, token);
        ResponseEnreplacedy<String> response;
        log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder().put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()).put(LogMessage.ACTION, "Invoke Vault API").put(LogMessage.MESSAGE, String.format("Calling the Cert end point [%s] using POST method", endpoint)).put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()).build()));
        try {
            response = restTemplate.exchange(endpoint, HttpMethod.PUT, new HttpEnreplacedy<>(payload), String.clreplaced);
        } catch (HttpStatusCodeException e) {
            return ResponseEnreplacedy.status(e.getStatusCode()).body(e.getResponseBodyreplacedtring());
        } catch (RestClientException e) {
            return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
        return response;
    }

    /**
     * Peform the Get Rest Call
     * @param endpoint
     * @param token
     * @return
     */
    public ResponseEnreplacedy<String> get(String endpoint, String token) {
        RestTemplate restTemplate = getRestTemplate(sslVerify, token);
        log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder().put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()).put(LogMessage.ACTION, "Invoke Vault API").put(LogMessage.MESSAGE, String.format("Calling the Cert end point [%s] using GET method", endpoint)).put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()).build()));
        ResponseEnreplacedy<String> response;
        try {
            response = restTemplate.getForEnreplacedy(endpoint, String.clreplaced);
        } catch (HttpStatusCodeException e) {
            return ResponseEnreplacedy.status(e.getStatusCode()).body(e.getResponseBodyreplacedtring());
        } catch (RestClientException e) {
            return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
        return response;
    }

    /**
     * Perform the delete rest call
     * @param endpoint
     * @param token
     * @return
     */
    public ResponseEnreplacedy<String> delete(String endpoint, String token) {
        RestTemplate restTemplate = getRestTemplate(sslVerify, token);
        ResponseEnreplacedy<String> response = null;
        log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder().put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()).put(LogMessage.ACTION, "Invoke Vault API").put(LogMessage.MESSAGE, String.format("Calling the Cert end point [%s] using DELETE method", endpoint)).put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()).build()));
        try {
            response = restTemplate.exchange(endpoint, HttpMethod.DELETE, null, String.clreplaced);
        } catch (HttpStatusCodeException e) {
            return ResponseEnreplacedy.status(e.getStatusCode()).body(e.getResponseBodyreplacedtring());
        } catch (RestClientException e) {
            return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        return response;
    }

    /**
     * Perform the delete rest call with request body
     * @param endpoint
     * @param token
     * @return
     */
    public ResponseEnreplacedy<String> deleteWithPayload(String endpoint, String token, Object payload) {
        RestTemplate restTemplate = getRestTemplate(sslVerify, token);
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-HTTP-Method-Override", "DELETE");
        HttpEnreplacedy<String> request = new HttpEnreplacedy<String>(payload.toString(), headers);
        ResponseEnreplacedy<String> response;
        log.debug(JSONUtil.getJSON(ImmutableMap.<String, String>builder().put(LogMessage.USER, ThreadLocalContext.getCurrentMap().get(LogMessage.USER).toString()).put(LogMessage.ACTION, "Invoke Vault API").put(LogMessage.MESSAGE, String.format("Calling the Cert end point [%s] using DELETE method", endpoint)).put(LogMessage.APIURL, ThreadLocalContext.getCurrentMap().get(LogMessage.APIURL).toString()).build()));
        try {
            response = restTemplate.exchange(endpoint, HttpMethod.DELETE, request, String.clreplaced);
        } catch (HttpStatusCodeException e) {
            return ResponseEnreplacedy.status(e.getStatusCode()).body(e.getResponseBodyreplacedtring());
        } catch (RestClientException e) {
            return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
        return response;
    }

    /**
     * Get the rest template
     * @param sslVerify
     * @param token
     * @return
     */
    private static RestTemplate getRestTemplate(boolean sslVerify, String token) {
        HttpClient httpClient = null;
        try {
            if (!sslVerify)
                httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).setRedirectStrategy(new LaxRedirectStrategy()).build();
            else
                httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e1) {
            log.debug(e1.getMessage());
        }
        RestTemplate restTemplate = new RestTemplate();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        restTemplate.setRequestFactory(factory);
        HttpCertRequestInterceptor interceptor = new HttpCertRequestInterceptor(token);
        restTemplate.getInterceptors().add(interceptor);
        return restTemplate;
    }
}

19 Source : UnpublishHandler.java
with Apache License 2.0
from syndesisio

@Qualifier("s2i")
@Component()
@ConditionalOnProperty(value = "controllers.integration", havingValue = "s2i", matchIfMissing = true)
public clreplaced UnpublishHandler extends BaseOnlineHandler implements StateChangeHandler {

    private static final Logger LOG = LoggerFactory.getLogger(UnpublishHandler.clreplaced);

    public UnpublishHandler(OpenShiftService openShiftService, IntegrationDao iDao, IntegrationDeploymentDao idDao, IntegrationPublishValidator validator) {
        super(openShiftService, iDao, idDao, validator);
    }

    @Override
    public Set<IntegrationDeploymentState> getTriggerStates() {
        return Collections.singleton(IntegrationDeploymentState.Unpublished);
    }

    @Override
    public StateUpdate execute(IntegrationDeployment integrationDeployment) {
        Map<String, String> stepsDone = new HashMap<>(integrationDeployment.getStepsDone());
        // we are literally undoing this step.
        stepsDone.remove("deploy");
        IntegrationDeploymentState currentState = IntegrationDeploymentState.Pending;
        Map<String, String> labels = new HashMap<>();
        labels.put(OpenShiftService.INTEGRATION_ID_LABEL, Labels.validate(integrationDeployment.getIntegrationId().get()));
        labels.put(OpenShiftService.DEPLOYMENT_VERSION_LABEL, String.valueOf(integrationDeployment.getVersion()));
        List<DeploymentConfig> deployments = getOpenShiftService().getDeploymentsByLabel(labels);
        Boolean isDeployed = !deployments.stream().filter(d -> d.getSpec().getReplicas() != 0).collect(Collectors.toList()).isEmpty();
        if (isDeployed) {
            try {
                LOG.info("Undeploying integration deployment:{} version:{}", integrationDeployment.getSpec().getName(), integrationDeployment.getVersion());
                getOpenShiftService().scale(integrationDeployment.getSpec().getName(), labels, 0, 1, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return new StateUpdate(currentState, stepsDone);
            }
        }
        Boolean isUndeployed = !deployments.stream().filter(d -> d.getStatus().getAvailableReplicas() == 0).collect(Collectors.toList()).isEmpty();
        if (isUndeployed) {
            currentState = IntegrationDeploymentState.Unpublished;
        }
        return new StateUpdate(currentState, stepsDone);
    }
}

19 Source : PublishHandler.java
with Apache License 2.0
from syndesisio

@Qualifier("s2i")
@Component()
@ConditionalOnProperty(value = "controllers.integration", havingValue = "s2i", matchIfMissing = true)
public clreplaced PublishHandler extends BaseOnlineHandler implements StateChangeHandler {

    private final IntegrationProjectGenerator projectGenerator;

    private final List<DeploymentDataCustomizer> customizers;

    PublishHandler(OpenShiftService openShiftService, IntegrationDao iDao, IntegrationDeploymentDao idDao, IntegrationProjectGenerator projectGenerator, List<DeploymentDataCustomizer> customizers, IntegrationPublishValidator validator) {
        super(openShiftService, iDao, idDao, validator);
        this.projectGenerator = projectGenerator;
        this.customizers = customizers;
    }

    @Override
    public Set<IntegrationDeploymentState> getTriggerStates() {
        return Collections.singleton(IntegrationDeploymentState.Published);
    }

    @Override
    public StateUpdate execute(final IntegrationDeployment integrationDeployment) {
        StateUpdate updateViaValidation = getValidator().validate(integrationDeployment);
        if (updateViaValidation != null) {
            return updateViaValidation;
        }
        logInfo(integrationDeployment, "Build started: {}, isRunning: {}, Deployment ready: {}", isBuildStarted(integrationDeployment), isRunning(integrationDeployment), isReady(integrationDeployment));
        BuildStepOncePerformer stepOncePerformer = new BuildStepOncePerformer(integrationDeployment);
        logInfo(integrationDeployment, "Steps performed so far: " + stepOncePerformer.getStepsPerformed());
        if (hasError(integrationDeployment) || isBuildFailed(integrationDeployment)) {
            logError(integrationDeployment, "[ERROR] Build is in failed state");
            return new StateUpdate(IntegrationDeploymentState.Error, stepOncePerformer.getStepsPerformed(), "Error", integrationDeployment.getError());
        }
        final Integration integration = integrationOf(integrationDeployment);
        try {
            setVersion(integrationDeployment);
            deactivatePreviousDeployments(integrationDeployment);
            DeploymentData deploymentData = createDeploymentData(integration, integrationDeployment);
            String buildLabel = "buildv" + deploymentData.getVersion();
            stepOncePerformer.perform(buildLabel, this::build, deploymentData);
            if (stepOncePerformer.hasError()) {
                logError(integrationDeployment, "[ERROR] Build failed with {} - {}", stepOncePerformer.getError().getType(), stepOncePerformer.getError().getMessage());
                return new StateUpdate(IntegrationDeploymentState.Error, stepOncePerformer.getStepsPerformed(), "Error", stepOncePerformer.getError());
            }
            if (hasPublishedDeployments(integrationDeployment)) {
                return new StateUpdate(IntegrationDeploymentState.Unpublished, integrationDeployment.getStepsDone(), "Integration has still active deployments. Will retry shortly");
            }
            deploymentData = new DeploymentData.Builder().createFrom(deploymentData).withImage(stepOncePerformer.stepsPerformed.get(buildLabel)).build();
            stepOncePerformer.perform("deploy", this::deploy, deploymentData);
        } catch (Exception e) {
            logError(integrationDeployment, "[ERROR] Activation failure", e);
            // Setting a message to update means implicitly that the deployment is in an error state (for the UI)
            return new StateUpdate(IntegrationDeploymentState.Pending, stepOncePerformer.getStepsPerformed(), e.getMessage());
        }
        // Set status to activate if finally running. Also clears the previous step which has been performed
        if (isRunning(integrationDeployment)) {
            logInfo(integrationDeployment, "[ACTIVATED] bc. integration is running with 1 pod");
            updateDeploymentState(integrationDeployment, IntegrationDeploymentState.Published);
            return new StateUpdate(IntegrationDeploymentState.Published, stepOncePerformer.getStepsPerformed());
        }
        logInfo(integrationDeployment, "Build started: {}, isRunning: {}, Deployment ready: {}", isBuildStarted(integrationDeployment), isRunning(integrationDeployment), isReady(integrationDeployment));
        logInfo(integrationDeployment, "[PENDING] [" + stepOncePerformer.getStepsPerformed() + "]");
        return new StateUpdate(IntegrationDeploymentState.Pending, stepOncePerformer.getStepsPerformed());
    }

    private DeploymentData createDeploymentData(Integration integration, IntegrationDeployment integrationDeployment) {
        Properties applicationProperties = projectGenerator.generateApplicationProperties(integration);
        String username = integrationDeployment.getUserId().orElseThrow(() -> new IllegalStateException("Couldn't find the user of the integration"));
        String integrationId = integrationDeployment.getIntegrationId().orElseThrow(() -> new IllegalStateException("IntegrationDeployment should have an integrationId"));
        String version = Integer.toString(integrationDeployment.getVersion());
        final DeploymentData.Builder deploymentDataBuilder = DeploymentData.builder().withVersion(integrationDeployment.getVersion()).addLabel(OpenShiftService.INTEGRATION_ID_LABEL, Labels.validate(integrationId)).addLabel(OpenShiftService.DEPLOYMENT_VERSION_LABEL, version).addLabel(OpenShiftService.USERNAME_LABEL, Labels.sanitize(username)).addAnnotation(OpenShiftService.INTEGRATION_NAME_ANNOTATION, integration.getName()).addAnnotation(OpenShiftService.INTEGRATION_ID_LABEL, integrationId).addAnnotation(OpenShiftService.DEPLOYMENT_VERSION_LABEL, version).addSecretEntry("application.properties", propsToString(applicationProperties));
        integration.getConfiguredProperties().forEach((k, v) -> deploymentDataBuilder.addProperty(k, v));
        DeploymentData data = deploymentDataBuilder.build();
        if (this.customizers != null && !this.customizers.isEmpty()) {
            for (DeploymentDataCustomizer customizer : customizers) {
                data = customizer.customize(data, integrationDeployment);
            }
        }
        return data;
    }

    // =============================================================================
    // Various steps to perform:
    private String build(IntegrationDeployment integration, DeploymentData data, IntegrationErrorHandler errorHandler) {
        InputStream tarInputStream = createProjectFiles(integration.getSpec(), errorHandler);
        logInfo(integration, "Created project files and starting build");
        try {
            return getOpenShiftService().build(integration.getSpec().getName(), data, tarInputStream);
        } catch (InterruptedException e) {
            throw SyndesisServerException.launderThrowable(e);
        }
    }

    private String deploy(IntegrationDeployment integration, DeploymentData data) {
        logInfo(integration, "Starting deployment");
        String revision = getOpenShiftService().deploy(integration.getSpec().getName(), data);
        logInfo(integration, "Deployment done");
        return revision;
    }

    // =================================================================================
    private boolean hasError(IntegrationDeployment integrationDeployment) {
        return integrationDeployment.getCurrentState() == IntegrationDeploymentState.Error || integrationDeployment.hasError() || getIntegrationDeploymentDao().hasError(integrationDeployment.getId().get());
    }

    private boolean isBuildStarted(IntegrationDeployment integrationDeployment) {
        return getOpenShiftService().isBuildStarted(integrationDeployment.getSpec().getName());
    }

    private boolean isBuildFailed(IntegrationDeployment integrationDeployment) {
        return getOpenShiftService().isBuildFailed(integrationDeployment.getSpec().getName());
    }

    private boolean isReady(IntegrationDeployment integrationDeployment) {
        return getOpenShiftService().isDeploymentReady(integrationDeployment.getSpec().getName());
    }

    private static String propsToString(Properties data) {
        if (data == null) {
            return "";
        }
        try {
            StringWriter w = new StringWriter();
            data.store(w, "");
            return w.toString();
        } catch (IOException e) {
            throw SyndesisServerException.launderThrowable(e);
        }
    }

    private static Integration integrationOf(IntegrationDeployment integrationDeployment) {
        return integrationDeployment.getSpec();
    }

    /**
     * Check if Integration has active deployments.
     * @param deployment The specified {@link IntegrationDeployment}.
     * @return  The true if there are, false otherwise.
     */
    private boolean hasPublishedDeployments(IntegrationDeployment deployment) {
        Integration integration = deployment.getSpec();
        String id = Labels.validate(integration.getId().orElseThrow(() -> new IllegalStateException("Couldn't find the id of the integration")));
        String version = String.valueOf(integration.getVersion());
        Map<String, String> labels = new HashMap<>();
        labels.put(OpenShiftService.INTEGRATION_ID_LABEL, id);
        return (int) getOpenShiftService().getDeploymentsByLabel(labels).stream().filter(d -> !version.equals(d.getMetadata().getLabels().get(OpenShiftService.DEPLOYMENT_VERSION_LABEL))).filter(d -> d.getSpec().getReplicas() > 0).count() > 0;
    }

    private InputStream createProjectFiles(Integration integration, IntegrationErrorHandler errorHandler) {
        try {
            return projectGenerator.generate(integration, errorHandler);
        } catch (IOException e) {
            throw SyndesisServerException.launderThrowable(e);
        }
    }

    // ===============================================================================
    // Some helper method to conditional execute certain steps
    @FunctionalInterface
    public interface IoCheckedFunction<T> {

        String apply(T t, DeploymentData data);
    }

    @FunctionalInterface
    public interface IoCheckedErrorHandlingFunction<T> {

        String apply(T t, DeploymentData data, IntegrationErrorHandler errorHandler);
    }

    private clreplaced BuildStepOncePerformer {

        private final Map<String, String> stepsPerformed;

        private final IntegrationDeployment integrationDeployment;

        private IntegrationDeploymentError error;

        BuildStepOncePerformer(IntegrationDeployment integrationDeployment) {
            this.integrationDeployment = integrationDeployment;
            this.stepsPerformed = new HashMap<>(integrationDeployment.getStepsDone());
        }

        void perform(String step, IoCheckedFunction<IntegrationDeployment> callable, DeploymentData data) {
            if (!stepsPerformed.containsKey(step)) {
                stepsPerformed.put(step, callable.apply(integrationDeployment, data));
            } else {
                logInfo(integrationDeployment, "Skipped step {} because already performed", step);
            }
        }

        void perform(String step, IoCheckedErrorHandlingFunction<IntegrationDeployment> callable, DeploymentData data) {
            if (!stepsPerformed.containsKey(step)) {
                stepsPerformed.put(step, callable.apply(integrationDeployment, data, (throwable) -> {
                    logError(integrationDeployment, "Error for step {}: {} {}", step, throwable.getClreplaced().getName(), Optional.ofNullable(throwable.getMessage()).orElse(""));
                    error = new IntegrationDeploymentError.Builder().type(throwable.getClreplaced().getName()).message(throwable.getMessage()).build();
                }));
            } else {
                logInfo(integrationDeployment, "Skipped step {} because already performed", step);
            }
        }

        boolean hasError() {
            return error != null;
        }

        IntegrationDeploymentError getError() {
            return error;
        }

        Map<String, String> getStepsPerformed() {
            return stepsPerformed;
        }
    }
}

19 Source : Checker.java
with MIT License
from PacktPublishing

@Component()
@RequestScope
public clreplaced Checker {

    private static final Logger log = LoggerFactory.getLogger(Checker.clreplaced);

    private final Collection<ConsistencyChecker> checkers;

    private final ProductInformationCollector piCollector;

    private final ProductsCheckerCollector pcCollector;

    private final CheckerScriptExecutor executor;

    public Checker(@Autowired Collection<ConsistencyChecker> checkers, @Autowired ProductInformationCollector piCollector, @Autowired ProductsCheckerCollector pcCollector, @Autowired CheckerScriptExecutor executor) {
        java.util.concurrent.Flow.Processor<Object, Object> processor;
        this.checkers = checkers;
        this.piCollector = piCollector;
        this.pcCollector = pcCollector;
        this.executor = executor;
    }

    /**
     * Check that amn order is consistent calling all consistency checkers that are relevant for the order.
     *
     * @param order
     * @return true if the order is consistent by all checkers
     */
    public boolean isConsistent(Order order) {
        final Map<OrderItem, ProductInformation> map = piCollector.collectProductInformation(order);
        if (map == null) {
            return false;
        }
        final Set<Clreplaced<? extends Annotation>> annotations = pcCollector.getProductAnnotations(order);
        Predicate<Annotation> annotationIsNeeded = annotation -> annotations.contains(annotation.annotationType());
        Predicate<ConsistencyChecker> productIsConsistent = checker -> Arrays.stream(checker.getClreplaced().getAnnotations()).parallel().unordered().filter(annotationIsNeeded).anyMatch(x -> checker.isInconsistent(order));
        final boolean checkersSayConsistent = !checkers.stream().anyMatch(productIsConsistent);
        final boolean scriptsSayConsistent = !map.values().parallelStream().map(ProductInformation::getCheckScript).filter(Objects::nonNull).anyMatch(s -> executor.notConsistent(s, order));
        return checkersSayConsistent && scriptsSayConsistent;
    }
}

19 Source : SetEncryptionKeyExchangeOnGMeterCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced SetEncryptionKeyExchangeOnGMeterCommandExecutor extends AbstractCommandExecutor<GMeterInfoDto, MethodResultCode> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SetEncryptionKeyExchangeOnGMeterCommandExecutor.clreplaced);

    private static final int CLreplaced_ID = 72;

    private static final ObisCode OBIS_CODE_INTERVAL_MBUS_1 = new ObisCode("0.1.24.1.0.255");

    private static final ObisCode OBIS_CODE_INTERVAL_MBUS_2 = new ObisCode("0.2.24.1.0.255");

    private static final ObisCode OBIS_CODE_INTERVAL_MBUS_3 = new ObisCode("0.3.24.1.0.255");

    private static final ObisCode OBIS_CODE_INTERVAL_MBUS_4 = new ObisCode("0.4.24.1.0.255");

    private static final Map<Integer, ObisCode> OBIS_HASHMAP = new HashMap<>();

    static {
        OBIS_HASHMAP.put(1, OBIS_CODE_INTERVAL_MBUS_1);
        OBIS_HASHMAP.put(2, OBIS_CODE_INTERVAL_MBUS_2);
        OBIS_HASHMAP.put(3, OBIS_CODE_INTERVAL_MBUS_3);
        OBIS_HASHMAP.put(4, OBIS_CODE_INTERVAL_MBUS_4);
    }

    @Autowired
    private SecretManagementService secretManagementService;

    @Autowired
    private DlmsDeviceRepository dlmsDeviceRepository;

    public SetEncryptionKeyExchangeOnGMeterCommandExecutor() {
        super(GMeterInfoDto.clreplaced);
    }

    @Override
    public ActionResponseDto asBundleResponse(final MethodResultCode executionResult) throws ProtocolAdapterException {
        this.checkMethodResultCode(executionResult);
        return new ActionResponseDto("M-Bus User key exchange on Gas meter was successful");
    }

    @Override
    public MethodResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final GMeterInfoDto gMeterInfo) throws ProtocolAdapterException {
        try {
            LOGGER.debug("SetEncryptionKeyExchangeOnGMeterCommandExecutor.execute called");
            final String mbusDeviceIdentification = gMeterInfo.getDeviceIdentification();
            final int channel = gMeterInfo.getChannel();
            final ObisCode obisCode = OBIS_HASHMAP.get(channel);
            final byte[] gMeterEncryptionKey = this.secretManagementService.generate128BitsKeyAndStoreAsNewKey(mbusDeviceIdentification, G_METER_ENCRYPTION);
            MethodResult methodResultCode = this.transferKey(conn, mbusDeviceIdentification, channel, gMeterEncryptionKey);
            this.checkMethodResultCode(methodResultCode, "M-Bus Setup transfer_key", obisCode);
            methodResultCode = this.setEncryptionKey(conn, channel, gMeterEncryptionKey);
            this.checkMethodResultCode(methodResultCode, "M-Bus Setup set_encryption_key", obisCode);
            this.secretManagementService.activateNewKey(mbusDeviceIdentification, G_METER_ENCRYPTION);
            return MethodResultCode.SUCCESS;
        } catch (final IOException e) {
            throw new ConnectionException(e);
        } catch (final EncrypterException e) {
            throw new ProtocolAdapterException("Unexpected exception during decryption of security keys, reason = " + e.getMessage(), e);
        }
    }

    private MethodResult setEncryptionKey(final DlmsConnectionManager conn, final int channel, final byte[] encryptionKey) throws IOException {
        final MethodParameter methodSetEncryptionKey = this.getSetEncryptionKeyMethodParameter(OBIS_HASHMAP.get(channel), encryptionKey);
        conn.getDlmsMessageListener().setDescription("SetEncryptionKeyExchangeOnGMeter for channel " + channel + ", call M-Bus Setup set_encryption_key method: " + JdlmsObjectToStringUtil.describeMethod(methodSetEncryptionKey));
        return conn.getConnection().action(methodSetEncryptionKey);
    }

    private MethodResult transferKey(final DlmsConnectionManager conn, final String mbusDeviceIdentification, final int channel, final byte[] encryptionKey) throws ProtocolAdapterException, IOException {
        final MethodParameter methodTransferKey = this.getTransferKeyMethodParameter(mbusDeviceIdentification, channel, encryptionKey);
        conn.getDlmsMessageListener().setDescription("SetEncryptionKeyExchangeOnGMeter for channel " + channel + ", call M-Bus Setup transfer_key method: " + JdlmsObjectToStringUtil.describeMethod(methodTransferKey));
        return conn.getConnection().action(methodTransferKey);
    }

    private MethodParameter getTransferKeyMethodParameter(final String mbusDeviceIdentification, final int channel, final byte[] gMeterUserKey) throws ProtocolAdapterException {
        final DlmsDevice mbusDevice = this.dlmsDeviceRepository.findByDeviceIdentification(mbusDeviceIdentification);
        if (mbusDevice == null) {
            throw new ProtocolAdapterException("Unknown M-Bus device: " + mbusDeviceIdentification);
        }
        final byte[] mbusDefaultKey = this.secretManagementService.getKey(mbusDeviceIdentification, G_METER_MASTER);
        final byte[] encryptedUserKey = this.encryptMbusUserKey(mbusDefaultKey, gMeterUserKey);
        final DataObject methodParameter = DataObject.newOctetStringData(encryptedUserKey);
        final MBusClientMethod method = MBusClientMethod.TRANSFER_KEY;
        return new MethodParameter(method.getInterfaceClreplaced().id(), OBIS_HASHMAP.get(channel), method.getMethodId(), methodParameter);
    }

    private void checkMethodResultCode(final MethodResult methodResultCode, final String methodParameterName, final ObisCode obisCode) throws ProtocolAdapterException {
        if (methodResultCode == null || !MethodResultCode.SUCCESS.equals(methodResultCode.getResultCode())) {
            String message = "Error while executing " + methodParameterName + ".";
            if (methodResultCode != null) {
                message += " Reason = " + methodResultCode.getResultCode();
            }
            throw new ProtocolAdapterException(message);
        } else {
            LOGGER.info("Successfully invoked '{}' method: clreplaced_id {} obis_code {}", methodParameterName, CLreplaced_ID, obisCode);
        }
    }

    private MethodParameter getSetEncryptionKeyMethodParameter(final ObisCode obisCode, final byte[] encryptionKey) {
        final DataObject methodParameter = DataObject.newOctetStringData(encryptionKey);
        final MBusClientMethod method = MBusClientMethod.SET_ENCRYPTION_KEY;
        return new MethodParameter(method.getInterfaceClreplaced().id(), obisCode, method.getMethodId(), methodParameter);
    }

    /**
     * Encrypts a new M-Bus User key with the M-Bus Default key for use as M-Bus
     * Client Setup transfer_key parameter.
     * <p>
     * Note that the specifics of the encryption of the M-Bus User key depend on
     * the M-Bus version the devices support. This method should be appropriate
     * for use with DSMR 4 M-Bus devices.
     * <p>
     * The encryption is performed by applying an AES/CBC/NoPadding cipher
     * initialized for encryption with the given mbusDefaultKey and an
     * initialization vector of 16 zero-bytes to the given mbusUserKey.
     *
     * @return the properly wrapped User key for a DSMR 4 M-Bus User key change.
     */
    private byte[] encryptMbusUserKey(final byte[] mbusDefaultKey, final byte[] mbusUserKey) throws ProtocolAdapterException {
        final Key secretkeySpec = new SecretKeySpec(mbusDefaultKey, "AES");
        try {
            final Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            final IvParameterSpec params = new IvParameterSpec(new byte[16]);
            cipher.init(Cipher.ENCRYPT_MODE, secretkeySpec, params);
            return cipher.doFinal(mbusUserKey);
        } catch (final NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
            final String message = "Error encrypting M-Bus User key with M-Bus Default key for transfer.";
            LOGGER.error(message, e);
            throw new ProtocolAdapterException(message);
        }
    }
}

19 Source : SetPushSetupSmsCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced SetPushSetupSmsCommandExecutor extends SetPushSetupCommandExecutor<PushSetupSmsDto, AccessResultCode> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SetPushSetupSmsCommandExecutor.clreplaced);

    private static final ObisCode OBIS_CODE = new ObisCode("0.2.25.9.0.255");

    public SetPushSetupSmsCommandExecutor() {
        super(SetPushSetupSmsRequestDto.clreplaced);
    }

    @Override
    public PushSetupSmsDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        final SetPushSetupSmsRequestDto setPushSetupSmsRequestDto = (SetPushSetupSmsRequestDto) bundleInput;
        return setPushSetupSmsRequestDto.getPushSetupSms();
    }

    @Override
    public ActionResponseDto asBundleResponse(final AccessResultCode executionResult) throws ProtocolAdapterException {
        this.checkAccessResultCode(executionResult);
        return new ActionResponseDto("Setting push setup SMS was successful");
    }

    @Override
    public AccessResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final PushSetupSmsDto pushSetupSms) throws ProtocolAdapterException {
        final SetParameter setParameterSendDestinationAndMethod = this.getSetParameter(pushSetupSms);
        final AccessResultCode resultCode = this.getAccessResultSetSendDestinationAndMethod("PushSetupSms", conn, OBIS_CODE, setParameterSendDestinationAndMethod);
        if (resultCode != null) {
            return resultCode;
        } else {
            throw new ProtocolAdapterException("Error setting Sms push setup data.");
        }
    }

    private SetParameter getSetParameter(final PushSetupSmsDto pushSetupSms) throws ProtocolAdapterException {
        this.checkPushSetupSms(pushSetupSms);
        final AttributeAddress sendDestinationAndMethodAddress = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_SEND_DESTINATION_AND_METHOD);
        final DataObject value = this.buildSendDestinationAndMethodObject(pushSetupSms.getSendDestinationAndMethod());
        return new SetParameter(sendDestinationAndMethodAddress, value);
    }

    private void checkPushSetupSms(final PushSetupSmsDto pushSetupSms) throws ProtocolAdapterException {
        if (!pushSetupSms.hreplacedendDestinationAndMethod()) {
            LOGGER.error("Send Destination and Method of the Push Setup Sms is expected to be set.");
            throw new ProtocolAdapterException("Error setting Sms push setup data. No destination and method data");
        }
        if (pushSetupSms.hasPushObjectList()) {
            LOGGER.warn("Setting Push Object List of Push Setup Sms not implemented: {}", pushSetupSms.getPushObjectList());
        }
        if (pushSetupSms.hasCommunicationWindow()) {
            LOGGER.warn("Setting Communication Window of Push Setup Sms not implemented: {}", pushSetupSms.getCommunicationWindow());
        }
        if (pushSetupSms.hasRandomisationStartInterval()) {
            LOGGER.warn("Setting Randomisation Start Interval of Push Setup Sms not implemented: {}", pushSetupSms.getRandomisationStartInterval());
        }
        if (pushSetupSms.hasNumberOfRetries()) {
            LOGGER.warn("Setting Number of Retries of Push Setup Sms not implemented: {}", pushSetupSms.getNumberOfRetries());
        }
        if (pushSetupSms.hasRepereplacedionDelay()) {
            LOGGER.warn("Setting Repereplacedion Delay of Push Setup Sms not implemented: {}", pushSetupSms.getRepereplacedionDelay());
        }
    }
}

19 Source : SetPushSetupAlarmCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced SetPushSetupAlarmCommandExecutor extends SetPushSetupCommandExecutor<PushSetupAlarmDto, AccessResultCode> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SetPushSetupAlarmCommandExecutor.clreplaced);

    private static final ObisCode OBIS_CODE = new ObisCode("0.1.25.9.0.255");

    public SetPushSetupAlarmCommandExecutor() {
        super(SetPushSetupAlarmRequestDto.clreplaced);
    }

    @Override
    public PushSetupAlarmDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        final SetPushSetupAlarmRequestDto setPushSetupAlarmRequestDto = (SetPushSetupAlarmRequestDto) bundleInput;
        return setPushSetupAlarmRequestDto.getPushSetupAlarm();
    }

    @Override
    public ActionResponseDto asBundleResponse(final AccessResultCode executionResult) throws ProtocolAdapterException {
        this.checkAccessResultCode(executionResult);
        return new ActionResponseDto("Setting push setup alarm was successful");
    }

    @Override
    public AccessResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final PushSetupAlarmDto pushSetupAlarm) throws ProtocolAdapterException {
        final SetParameter setParameterSendDestinationAndMethod = this.getSetParameter(pushSetupAlarm);
        final AccessResultCode resultCode = this.getAccessResultSetSendDestinationAndMethod("PushSetupAlarm", conn, OBIS_CODE, setParameterSendDestinationAndMethod);
        if (resultCode != null) {
            return resultCode;
        } else {
            throw new ProtocolAdapterException("Error setting Alarm push setup data.");
        }
    }

    private SetParameter getSetParameter(final PushSetupAlarmDto pushSetupAlarm) throws ProtocolAdapterException {
        this.checkPushSetupAlarm(pushSetupAlarm);
        final AttributeAddress sendDestinationAndMethodAddress = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_SEND_DESTINATION_AND_METHOD);
        final DataObject value = this.buildSendDestinationAndMethodObject(pushSetupAlarm.getSendDestinationAndMethod());
        return new SetParameter(sendDestinationAndMethodAddress, value);
    }

    private void checkPushSetupAlarm(final PushSetupAlarmDto pushSetupAlarm) throws ProtocolAdapterException {
        if (!pushSetupAlarm.hreplacedendDestinationAndMethod()) {
            LOGGER.error("Send Destination and Method of the Push Setup Alarm is expected to be set.");
            throw new ProtocolAdapterException("Error setting Alarm push setup data. No destination and method data");
        }
        if (pushSetupAlarm.hasPushObjectList()) {
            LOGGER.warn("Setting Push Object List of Push Setup Alarm not implemented: {}", pushSetupAlarm.getPushObjectList());
        }
        if (pushSetupAlarm.hasCommunicationWindow()) {
            LOGGER.warn("Setting Communication Window of Push Setup Alarm not implemented: {}", pushSetupAlarm.getCommunicationWindow());
        }
        if (pushSetupAlarm.hasRandomisationStartInterval()) {
            LOGGER.warn("Setting Randomisation Start Interval of Push Setup Alarm not implemented: {}", pushSetupAlarm.getRandomisationStartInterval());
        }
        if (pushSetupAlarm.hasNumberOfRetries()) {
            LOGGER.warn("Setting Number of Retries of Push Setup Alarm not implemented: {}", pushSetupAlarm.getNumberOfRetries());
        }
        if (pushSetupAlarm.hasRepereplacedionDelay()) {
            LOGGER.warn("Setting Repereplacedion Delay of Push Setup Alarm not implemented: {}", pushSetupAlarm.getRepereplacedionDelay());
        }
    }
}

19 Source : GetPushSetupSmsCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced GetPushSetupSmsCommandExecutor extends GetPushSetupCommandExecutor<Void, PushSetupSmsDto> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetPushSetupSmsCommandExecutor.clreplaced);

    private static final ObisCode OBIS_CODE = new ObisCode("0.2.25.9.0.255");

    private static final AttributeAddress[] ATTRIBUTE_ADDRESSES = new AttributeAddress[6];

    static {
        ATTRIBUTE_ADDRESSES[0] = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_PUSH_OBJECT_LIST);
        ATTRIBUTE_ADDRESSES[1] = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_SEND_DESTINATION_AND_METHOD);
        ATTRIBUTE_ADDRESSES[2] = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_COMMUNICATION_WINDOW);
        ATTRIBUTE_ADDRESSES[3] = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_RANDOMISATION_START_INTERVAL);
        ATTRIBUTE_ADDRESSES[4] = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_NUMBER_OF_RETRIES);
        ATTRIBUTE_ADDRESSES[5] = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_REPEreplacedION_DELAY);
    }

    @Autowired
    private DlmsHelper dlmsHelper;

    @Override
    public PushSetupSmsDto execute(final DlmsConnectionManager conn, final DlmsDevice device, final Void useless) throws ProtocolAdapterException {
        conn.getDlmsMessageListener().setDescription("GetPushSetupSms, retrieve attributes: " + JdlmsObjectToStringUtil.describeAttributes(ATTRIBUTE_ADDRESSES));
        LOGGER.info("Retrieving Push Setup SMS");
        final List<GetResult> getResultList = this.dlmsHelper.getWithList(conn, device, ATTRIBUTE_ADDRESSES);
        GetPushSetupCommandExecutor.checkResultList(getResultList, ATTRIBUTE_ADDRESSES);
        final PushSetupSmsDto.Builder pushSetupSmsBuilder = new PushSetupSmsDto.Builder();
        pushSetupSmsBuilder.withLogicalName(new CosemObisCodeDto(OBIS_CODE.bytes()));
        pushSetupSmsBuilder.withPushObjectList(this.dlmsHelper.readListOfObjectDefinition(getResultList.get(INDEX_PUSH_OBJECT_LIST), "Push Object List"));
        pushSetupSmsBuilder.withSendDestinationAndMethod(this.dlmsHelper.readSendDestinationAndMethod(getResultList.get(INDEX_SEND_DESTINATION_AND_METHOD), "Send Destination And Method"));
        pushSetupSmsBuilder.withCommunicationWindow(this.dlmsHelper.readListOfWindowElement(getResultList.get(INDEX_COMMUNICATION_WINDOW), "Communication Window"));
        pushSetupSmsBuilder.withRandomisationStartInterval(this.dlmsHelper.readLongNotNull(getResultList.get(INDEX_RANDOMISATION_START_INTERVAL), "Randomisation Start Interval").intValue());
        pushSetupSmsBuilder.withNumberOfRetries(this.dlmsHelper.readLongNotNull(getResultList.get(INDEX_NUMBER_OF_RETRIES), "Number of Retries").intValue());
        pushSetupSmsBuilder.withRepereplacedionDelay(this.dlmsHelper.readLongNotNull(getResultList.get(INDEX_REPEreplacedION_DELAY), "Repereplacedion Delay").intValue());
        return pushSetupSmsBuilder.build();
    }
}

19 Source : GetPushSetupAlarmCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced GetPushSetupAlarmCommandExecutor extends GetPushSetupCommandExecutor<Void, PushSetupAlarmDto> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetPushSetupAlarmCommandExecutor.clreplaced);

    private static final ObisCode OBIS_CODE = new ObisCode("0.1.25.9.0.255");

    private static final AttributeAddress[] ATTRIBUTE_ADDRESSES = { new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_PUSH_OBJECT_LIST), new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_SEND_DESTINATION_AND_METHOD), new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_COMMUNICATION_WINDOW), new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_RANDOMISATION_START_INTERVAL), new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_NUMBER_OF_RETRIES), new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_REPEreplacedION_DELAY) };

    @Autowired
    private DlmsHelper dlmsHelper;

    @Override
    public PushSetupAlarmDto execute(final DlmsConnectionManager conn, final DlmsDevice device, final Void useless) throws ProtocolAdapterException {
        conn.getDlmsMessageListener().setDescription("GetPushSetupAlarm, retrieve attributes: " + JdlmsObjectToStringUtil.describeAttributes(ATTRIBUTE_ADDRESSES));
        LOGGER.info("Retrieving Push Setup Alarm");
        final List<GetResult> getResultList = this.dlmsHelper.getWithList(conn, device, ATTRIBUTE_ADDRESSES);
        GetPushSetupCommandExecutor.checkResultList(getResultList, ATTRIBUTE_ADDRESSES);
        final PushSetupAlarmDto.Builder pushSetupAlarmBuilder = new PushSetupAlarmDto.Builder();
        pushSetupAlarmBuilder.withLogicalName(new CosemObisCodeDto(OBIS_CODE.bytes()));
        pushSetupAlarmBuilder.withPushObjectList(this.dlmsHelper.readListOfObjectDefinition(getResultList.get(INDEX_PUSH_OBJECT_LIST), "Push Object List"));
        pushSetupAlarmBuilder.withSendDestinationAndMethod(this.dlmsHelper.readSendDestinationAndMethod(getResultList.get(INDEX_SEND_DESTINATION_AND_METHOD), "Send Destination And Method"));
        pushSetupAlarmBuilder.withCommunicationWindow(this.dlmsHelper.readListOfWindowElement(getResultList.get(INDEX_COMMUNICATION_WINDOW), "Communication Window"));
        pushSetupAlarmBuilder.withRandomisationStartInterval(this.dlmsHelper.readLongNotNull(getResultList.get(INDEX_RANDOMISATION_START_INTERVAL), "Randomisation Start Interval").intValue());
        pushSetupAlarmBuilder.withNumberOfRetries(this.dlmsHelper.readLongNotNull(getResultList.get(INDEX_NUMBER_OF_RETRIES), "Number of Retries").intValue());
        pushSetupAlarmBuilder.withRepereplacedionDelay(this.dlmsHelper.readLongNotNull(getResultList.get(INDEX_REPEreplacedION_DELAY), "Repereplacedion Delay").intValue());
        return pushSetupAlarmBuilder.build();
    }
}

19 Source : GetPeriodicMeterReadsGasCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced GetPeriodicMeterReadsGasCommandExecutor extends AbstractPeriodicMeterReadsCommandExecutor<PeriodicMeterReadsRequestDto, PeriodicMeterReadGasResponseDto> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetPeriodicMeterReadsGasCommandExecutor.clreplaced);

    private static final String GAS_VALUE = "gasValue";

    private static final String PERIODIC_G_METER_READS = "Periodic G-Meter Reads";

    private static final String UNEXPECTED_VALUE = "Unexpected null/unspecified value for Gas Capture Time";

    private static final String FORMAT_DESCRIPTION = "GetPeriodicMeterReadsGas for channel %s, %s from %s until %s, " + "retrieve attribute: %s";

    private final DlmsHelper dlmsHelper;

    private final DlmsObjectConfigService dlmsObjectConfigService;

    @Autowired
    public GetPeriodicMeterReadsGasCommandExecutor(final DlmsHelper dlmsHelper, final AmrProfileStatusCodeHelper amrProfileStatusCodeHelper, final DlmsObjectConfigService dlmsObjectConfigService) {
        super(PeriodicMeterReadsGasRequestDto.clreplaced, amrProfileStatusCodeHelper);
        this.dlmsHelper = dlmsHelper;
        this.dlmsObjectConfigService = dlmsObjectConfigService;
    }

    @Override
    public PeriodicMeterReadsRequestDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        final PeriodicMeterReadsGasRequestDto periodicMeterReadsGasRequestDto = (PeriodicMeterReadsGasRequestDto) bundleInput;
        return new PeriodicMeterReadsRequestDto(periodicMeterReadsGasRequestDto.getPeriodType(), periodicMeterReadsGasRequestDto.getBeginDate(), periodicMeterReadsGasRequestDto.getEndDate(), periodicMeterReadsGasRequestDto.getChannel());
    }

    @Override
    public PeriodicMeterReadGasResponseDto execute(final DlmsConnectionManager conn, final DlmsDevice device, final PeriodicMeterReadsRequestDto periodicMeterReadsQuery) throws ProtocolAdapterException {
        if (periodicMeterReadsQuery == null) {
            throw new IllegalArgumentException("PeriodicMeterReadsQuery should contain PeriodType, BeginDate and EndDate.");
        }
        final PeriodTypeDto queryPeriodType = periodicMeterReadsQuery.getPeriodType();
        final DateTime from = new DateTime(periodicMeterReadsQuery.getBeginDate());
        final DateTime to = new DateTime(periodicMeterReadsQuery.getEndDate());
        final AttributeAddressForProfile profileBufferAddress = this.getProfileBufferAddress(queryPeriodType, periodicMeterReadsQuery.getChannel(), from, to, device);
        final List<AttributeAddress> scalerUnitAddresses = this.getScalerUnitAddresses(periodicMeterReadsQuery.getChannel(), profileBufferAddress);
        final Optional<ProfileCaptureTime> intervalTime = this.getProfileCaptureTime(device, this.dlmsObjectConfigService, Medium.GAS);
        LOGGER.info("Retrieving current billing period and profiles for gas for period type: {}, from: " + "{}, to: {}", queryPeriodType, from, to);
        /*
         * workaround for a problem when using with_list and retrieving a profile
         * buffer, this will be returned erroneously.
         */
        final List<GetResult> getResultList = new ArrayList<>();
        final List<AttributeAddress> allAttributeAddresses = new ArrayList<>();
        allAttributeAddresses.add(profileBufferAddress.getAttributeAddress());
        allAttributeAddresses.addAll(scalerUnitAddresses);
        for (final AttributeAddress address : allAttributeAddresses) {
            conn.getDlmsMessageListener().setDescription(String.format(FORMAT_DESCRIPTION, periodicMeterReadsQuery.getChannel(), queryPeriodType, from, to, JdlmsObjectToStringUtil.describeAttributes(address)));
            getResultList.addAll(this.dlmsHelper.getAndCheck(conn, device, "retrieve periodic meter reads for " + queryPeriodType + ", channel " + periodicMeterReadsQuery.getChannel(), address));
        }
        LOGGER.info("Received getResult: {} ", getResultList);
        final DataObject resultData = this.dlmsHelper.readDataObject(getResultList.get(0), PERIODIC_G_METER_READS);
        final List<DataObject> bufferedObjectsList = resultData.getValue();
        final List<PeriodicMeterReadsGasResponseItemDto> periodicMeterReads = new ArrayList<>();
        for (final DataObject bufferedObject : bufferedObjectsList) {
            final List<DataObject> bufferedObjectValue = bufferedObject.getValue();
            try {
                periodicMeterReads.add(this.convertToResponseItem(new ConversionContext(periodicMeterReadsQuery, bufferedObjectValue, getResultList, profileBufferAddress, scalerUnitAddresses, intervalTime), periodicMeterReads));
            } catch (final BufferedDateTimeValidationException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
        LOGGER.info("Resulting periodicMeterReads: {} ", periodicMeterReads);
        return new PeriodicMeterReadGasResponseDto(queryPeriodType, periodicMeterReads);
    }

    private PeriodicMeterReadsGasResponseItemDto convertToResponseItem(final ConversionContext ctx, final List<PeriodicMeterReadsGasResponseItemDto> periodicMeterReads) throws ProtocolAdapterException, BufferedDateTimeValidationException {
        final Optional<Date> previousLogTime = this.getPreviousLogTime(periodicMeterReads);
        final Date logTime = this.readClock(ctx, previousLogTime, this.dlmsHelper);
        final AmrProfileStatusCodeDto status = this.readStatus(ctx.bufferedObjects, ctx.attributeAddressForProfile);
        final DataObject gasValue = this.readValue(ctx.bufferedObjects, ctx.attributeAddressForProfile);
        final DataObject scalerUnit = this.readScalerUnit(ctx.getResultList, ctx.attributeAddresses, ctx.attributeAddressForProfile, ctx.periodicMeterReadsQuery.getChannel().getChannelNumber());
        final Date captureTime = this.readCaptureTime(ctx.bufferedObjects, ctx.attributeAddressForProfile);
        LOGGER.info("Converting bufferObject with value: {} ", ctx.bufferedObjects);
        LOGGER.info("Resulting values: LogTime: {}, status: {}, gasValue {}, scalerUnit: {}, captureTime {} ", logTime, status, gasValue, scalerUnit, captureTime);
        return new PeriodicMeterReadsGasResponseItemDto(logTime, this.dlmsHelper.getScaledMeterValue(gasValue, scalerUnit, GAS_VALUE), captureTime, status);
    }

    private Optional<Date> getPreviousLogTime(final List<PeriodicMeterReadsGasResponseItemDto> periodicMeterReads) {
        if (periodicMeterReads.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(periodicMeterReads.get(periodicMeterReads.size() - 1).getLogTime());
    }

    private DataObject readValue(final List<DataObject> bufferedObjects, final AttributeAddressForProfile attributeAddressForProfile) {
        final Integer valueIndex = attributeAddressForProfile.getIndex(DlmsObjectType.MBUS_MASTER_VALUE, 2);
        DataObject value = null;
        if (valueIndex != null) {
            value = bufferedObjects.get(valueIndex);
        }
        return value;
    }

    private DataObject readScalerUnit(final List<GetResult> getResultList, final List<AttributeAddress> attributeAddresses, final AttributeAddressForProfile attributeAddressForProfile, final Integer channel) {
        final DlmsCaptureObject captureObject = attributeAddressForProfile.getCaptureObject(DlmsObjectType.MBUS_MASTER_VALUE);
        int index = 0;
        Integer scalerUnitIndex = null;
        for (final AttributeAddress address : attributeAddresses) {
            final String obisCode = captureObject.getRelatedObject().getObisCodereplacedtring().replace("<c>", channel.toString());
            if (address.getInstanceId().equals(new ObisCode(obisCode))) {
                scalerUnitIndex = index;
            }
            index++;
        }
        // Get scaler unit from result list. Note: "index + 1" because the first result is the array with values
        // and should be skipped. The first scaler unit is at index 1.
        if (scalerUnitIndex != null) {
            return getResultList.get(scalerUnitIndex + 1).getResultData();
        }
        return null;
    }

    private Date readCaptureTime(final List<DataObject> bufferedObjects, final AttributeAddressForProfile attributeAddressForProfile) throws ProtocolAdapterException {
        final Integer captureTimeIndex = attributeAddressForProfile.getIndex(DlmsObjectType.MBUS_MASTER_VALUE, 5);
        if (captureTimeIndex != null) {
            final CosemDateTimeDto cosemDateTime = this.dlmsHelper.readDateTime(bufferedObjects.get(captureTimeIndex), "Clock from mbus interval extended register");
            final Date captureTime;
            if (cosemDateTime.isDateTimeSpecified()) {
                captureTime = cosemDateTime.asDateTime().toDate();
            } else {
                throw new ProtocolAdapterException(UNEXPECTED_VALUE);
            }
            return captureTime;
        }
        return null;
    }

    private AttributeAddressForProfile getProfileBufferAddress(final PeriodTypeDto periodType, final ChannelDto channel, final DateTime beginDateTime, final DateTime endDateTime, final DlmsDevice device) throws ProtocolAdapterException {
        final DlmsObjectType type = DlmsObjectType.getTypeForPeriodType(periodType);
        // Add the attribute address for the profile
        final AttributeAddressForProfile attributeAddressProfile = this.dlmsObjectConfigService.findAttributeAddressForProfile(device, type, channel.getChannelNumber(), beginDateTime, endDateTime, Medium.GAS).orElseThrow(() -> new ProtocolAdapterException("No address found for " + type));
        LOGGER.info("Dlms object config service returned profile buffer address {} ", attributeAddressProfile);
        return attributeAddressProfile;
    }

    private List<AttributeAddress> getScalerUnitAddresses(final ChannelDto channel, final AttributeAddressForProfile attributeAddressForProfile) {
        final List<AttributeAddress> attributeAddresses = this.dlmsObjectConfigService.getAttributeAddressesForScalerUnit(attributeAddressForProfile, channel.getChannelNumber());
        LOGGER.info("Dlms object config service returned scaler unit addresses {} ", attributeAddresses);
        return attributeAddresses;
    }

    @Override
    public Logger getLogger() {
        return LOGGER;
    }
}

19 Source : GetPeriodicMeterReadsCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced GetPeriodicMeterReadsCommandExecutor extends AbstractPeriodicMeterReadsCommandExecutor<PeriodicMeterReadsRequestDto, PeriodicMeterReadsResponseDto> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetPeriodicMeterReadsCommandExecutor.clreplaced);

    static final String PERIODIC_E_METER_READS = "Periodic E-Meter Reads";

    private static final String FORMAT_DESCRIPTION = "GetPeriodicMeterReads %s from %s until %s, retrieve attribute: " + "%s";

    private final DlmsHelper dlmsHelper;

    private final DlmsObjectConfigService dlmsObjectConfigService;

    @Autowired
    public GetPeriodicMeterReadsCommandExecutor(final DlmsHelper dlmsHelper, final AmrProfileStatusCodeHelper amrProfileStatusCodeHelper, final DlmsObjectConfigService dlmsObjectConfigService) {
        super(PeriodicMeterReadsRequestDataDto.clreplaced, amrProfileStatusCodeHelper);
        this.dlmsHelper = dlmsHelper;
        this.dlmsObjectConfigService = dlmsObjectConfigService;
    }

    @Override
    public PeriodicMeterReadsRequestDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        final PeriodicMeterReadsRequestDataDto periodicMeterReadsRequestDataDto = (PeriodicMeterReadsRequestDataDto) bundleInput;
        return new PeriodicMeterReadsRequestDto(periodicMeterReadsRequestDataDto.getPeriodType(), periodicMeterReadsRequestDataDto.getBeginDate(), periodicMeterReadsRequestDataDto.getEndDate());
    }

    @Override
    public PeriodicMeterReadsResponseDto execute(final DlmsConnectionManager conn, final DlmsDevice device, final PeriodicMeterReadsRequestDto periodicMeterReadsQuery) throws ProtocolAdapterException {
        if (periodicMeterReadsQuery == null) {
            throw new IllegalArgumentException("PeriodicMeterReadsQuery should contain PeriodType, BeginDate and EndDate.");
        }
        final PeriodTypeDto queryPeriodType = periodicMeterReadsQuery.getPeriodType();
        final DateTime from = new DateTime(periodicMeterReadsQuery.getBeginDate());
        final DateTime to = new DateTime(periodicMeterReadsQuery.getEndDate());
        final AttributeAddressForProfile profileBufferAddress = this.getProfileBufferAddress(queryPeriodType, from, to, device);
        final List<AttributeAddress> scalerUnitAddresses = this.getScalerUnitAddresses(profileBufferAddress);
        final Optional<ProfileCaptureTime> intervalTime = this.getProfileCaptureTime(device, this.dlmsObjectConfigService, Medium.ELECTRICITY);
        LOGGER.debug("Retrieving current billing period and profiles for period type: {}, from: {}, to: {}", queryPeriodType, from, to);
        // Get results one by one because getWithList does not work for all devices
        final List<GetResult> getResultList = new ArrayList<>();
        final List<AttributeAddress> allAttributeAddresses = new ArrayList<>();
        allAttributeAddresses.add(profileBufferAddress.getAttributeAddress());
        allAttributeAddresses.addAll(scalerUnitAddresses);
        for (final AttributeAddress address : allAttributeAddresses) {
            conn.getDlmsMessageListener().setDescription(String.format(FORMAT_DESCRIPTION, queryPeriodType, from, to, JdlmsObjectToStringUtil.describeAttributes(address)));
            getResultList.addAll(this.dlmsHelper.getAndCheck(conn, device, "retrieve periodic meter reads for " + queryPeriodType, address));
        }
        LOGGER.info("Received getResult: {} ", getResultList);
        final DataObject resultData = this.dlmsHelper.readDataObject(getResultList.get(0), PERIODIC_E_METER_READS);
        final List<DataObject> bufferedObjectsList = resultData.getValue();
        final List<PeriodicMeterReadsResponseItemDto> periodicMeterReads = new ArrayList<>();
        for (final DataObject bufferedObject : bufferedObjectsList) {
            final List<DataObject> bufferedObjectValue = bufferedObject.getValue();
            try {
                periodicMeterReads.add(this.convertToResponseItem(new ConversionContext(periodicMeterReadsQuery, bufferedObjectValue, getResultList, profileBufferAddress, scalerUnitAddresses, intervalTime), periodicMeterReads));
            } catch (final BufferedDateTimeValidationException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
        return new PeriodicMeterReadsResponseDto(queryPeriodType, periodicMeterReads);
    }

    private PeriodicMeterReadsResponseItemDto convertToResponseItem(final ConversionContext ctx, final List<PeriodicMeterReadsResponseItemDto> periodicMeterReads) throws ProtocolAdapterException, BufferedDateTimeValidationException {
        LOGGER.info("Converting bufferObject with value: {} ", ctx.bufferedObjects);
        final Optional<Date> previousLogTime = this.getPreviousLogTime(periodicMeterReads);
        final Date logTime = this.readClock(ctx, previousLogTime, this.dlmsHelper);
        final AmrProfileStatusCodeDto status = this.readStatus(ctx.bufferedObjects, ctx.attributeAddressForProfile);
        if (ctx.periodicMeterReadsQuery.getPeriodType() == PeriodTypeDto.INTERVAL) {
            final DlmsMeterValueDto importValue = this.getScaledMeterValue(ctx.bufferedObjects, ctx.getResultList, ctx.attributeAddresses, ctx.attributeAddressForProfile, DlmsObjectType.ACTIVE_ENERGY_IMPORT, "positiveActiveEnergy");
            final DlmsMeterValueDto exportValue = this.getScaledMeterValue(ctx.bufferedObjects, ctx.getResultList, ctx.attributeAddresses, ctx.attributeAddressForProfile, DlmsObjectType.ACTIVE_ENERGY_EXPORT, "negativeActiveEnergy");
            LOGGER.info("Resulting values: LogTime: {}, status: {}, importValue {}, exportValue {} ", logTime, status, importValue, exportValue);
            return new PeriodicMeterReadsResponseItemDto(logTime, importValue, exportValue, status);
        } else {
            final DlmsMeterValueDto importValueRate1 = this.getScaledMeterValue(ctx.bufferedObjects, ctx.getResultList, ctx.attributeAddresses, ctx.attributeAddressForProfile, DlmsObjectType.ACTIVE_ENERGY_IMPORT_RATE_1, "positiveActiveEnergyTariff1");
            final DlmsMeterValueDto importValueRate2 = this.getScaledMeterValue(ctx.bufferedObjects, ctx.getResultList, ctx.attributeAddresses, ctx.attributeAddressForProfile, DlmsObjectType.ACTIVE_ENERGY_IMPORT_RATE_2, "positiveActiveEnergyTariff2");
            final DlmsMeterValueDto exportValueRate1 = this.getScaledMeterValue(ctx.bufferedObjects, ctx.getResultList, ctx.attributeAddresses, ctx.attributeAddressForProfile, DlmsObjectType.ACTIVE_ENERGY_EXPORT_RATE_1, "negativeActiveEnergyTariff1");
            final DlmsMeterValueDto exportValueRate2 = this.getScaledMeterValue(ctx.bufferedObjects, ctx.getResultList, ctx.attributeAddresses, ctx.attributeAddressForProfile, DlmsObjectType.ACTIVE_ENERGY_EXPORT_RATE_2, "negativeActiveEnergyTariff2");
            LOGGER.info("Resulting values: LogTime: {}, status: {}, importRate1Value {}, importRate2Value {}, " + "exportRate1Value {}, exportRate2Value {} ", logTime, status, importValueRate1, importValueRate2, exportValueRate1, exportValueRate2);
            return new PeriodicMeterReadsResponseItemDto(logTime, importValueRate1, importValueRate2, exportValueRate1, exportValueRate2, status);
        }
    }

    private Optional<Date> getPreviousLogTime(final List<PeriodicMeterReadsResponseItemDto> periodicMeterReads) {
        if (periodicMeterReads.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(periodicMeterReads.get(periodicMeterReads.size() - 1).getLogTime());
    }

    private DlmsMeterValueDto getScaledMeterValue(final List<DataObject> bufferedObjects, final List<GetResult> getResultList, final List<AttributeAddress> attributeAddresses, final AttributeAddressForProfile attributeAddressForProfile, final DlmsObjectType objectType, final String description) throws ProtocolAdapterException {
        final DataObject importValue = this.readValue(bufferedObjects, attributeAddressForProfile, objectType);
        final DataObject importScalerUnit = this.readScalerUnit(getResultList, attributeAddresses, attributeAddressForProfile, objectType);
        return this.dlmsHelper.getScaledMeterValue(importValue, importScalerUnit, description);
    }

    private DataObject readValue(final List<DataObject> bufferedObjects, final AttributeAddressForProfile attributeAddressForProfile, final DlmsObjectType objectType) {
        final Integer valueIndex = attributeAddressForProfile.getIndex(objectType, 2);
        DataObject value = null;
        if (valueIndex != null) {
            value = bufferedObjects.get(valueIndex);
        }
        return value;
    }

    private DataObject readScalerUnit(final List<GetResult> getResultList, final List<AttributeAddress> attributeAddresses, final AttributeAddressForProfile attributeAddressForProfile, final DlmsObjectType objectType) {
        final DlmsCaptureObject captureObject = attributeAddressForProfile.getCaptureObject(objectType);
        int index = 0;
        Integer scalerUnitIndex = null;
        for (final AttributeAddress address : attributeAddresses) {
            final ObisCode obisCode = captureObject.getRelatedObject().getObisCode();
            if (address.getInstanceId().equals(obisCode)) {
                scalerUnitIndex = index;
            }
            index++;
        }
        // Get scaler unit from result list. Note: "index + 1" because the first result is the array with values
        // and should be skipped. The first scaler unit is at index 1.
        if (scalerUnitIndex != null) {
            return getResultList.get(scalerUnitIndex + 1).getResultData();
        }
        return null;
    }

    private AttributeAddressForProfile getProfileBufferAddress(final PeriodTypeDto periodType, final DateTime beginDateTime, final DateTime endDateTime, final DlmsDevice device) throws ProtocolAdapterException {
        final DlmsObjectType type = DlmsObjectType.getTypeForPeriodType(periodType);
        // Add the attribute address for the profile
        final AttributeAddressForProfile attributeAddressProfile = this.dlmsObjectConfigService.findAttributeAddressForProfile(device, type, 0, beginDateTime, endDateTime, Medium.ELECTRICITY).orElseThrow(() -> new ProtocolAdapterException("No address found for " + type));
        LOGGER.info("Dlms object config service returned profile buffer address {} ", attributeAddressProfile);
        return attributeAddressProfile;
    }

    private List<AttributeAddress> getScalerUnitAddresses(final AttributeAddressForProfile attributeAddressForProfile) {
        final List<AttributeAddress> attributeAddresses = this.dlmsObjectConfigService.getAttributeAddressesForScalerUnit(attributeAddressForProfile, 0);
        LOGGER.info("Dlms object config service returned scaler unit addresses {} ", attributeAddresses);
        return attributeAddresses;
    }

    @Override
    protected Logger getLogger() {
        return LOGGER;
    }
}

19 Source : SetAdministrativeStatusCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced SetAdministrativeStatusCommandExecutor extends AbstractCommandExecutor<AdministrativeStatusTypeDto, AccessResultCode> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SetAdministrativeStatusCommandExecutor.clreplaced);

    private static final int CLreplaced_ID = 1;

    private static final ObisCode OBIS_CODE = new ObisCode("0.1.94.31.0.255");

    private static final int ATTRIBUTE_ID = 2;

    @Autowired
    private ConfigurationMapper configurationMapper;

    public SetAdministrativeStatusCommandExecutor() {
        super(AdministrativeStatusTypeDataDto.clreplaced);
    }

    @Override
    public AdministrativeStatusTypeDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        final AdministrativeStatusTypeDataDto administrativeStatusTypeDataDto = (AdministrativeStatusTypeDataDto) bundleInput;
        return administrativeStatusTypeDataDto.getAdministrativeStatusType();
    }

    @Override
    public ActionResponseDto asBundleResponse(final AccessResultCode executionResult) throws ProtocolAdapterException {
        this.checkAccessResultCode(executionResult);
        return new ActionResponseDto("Set administrative status was successful");
    }

    @Override
    public AccessResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final AdministrativeStatusTypeDto administrativeStatusType) throws ProtocolAdapterException {
        LOGGER.info("Set administrative status by issuing get request for clreplaced id: {}, obis code: {}, attribute id: {}", CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID);
        final AttributeAddress attributeAddress = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID);
        final DataObject value = DataObject.newEnumerateData(this.configurationMapper.map(administrativeStatusType, Integer.clreplaced));
        final SetParameter setParameter = new SetParameter(attributeAddress, value);
        conn.getDlmsMessageListener().setDescription("SetAdminstrativeStatus to " + administrativeStatusType + ", set attribute: " + JdlmsObjectToStringUtil.describeAttributes(attributeAddress));
        try {
            return conn.getConnection().set(setParameter);
        } catch (final IOException e) {
            throw new ConnectionException(e);
        }
    }
}

19 Source : GetAdministrativeStatusCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced GetAdministrativeStatusCommandExecutor extends AbstractCommandExecutor<Void, AdministrativeStatusTypeDto> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetAdministrativeStatusCommandExecutor.clreplaced);

    private static final int CLreplaced_ID = 1;

    private static final ObisCode OBIS_CODE = new ObisCode("0.1.94.31.0.255");

    private static final int ATTRIBUTE_ID = 2;

    @Autowired
    private ConfigurationMapper configurationMapper;

    public GetAdministrativeStatusCommandExecutor() {
        super(GetAdministrativeStatusDataDto.clreplaced);
    }

    @Override
    public Void fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        return null;
    }

    @Override
    public ActionResponseDto asBundleResponse(final AdministrativeStatusTypeDto executionResult) throws ProtocolAdapterException {
        return new AdministrativeStatusTypeResponseDto(executionResult);
    }

    @Override
    public AdministrativeStatusTypeDto execute(final DlmsConnectionManager conn, final DlmsDevice device, final Void useless) throws ProtocolAdapterException {
        final AttributeAddress getParameter = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID);
        conn.getDlmsMessageListener().setDescription("GetAdministrativeStatus, retrieve attribute: " + JdlmsObjectToStringUtil.describeAttributes(getParameter));
        LOGGER.info("Retrieving current administrative status by issuing get request for clreplaced id: {}, obis code: {}, " + "attribute id: {}", CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID);
        final DataObject dataObject = this.getValidatedResultData(conn, getParameter);
        return this.configurationMapper.map(dataObject.getValue(), AdministrativeStatusTypeDto.clreplaced);
    }
}

19 Source : GetActualMeterReadsGasCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced GetActualMeterReadsGasCommandExecutor extends AbstractCommandExecutor<ActualMeterReadsQueryDto, MeterReadsGasResponseDto> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetActualMeterReadsGasCommandExecutor.clreplaced);

    private static final int CLreplaced_ID_MBUS = 4;

    private static final byte ATTRIBUTE_ID_VALUE = 2;

    private static final byte ATTRIBUTE_ID_SCALER_UNIT = 3;

    private static final byte ATTRIBUTE_ID_TIME = 5;

    private static final ObisCode OBIS_CODE_MBUS_MASTER_VALUE_1 = new ObisCode("0.1.24.2.1.255");

    private static final ObisCode OBIS_CODE_MBUS_MASTER_VALUE_2 = new ObisCode("0.2.24.2.1.255");

    private static final ObisCode OBIS_CODE_MBUS_MASTER_VALUE_3 = new ObisCode("0.3.24.2.1.255");

    private static final ObisCode OBIS_CODE_MBUS_MASTER_VALUE_4 = new ObisCode("0.4.24.2.1.255");

    @Autowired
    private DlmsHelper dlmsHelper;

    public GetActualMeterReadsGasCommandExecutor() {
        super(ActualMeterReadsDataGasDto.clreplaced);
    }

    @Override
    public ActualMeterReadsQueryDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        final ActualMeterReadsDataGasDto actualMeterReadsDataGasDto = (ActualMeterReadsDataGasDto) bundleInput;
        return new ActualMeterReadsQueryDto(actualMeterReadsDataGasDto.getChannel());
    }

    @Override
    public MeterReadsGasResponseDto execute(final DlmsConnectionManager conn, final DlmsDevice device, final ActualMeterReadsQueryDto actualMeterReadsRequest) throws ProtocolAdapterException {
        final ObisCode obisCodeMbusMasterValue = this.masterValueForChannel(actualMeterReadsRequest.getChannel());
        LOGGER.debug("Retrieving current MBUS master value for ObisCode: {}", obisCodeMbusMasterValue);
        final AttributeAddress mbusValue = new AttributeAddress(CLreplaced_ID_MBUS, this.masterValueForChannel(actualMeterReadsRequest.getChannel()), ATTRIBUTE_ID_VALUE);
        LOGGER.debug("Retrieving current MBUS master capture time for ObisCode: {}", obisCodeMbusMasterValue);
        final AttributeAddress mbusTime = new AttributeAddress(CLreplaced_ID_MBUS, obisCodeMbusMasterValue, ATTRIBUTE_ID_TIME);
        final AttributeAddress scalerUnit = new AttributeAddress(CLreplaced_ID_MBUS, this.masterValueForChannel(actualMeterReadsRequest.getChannel()), ATTRIBUTE_ID_SCALER_UNIT);
        conn.getDlmsMessageListener().setDescription("GetActualMeterReadsGas for channel " + actualMeterReadsRequest.getChannel() + ", retrieve attributes: " + JdlmsObjectToStringUtil.describeAttributes(mbusValue, mbusTime, scalerUnit));
        final List<GetResult> getResultList = this.dlmsHelper.getAndCheck(conn, device, "retrieve actual meter reads for mbus " + actualMeterReadsRequest.getChannel(), mbusValue, mbusTime, scalerUnit);
        final DlmsMeterValueDto consumption = this.dlmsHelper.getScaledMeterValue(getResultList.get(0), getResultList.get(2), "retrieve scaled value for mbus " + actualMeterReadsRequest.getChannel());
        final CosemDateTimeDto cosemDateTime = this.dlmsHelper.readDateTime(getResultList.get(1), "captureTime gas");
        final Date captureTime;
        if (cosemDateTime.isDateTimeSpecified()) {
            captureTime = cosemDateTime.asDateTime().toDate();
        } else {
            throw new ProtocolAdapterException("Unexpected null/unspecified value for M-Bus Capture Time");
        }
        return new MeterReadsGasResponseDto(new Date(), consumption, captureTime);
    }

    private ObisCode masterValueForChannel(final ChannelDto channel) throws ProtocolAdapterException {
        switch(channel) {
            case ONE:
                return OBIS_CODE_MBUS_MASTER_VALUE_1;
            case TWO:
                return OBIS_CODE_MBUS_MASTER_VALUE_2;
            case THREE:
                return OBIS_CODE_MBUS_MASTER_VALUE_3;
            case FOUR:
                return OBIS_CODE_MBUS_MASTER_VALUE_4;
            default:
                throw new ProtocolAdapterException(String.format("channel %s not supported", channel));
        }
    }
}

19 Source : GetActualMeterReadsCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced GetActualMeterReadsCommandExecutor extends AbstractCommandExecutor<ActualMeterReadsQueryDto, MeterReadsResponseDto> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetActualMeterReadsCommandExecutor.clreplaced);

    private static final int CLreplaced_ID_REGISTER = 3;

    private static final ObisCode OBIS_CODE_ACTIVE_ENERGY_IMPORT = new ObisCode("1.0.1.8.0.255");

    private static final ObisCode OBIS_CODE_ACTIVE_ENERGY_EXPORT = new ObisCode("1.0.2.8.0.255");

    private static final ObisCode OBIS_CODE_ACTIVE_ENERGY_IMPORT_RATE_1 = new ObisCode("1.0.1.8.1.255");

    private static final ObisCode OBIS_CODE_ACTIVE_ENERGY_IMPORT_RATE_2 = new ObisCode("1.0.1.8.2.255");

    private static final ObisCode OBIS_CODE_ACTIVE_ENERGY_EXPORT_RATE_1 = new ObisCode("1.0.2.8.1.255");

    private static final ObisCode OBIS_CODE_ACTIVE_ENERGY_EXPORT_RATE_2 = new ObisCode("1.0.2.8.2.255");

    private static final byte ATTRIBUTE_ID_VALUE = 2;

    private static final byte ATTRIBUTE_ID_SCALER_UNIT = 3;

    private static final int CLreplaced_ID_CLOCK = 8;

    private static final ObisCode OBIS_CODE_CLOCK = new ObisCode("0.0.1.0.0.255");

    private static final byte ATTRIBUTE_ID_TIME = 2;

    // scaler unit attribute address is filled dynamically
    private static final AttributeAddress[] ATTRIBUTE_ADDRESSES = { new AttributeAddress(CLreplaced_ID_CLOCK, OBIS_CODE_CLOCK, ATTRIBUTE_ID_TIME), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_IMPORT, ATTRIBUTE_ID_VALUE), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_IMPORT_RATE_1, ATTRIBUTE_ID_VALUE), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_IMPORT_RATE_2, ATTRIBUTE_ID_VALUE), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_EXPORT, ATTRIBUTE_ID_VALUE), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_EXPORT_RATE_1, ATTRIBUTE_ID_VALUE), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_EXPORT_RATE_2, ATTRIBUTE_ID_VALUE), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_IMPORT, ATTRIBUTE_ID_SCALER_UNIT), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_IMPORT_RATE_1, ATTRIBUTE_ID_SCALER_UNIT), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_IMPORT_RATE_2, ATTRIBUTE_ID_SCALER_UNIT), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_EXPORT, ATTRIBUTE_ID_SCALER_UNIT), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_EXPORT_RATE_1, ATTRIBUTE_ID_SCALER_UNIT), new AttributeAddress(CLreplaced_ID_REGISTER, OBIS_CODE_ACTIVE_ENERGY_EXPORT_RATE_2, ATTRIBUTE_ID_SCALER_UNIT) };

    private static final int INDEX_TIME = 0;

    private static final int INDEX_ACTIVE_ENERGY_IMPORT = 1;

    private static final int INDEX_ACTIVE_ENERGY_IMPORT_RATE_1 = 2;

    private static final int INDEX_ACTIVE_ENERGY_IMPORT_RATE_2 = 3;

    private static final int INDEX_ACTIVE_ENERGY_EXPORT = 4;

    private static final int INDEX_ACTIVE_ENERGY_EXPORT_RATE_1 = 5;

    private static final int INDEX_ACTIVE_ENERGY_EXPORT_RATE_2 = 6;

    private static final int INDEX_ACTIVE_ENERGY_IMPORT_SCALER_UNIT = 7;

    private static final int INDEX_ACTIVE_ENERGY_IMPORT_RATE_1_SCALER_UNIT = 8;

    private static final int INDEX_ACTIVE_ENERGY_IMPORT_RATE_2_SCALER_UNIT = 9;

    private static final int INDEX_ACTIVE_ENERGY_EXPORT_SCALER_UNIT = 10;

    private static final int INDEX_ACTIVE_ENERGY_EXPORT_RATE_1_SCALER_UNIT = 11;

    private static final int INDEX_ACTIVE_ENERGY_EXPORT_RATE_2_SCALER_UNIT = 12;

    @Autowired
    private DlmsHelper dlmsHelper;

    public GetActualMeterReadsCommandExecutor() {
        super(ActualMeterReadsDataDto.clreplaced);
    }

    @Override
    public ActualMeterReadsQueryDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        /*
         * The ActionRequestDto, which is an ActualMeterReadsDataDto does not
         * contain any data, so no further configuration of the
         * ActualMeterReadsQueryDto is necessary.
         */
        return new ActualMeterReadsQueryDto();
    }

    @Override
    public MeterReadsResponseDto execute(final DlmsConnectionManager conn, final DlmsDevice device, final ActualMeterReadsQueryDto actualMeterReadsQuery) throws ProtocolAdapterException {
        if (actualMeterReadsQuery != null && actualMeterReadsQuery.isMbusQuery()) {
            throw new IllegalArgumentException("ActualMeterReadsQuery object for energy reads should not be about gas.");
        }
        conn.getDlmsMessageListener().setDescription("GetActualMeterReads retrieve attributes: " + JdlmsObjectToStringUtil.describeAttributes(ATTRIBUTE_ADDRESSES));
        LOGGER.info("Retrieving actual energy reads");
        final List<GetResult> getResultList = this.dlmsHelper.getAndCheck(conn, device, "retrieve actual meter reads", ATTRIBUTE_ADDRESSES);
        final CosemDateTimeDto cosemDateTime = this.dlmsHelper.readDateTime(getResultList.get(INDEX_TIME), "Actual Energy Reads Time");
        final DateTime time = cosemDateTime.asDateTime();
        if (time == null) {
            throw new ProtocolAdapterException("Unexpected null/unspecified value for Actual Energy Reads Time");
        }
        final DlmsMeterValueDto activeEnergyImport = this.dlmsHelper.getScaledMeterValue(getResultList.get(INDEX_ACTIVE_ENERGY_IMPORT), getResultList.get(INDEX_ACTIVE_ENERGY_IMPORT_SCALER_UNIT), "Actual Energy Reads +A");
        final DlmsMeterValueDto activeEnergyExport = this.dlmsHelper.getScaledMeterValue(getResultList.get(INDEX_ACTIVE_ENERGY_EXPORT), getResultList.get(INDEX_ACTIVE_ENERGY_EXPORT_SCALER_UNIT), "Actual Energy Reads -A");
        final DlmsMeterValueDto activeEnergyImportRate1 = this.dlmsHelper.getScaledMeterValue(getResultList.get(INDEX_ACTIVE_ENERGY_IMPORT_RATE_1), getResultList.get(INDEX_ACTIVE_ENERGY_IMPORT_RATE_1_SCALER_UNIT), "Actual Energy Reads +A rate 1");
        final DlmsMeterValueDto activeEnergyImportRate2 = this.dlmsHelper.getScaledMeterValue(getResultList.get(INDEX_ACTIVE_ENERGY_IMPORT_RATE_2), getResultList.get(INDEX_ACTIVE_ENERGY_IMPORT_RATE_2_SCALER_UNIT), "Actual Energy Reads +A rate 2");
        final DlmsMeterValueDto activeEnergyExportRate1 = this.dlmsHelper.getScaledMeterValue(getResultList.get(INDEX_ACTIVE_ENERGY_EXPORT_RATE_1), getResultList.get(INDEX_ACTIVE_ENERGY_EXPORT_RATE_1_SCALER_UNIT), "Actual Energy Reads -A rate 1");
        final DlmsMeterValueDto activeEnergyExportRate2 = this.dlmsHelper.getScaledMeterValue(getResultList.get(INDEX_ACTIVE_ENERGY_EXPORT_RATE_2), getResultList.get(INDEX_ACTIVE_ENERGY_EXPORT_RATE_2_SCALER_UNIT), "Actual Energy Reads -A rate 2");
        return new MeterReadsResponseDto(time.toDate(), new ActiveEnergyValuesDto(activeEnergyImport, activeEnergyExport, activeEnergyImportRate1, activeEnergyImportRate2, activeEnergyExportRate1, activeEnergyExportRate2));
    }
}

19 Source : FindEventsCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced FindEventsCommandExecutor extends AbstractCommandExecutor<FindEventsRequestDto, List<EventDto>> {

    private static final Logger LOGGER = LoggerFactory.getLogger(FindEventsCommandExecutor.clreplaced);

    private static final int CLreplaced_ID = 7;

    private static final int ATTRIBUTE_ID = 2;

    private static final int CLreplaced_ID_CLOCK = 8;

    private static final byte[] OBIS_BYTES_CLOCK = new byte[] { 0, 0, 1, 0, 0, (byte) 255 };

    private static final byte ATTRIBUTE_ID_TIME = 2;

    private static final int ACCESS_SELECTOR_RANGE_DESCRIPTOR = 1;

    private final DataObjectToEventListConverter dataObjectToEventListConverter;

    private final DlmsHelper dlmsHelper;

    // @formatter:off
    private static final EnumMap<EventLogCategoryDto, ObisCode> EVENT_LOG_CATEGORY_OBISCODE_MAP = new EnumMap<>(EventLogCategoryDto.clreplaced);

    static {
        EVENT_LOG_CATEGORY_OBISCODE_MAP.put(EventLogCategoryDto.STANDARD_EVENT_LOG, new ObisCode("0.0.99.98.0.255"));
        EVENT_LOG_CATEGORY_OBISCODE_MAP.put(EventLogCategoryDto.FRAUD_DETECTION_LOG, new ObisCode("0.0.99.98.1.255"));
        EVENT_LOG_CATEGORY_OBISCODE_MAP.put(EventLogCategoryDto.COMMUNICATION_SESSION_LOG, new ObisCode("0.0.99.98.4.255"));
        EVENT_LOG_CATEGORY_OBISCODE_MAP.put(EventLogCategoryDto.M_BUS_EVENT_LOG, new ObisCode("0.0.99.98.3.255"));
        EVENT_LOG_CATEGORY_OBISCODE_MAP.put(EventLogCategoryDto.POWER_QUALITY_EVENT_LOG, new ObisCode("0.0.99.98.5.255"));
    }

    @Autowired
    public FindEventsCommandExecutor(final DlmsHelper dlmsHelper, final DataObjectToEventListConverter dataObjectToEventListConverter) {
        super(FindEventsRequestDto.clreplaced);
        this.dlmsHelper = dlmsHelper;
        this.dataObjectToEventListConverter = dataObjectToEventListConverter;
    }

    @Override
    public ActionResponseDto asBundleResponse(final List<EventDto> executionResult) throws ProtocolAdapterException {
        return new EventMessageDataResponseDto(executionResult);
    }

    @Override
    public List<EventDto> execute(final DlmsConnectionManager conn, final DlmsDevice device, final FindEventsRequestDto findEventsQuery) throws ProtocolAdapterException {
        final SelectiveAccessDescription selectiveAccessDescription = this.getSelectiveAccessDescription(findEventsQuery.getFrom(), findEventsQuery.getUntil());
        final AttributeAddress eventLogBuffer = new AttributeAddress(CLreplaced_ID, EVENT_LOG_CATEGORY_OBISCODE_MAP.get(findEventsQuery.getEventLogCategory()), ATTRIBUTE_ID, selectiveAccessDescription);
        conn.getDlmsMessageListener().setDescription("RetrieveEvents for " + findEventsQuery.getEventLogCategory() + " from " + findEventsQuery.getFrom() + " until " + findEventsQuery.getUntil() + ", retrieve attribute: " + JdlmsObjectToStringUtil.describeAttributes(eventLogBuffer));
        final GetResult getResult;
        try {
            getResult = conn.getConnection().get(eventLogBuffer);
        } catch (final IOException e) {
            throw new ConnectionException(e);
        }
        if (getResult == null) {
            throw new ProtocolAdapterException("No GetResult received while retrieving event register " + findEventsQuery.getEventLogCategory());
        }
        if (!AccessResultCode.SUCCESS.equals(getResult.getResultCode())) {
            LOGGER.info("Result of getting events for {} is {}", findEventsQuery.getEventLogCategory(), getResult.getResultCode());
            throw new ProtocolAdapterException("Getting the events for  " + findEventsQuery.getEventLogCategory() + " from the meter resulted in: " + getResult.getResultCode());
        }
        final DataObject resultData = getResult.getResultData();
        return this.dataObjectToEventListConverter.convert(resultData, findEventsQuery.getEventLogCategory());
    }

    private SelectiveAccessDescription getSelectiveAccessDescription(final DateTime beginDateTime, final DateTime endDateTime) {
        /*
         * Define the clock object {8,0-0:1.0.0.255,2,0} to be used as
         * restricting object in a range descriptor with a from value and to
         * value to determine which elements from the buffered array should be
         * retrieved.
         */
        final DataObject clockDefinition = DataObject.newStructureData(Arrays.asList(DataObject.newUInteger16Data(CLreplaced_ID_CLOCK), DataObject.newOctetStringData(OBIS_BYTES_CLOCK), DataObject.newInteger8Data(ATTRIBUTE_ID_TIME), DataObject.newUInteger16Data(0)));
        final DataObject fromValue = this.dlmsHelper.asDataObject(beginDateTime);
        final DataObject toValue = this.dlmsHelper.asDataObject(endDateTime);
        /*
         * Retrieve all captured objects by setting selectedValues to an empty
         * array.
         */
        final DataObject selectedValues = DataObject.newArrayData(Collections.emptyList());
        final DataObject accessParameter = DataObject.newStructureData(Arrays.asList(clockDefinition, fromValue, toValue, selectedValues));
        return new SelectiveAccessDescription(ACCESS_SELECTOR_RANGE_DESCRIPTOR, accessParameter);
    }
}

19 Source : SetMbusUserKeyByChannelCommandExecutor.java
with Apache License 2.0
from OSGP

/**
 * Executor that sets the M-Bus User key for an M-Bus device on a given channel
 * on a gateway device.
 * <p>
 * This executor delegates meter communication to the
 * {@link SetEncryptionKeyExchangeOnGMeterCommandExecutor} for which the actual
 * M-Bus device (with its M-Bus master key) needs to be known ahead of
 * execution.
 * <p>
 * This is implemented as a command executor in order to be able to link it to a
 * {@link SetMbusUserKeyByChannelRequestDataDto} from a bundle, as there does
 * not appear to be a simple way to use the
 * {@link SetEncryptionKeyExchangeOnGMeterCommandExecutor} from the
 * {@link BundleService} for both the {@link GMeterInfoDto} and the
 * {@link SetMbusUserKeyByChannelRequestDataDto} (where in the latter case the
 * M-Bus device has to be retrieved by the channel and the gateway device, while
 * in the former case it can be looked up by device identification).
 */
@Component()
public clreplaced SetMbusUserKeyByChannelCommandExecutor extends AbstractCommandExecutor<GMeterInfoDto, MethodResultCode> {

    @Autowired
    private ConfigurationService configurationService;

    @Autowired
    private SetEncryptionKeyExchangeOnGMeterCommandExecutor setEncryptionKeyExchangeOnGMeterCommandExecutor;

    public SetMbusUserKeyByChannelCommandExecutor() {
        super(SetMbusUserKeyByChannelRequestDataDto.clreplaced);
    }

    @Override
    public ActionResponseDto executeBundleAction(final DlmsConnectionManager conn, final DlmsDevice device, final ActionRequestDto actionRequestDto) throws OsgpException {
        this.checkActionRequestType(actionRequestDto);
        final SetMbusUserKeyByChannelRequestDataDto setMbusUserKeyByChannelRequestData = (SetMbusUserKeyByChannelRequestDataDto) actionRequestDto;
        final GMeterInfoDto gMeterInfo = this.configurationService.getMbusKeyExchangeData(conn, device, setMbusUserKeyByChannelRequestData);
        final MethodResultCode executionResult = this.execute(conn, device, gMeterInfo);
        return this.asBundleResponse(executionResult);
    }

    @Override
    public ActionResponseDto asBundleResponse(final MethodResultCode executionResult) throws ProtocolAdapterException {
        this.checkMethodResultCode(executionResult);
        return new ActionResponseDto("Setting M-Bus User key by channel was successful");
    }

    @Override
    public MethodResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final GMeterInfoDto gMeterInfo) throws ProtocolAdapterException, FunctionalException {
        return this.setEncryptionKeyExchangeOnGMeterCommandExecutor.execute(conn, device, gMeterInfo);
    }
}

19 Source : GetMbusEncryptionKeyStatusCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced GetMbusEncryptionKeyStatusCommandExecutor extends AbstractCommandExecutor<GetMbusEncryptionKeyStatusRequestDto, GetMbusEncryptionKeyStatusResponseDto> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetMbusEncryptionKeyStatusCommandExecutor.clreplaced);

    private static final int CLreplaced_ID = InterfaceClreplaced.MBUS_CLIENT.id();

    private static final Map<Short, ObisCode> OBIS_CODES = new HashMap<>();

    private static final int ATTRIBUTE_ID = MbusClientAttribute.ENCRYPTION_KEY_STATUS.attributeId();

    static {
        OBIS_CODES.put((short) 1, new ObisCode("0.1.24.1.0.255"));
        OBIS_CODES.put((short) 2, new ObisCode("0.2.24.1.0.255"));
        OBIS_CODES.put((short) 3, new ObisCode("0.3.24.1.0.255"));
        OBIS_CODES.put((short) 4, new ObisCode("0.4.24.1.0.255"));
    }

    public GetMbusEncryptionKeyStatusCommandExecutor() {
        super(GetMbusEncryptionKeyStatusRequestDto.clreplaced);
    }

    @Override
    public GetMbusEncryptionKeyStatusResponseDto execute(final DlmsConnectionManager conn, final DlmsDevice device, final GetMbusEncryptionKeyStatusRequestDto request) throws ProtocolAdapterException {
        final EncryptionKeyStatusTypeDto encryptionKeyStatusType = this.getEncryptionKeyStatusTypeDto(request.getChannel(), conn);
        return new GetMbusEncryptionKeyStatusResponseDto(request.getMbusDeviceIdentification(), encryptionKeyStatusType);
    }

    public EncryptionKeyStatusTypeDto getEncryptionKeyStatusTypeDto(final short channel, final DlmsConnectionManager conn) throws ProtocolAdapterException {
        final ObisCode obisCode = OBIS_CODES.get(channel);
        final AttributeAddress getParameter = new AttributeAddress(CLreplaced_ID, obisCode, ATTRIBUTE_ID);
        conn.getDlmsMessageListener().setDescription("GetMbusEncryptionKeyStatusByChannel, retrieve attribute: " + JdlmsObjectToStringUtil.describeAttributes(getParameter));
        LOGGER.info("Retrieving current M-Bus encryption key status by issuing get request for clreplaced id: {}, obis code: " + "{}, attribute id: {}", CLreplaced_ID, obisCode, ATTRIBUTE_ID);
        final DataObject dataObject = this.getValidatedResultData(conn, getParameter);
        return EncryptionKeyStatusTypeDto.valueOf(EncryptionKeyStatusType.fromValue(dataObject.getValue()).name());
    }
}

19 Source : DeviceChannelsHelper.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced DeviceChannelsHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeviceChannelsHelper.clreplaced);

    private static final int CLreplaced_ID = InterfaceClreplaced.MBUS_CLIENT.id();

    /**
     * The ObisCode for the M-Bus Client Setup exists for a number of channels.
     * DSMR specifies these M-Bus Client Setup channels as values from 1..4.
     */
    private static final String OBIS_CODE_TEMPLATE = "0.%d.24.1.0.255";

    private static final int NUMBER_OF_ATTRIBUTES_MBUS_CLIENT = 5;

    private static final int INDEX_PRIMARY_ADDRESS = 0;

    private static final int INDEX_IDENTIFICATION_NUMBER = 1;

    private static final int INDEX_MANUFACTURER_ID = 2;

    private static final int INDEX_VERSION = 3;

    private static final int INDEX_DEVICE_TYPE = 4;

    private static final short FIRST_CHANNEL = 1;

    private static final short NR_OF_CHANNELS = 4;

    private final DlmsHelper dlmsHelper;

    @Autowired
    public DeviceChannelsHelper(final DlmsHelper dlmsHelper) {
        this.dlmsHelper = dlmsHelper;
    }

    public List<ChannelElementValuesDto> findCandidateChannelsForDevice(final DlmsConnectionManager conn, final DlmsDevice device, final MbusChannelElementsDto requestDto) throws ProtocolAdapterException {
        final List<ChannelElementValuesDto> channelElementValuesList = new ArrayList<>();
        for (short channel = FIRST_CHANNEL; channel < FIRST_CHANNEL + NR_OF_CHANNELS; channel++) {
            final List<GetResult> resultList = this.getMBusClientAttributeValues(conn, device, channel);
            final ChannelElementValuesDto channelElementValues = this.makeChannelElementValues(channel, resultList);
            channelElementValuesList.add(channelElementValues);
            if (requestDto != null && FindMatchingChannelHelper.matches(requestDto, channelElementValues)) {
                /*
                 * A complete match for all attributes from the request has been
                 * found. Stop retrieving M-Bus Client Setup attributes for
                 * other channels. Return a list returning the values retrieved
                 * so far and don't retrieve any additional M-Bus Client Setup
                 * data from the device.
                 */
                return channelElementValuesList;
            }
        }
        /*
         * A complete match for all attributes from the request has not been
         * found. The best partial match that has no conflicting attribute
         * values, or the first free channel has to be picked from this list.
         */
        return channelElementValuesList;
    }

    protected List<GetResult> getMBusClientAttributeValues(final DlmsConnectionManager conn, final DlmsDevice device, final short channel) throws ProtocolAdapterException {
        final AttributeAddress[] attrAddresses = this.makeAttributeAddresses(channel);
        conn.getDlmsMessageListener().setDescription("DeviceChannelsHelper, retrieve M-Bus client setup attributes: " + JdlmsObjectToStringUtil.describeAttributes(attrAddresses));
        return this.dlmsHelper.getWithList(conn, device, attrAddresses);
    }

    protected ChannelElementValuesDto makeChannelElementValues(final short channel, final List<GetResult> resultList) throws ProtocolAdapterException {
        final short primaryAddress = this.readShort(resultList, INDEX_PRIMARY_ADDRESS, "primaryAddress");
        final String identificationNumber = this.readIdentificationNumber(resultList, INDEX_IDENTIFICATION_NUMBER, "identificationNumber");
        final String manufacturerIdentification = this.readManufacturerIdentification(resultList, INDEX_MANUFACTURER_ID, "manufacturerIdentification");
        final short version = this.readShort(resultList, INDEX_VERSION, "version");
        final short deviceTypeIdentification = this.readShort(resultList, INDEX_DEVICE_TYPE, "deviceTypeIdentification");
        return new ChannelElementValuesDto(channel, primaryAddress, identificationNumber, manufacturerIdentification, version, deviceTypeIdentification);
    }

    private String readIdentificationNumber(final List<GetResult> resultList, final int index, final String description) throws ProtocolAdapterException {
        final GetResult getResult = resultList.get(index);
        final DataObject resultData = getResult.getResultData();
        if (resultData == null) {
            return null;
        } else {
            final Long identification = this.dlmsHelper.readLong(resultData, description);
            return identification.toString();
        }
    }

    private String readManufacturerIdentification(final List<GetResult> resultList, final int index, final String description) throws ProtocolAdapterException {
        final int manufacturerId = this.readInt(resultList, index, description);
        return ManufacturerId.fromId(manufacturerId).getIdentification();
    }

    private int readInt(final List<GetResult> resultList, final int index, final String description) throws ProtocolAdapterException {
        final Integer value = this.dlmsHelper.readInteger(resultList.get(index), description);
        return value == null ? 0 : value;
    }

    private short readShort(final List<GetResult> resultList, final int index, final String description) throws ProtocolAdapterException {
        final Short value = this.dlmsHelper.readShort(resultList.get(index), description);
        return value == null ? 0 : value;
    }

    private AttributeAddress[] makeAttributeAddresses(final int channel) {
        final AttributeAddress[] attrAddresses = new AttributeAddress[NUMBER_OF_ATTRIBUTES_MBUS_CLIENT];
        final ObisCode obiscode = new ObisCode(String.format(OBIS_CODE_TEMPLATE, channel));
        attrAddresses[INDEX_PRIMARY_ADDRESS] = new AttributeAddress(CLreplaced_ID, obiscode, MbusClientAttribute.PRIMARY_ADDRESS.attributeId());
        attrAddresses[INDEX_IDENTIFICATION_NUMBER] = new AttributeAddress(CLreplaced_ID, obiscode, MbusClientAttribute.IDENTIFICATION_NUMBER.attributeId());
        attrAddresses[INDEX_MANUFACTURER_ID] = new AttributeAddress(CLreplaced_ID, obiscode, MbusClientAttribute.MANUFACTURER_ID.attributeId());
        attrAddresses[INDEX_VERSION] = new AttributeAddress(CLreplaced_ID, obiscode, MbusClientAttribute.VERSION.attributeId());
        attrAddresses[INDEX_DEVICE_TYPE] = new AttributeAddress(CLreplaced_ID, obiscode, MbusClientAttribute.DEVICE_TYPE.attributeId());
        return attrAddresses;
    }

    protected ChannelElementValuesDto writeUpdatedMbus(final DlmsConnectionManager conn, final MbusChannelElementsDto requestDto, final short channel, final Protocol protocol) throws ProtocolAdapterException {
        final DataObjectAttrExecutors dataObjectExecutors = new DataObjectAttrExecutors("CoupleMBusDevice").addExecutor(this.getMbusAttributeExecutor(MbusClientAttribute.IDENTIFICATION_NUMBER, IdentificationNumberFactory.create(protocol).fromLast8Digits(requestDto.getMbusIdentificationNumber()).asDataObject(), channel)).addExecutor(this.getMbusAttributeExecutor(MbusClientAttribute.MANUFACTURER_ID, ManufacturerId.fromIdentification(requestDto.getMbusManufacturerIdentification()).asDataObject(), channel)).addExecutor(this.getMbusAttributeExecutor(MbusClientAttribute.VERSION, DataObject.newUInteger8Data(requestDto.getMbusVersion()), channel)).addExecutor(this.getMbusAttributeExecutor(MbusClientAttribute.DEVICE_TYPE, DataObject.newUInteger8Data(requestDto.getMbusDeviceTypeIdentification()), channel));
        if (requestDto.getPrimaryAddress() != null) {
            dataObjectExecutors.addExecutor(this.getMbusAttributeExecutor(MbusClientAttribute.PRIMARY_ADDRESS, DataObject.newUInteger8Data(requestDto.getPrimaryAddress()), channel));
        }
        conn.getDlmsMessageListener().setDescription(String.format("Write updated MBus attributes to channel %d, set attributes: %s", channel, dataObjectExecutors.describeAttributes()));
        dataObjectExecutors.execute(conn);
        LOGGER.info("Finished coupling the mbus device to the gateway device");
        return new ChannelElementValuesDto(channel, requestDto.getPrimaryAddress(), requestDto.getMbusIdentificationNumber(), requestDto.getMbusManufacturerIdentification(), requestDto.getMbusVersion(), requestDto.getMbusDeviceTypeIdentification());
    }

    private DataObjectAttrExecutor getMbusAttributeExecutor(final MbusClientAttribute attribute, final DataObject value, final short channel) {
        final ObisCode obiscode = new ObisCode(String.format(OBIS_CODE_TEMPLATE, channel));
        final AttributeAddress attributeAddress = new AttributeAddress(CLreplaced_ID, obiscode, attribute.attributeId());
        return new DataObjectAttrExecutor(attribute.attributeName(), attributeAddress, value, CLreplaced_ID, obiscode, attribute.attributeId());
    }

    protected ChannelElementValuesDto findEmptyChannel(final List<ChannelElementValuesDto> channelElementValuesList) {
        for (final ChannelElementValuesDto channelElementValues : channelElementValuesList) {
            if (this.checkChannelIdentificationValues(channelElementValues) && this.checkChannelConfigurationValues(channelElementValues)) {
                return channelElementValues;
            }
        }
        return null;
    }

    /**
     * @return true if all channel elements are 0 or null
     */
    private boolean checkChannelConfigurationValues(final ChannelElementValuesDto channelElementValues) {
        return (channelElementValues.getVersion() == 0) && (channelElementValues.getDeviceTypeIdentification() == 0) && channelElementValues.getManufacturerIdentification() == null;
    }

    /**
     * @return true if all channel elements are 0 or null
     */
    private boolean checkChannelIdentificationValues(final ChannelElementValuesDto channelElementValues) {
        return (channelElementValues.getIdentificationNumber() == null || "00000000".equals(channelElementValues.getIdentificationNumber()) && (channelElementValues.getPrimaryAddress() == 0));
    }

    /*
     * @param channelElementValues
     *
     * @return 0-based offset for the channel as opposed to the channels in
     * ChannelElementValues, where the channels are incremented from
     * FIRST_CHANNEL.
     */
    protected short correctFirstChannelOffset(final ChannelElementValuesDto channelElementValues) {
        return (short) (channelElementValues.getChannel() - FIRST_CHANNEL);
    }
}

19 Source : SynchronizeTimeCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced SynchronizeTimeCommandExecutor extends AbstractCommandExecutor<SynchronizeTimeRequestDto, AccessResultCode> {

    private static final ObisCode LOGICAL_NAME = new ObisCode("0.0.1.0.0.255");

    private static final AttributeAddress ATTRIBUTE_TIME = new AttributeAddress(InterfaceClreplaced.CLOCK.id(), LOGICAL_NAME, ClockAttribute.TIME.attributeId());

    @Autowired
    private DlmsHelper dlmsHelper;

    public SynchronizeTimeCommandExecutor() {
        super(SynchronizeTimeRequestDto.clreplaced);
    }

    @Override
    public SynchronizeTimeRequestDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        return (SynchronizeTimeRequestDto) bundleInput;
    }

    @Override
    public ActionResponseDto asBundleResponse(final AccessResultCode executionResult) throws ProtocolAdapterException {
        this.checkAccessResultCode(executionResult);
        return new ActionResponseDto("Synchronizing time was successful");
    }

    @Override
    public AccessResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final SynchronizeTimeRequestDto synchronizeTimeRequestDto) throws ProtocolAdapterException {
        final DateTime dt = DateTime.now();
        final DataObject time = this.dlmsHelper.asDataObject(dt, synchronizeTimeRequestDto.getDeviation(), synchronizeTimeRequestDto.isDst());
        final SetParameter setParameter = new SetParameter(ATTRIBUTE_TIME, time);
        conn.getDlmsMessageListener().setDescription("SynchronizeTime to " + dt + ", set attribute: " + JdlmsObjectToStringUtil.describeAttributes(ATTRIBUTE_TIME));
        try {
            return conn.getConnection().set(setParameter);
        } catch (final IOException e) {
            throw new ConnectionException(e);
        }
    }
}

19 Source : SetSpecialDaysCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced SetSpecialDaysCommandExecutor extends AbstractCommandExecutor<List<SpecialDayDto>, AccessResultCode> {

    private static final int CLreplaced_ID = 11;

    private static final ObisCode OBIS_CODE = new ObisCode("0.0.11.0.0.255");

    private static final int ATTRIBUTE_ID = 2;

    @Autowired
    private DlmsHelper dlmsHelper;

    public SetSpecialDaysCommandExecutor() {
        super(SpecialDaysRequestDataDto.clreplaced);
    }

    @Override
    public List<SpecialDayDto> fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        final SpecialDaysRequestDataDto specialDaysRequestDataDto = (SpecialDaysRequestDataDto) bundleInput;
        return specialDaysRequestDataDto.getSpecialDays();
    }

    @Override
    public ActionResponseDto asBundleResponse(final AccessResultCode executionResult) throws ProtocolAdapterException {
        this.checkAccessResultCode(executionResult);
        return new ActionResponseDto("Set special days was successful");
    }

    @Override
    public AccessResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final List<SpecialDayDto> specialDays) throws ProtocolAdapterException {
        final StringBuilder specialDayData = new StringBuilder();
        final List<DataObject> specialDayEntries = new ArrayList<>();
        int i = 0;
        for (final SpecialDayDto specialDay : specialDays) {
            specialDayData.append(", ").append(specialDay.getDayId()).append(" => ").append(specialDay.getSpecialDayDate());
            final List<DataObject> specDayEntry = new ArrayList<>();
            specDayEntry.add(DataObject.newUInteger16Data(i));
            specDayEntry.add(this.dlmsHelper.asDataObject(specialDay.getSpecialDayDate()));
            specDayEntry.add(DataObject.newUInteger8Data((short) specialDay.getDayId()));
            final DataObject dayStruct = DataObject.newStructureData(specDayEntry);
            specialDayEntries.add(dayStruct);
            i += 1;
        }
        final AttributeAddress specialDaysTableEntries = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID);
        final DataObject entries = DataObject.newArrayData(specialDayEntries);
        final SetParameter request = new SetParameter(specialDaysTableEntries, entries);
        final String specialDayValues;
        if (specialDayData.length() == 0) {
            specialDayValues = "";
        } else {
            specialDayValues = ", values [" + specialDayData.substring(2) + "]";
        }
        conn.getDlmsMessageListener().setDescription("SetSpecialDays" + specialDayValues + ", set attribute: " + JdlmsObjectToStringUtil.describeAttributes(specialDaysTableEntries));
        try {
            return conn.getConnection().set(request);
        } catch (final IOException e) {
            throw new ConnectionException(e);
        }
    }
}

19 Source : SetActivityCalendarCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced SetActivityCalendarCommandExecutor extends AbstractCommandExecutor<ActivityCalendarDto, AccessResultCode> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SetActivityCalendarCommandExecutor.clreplaced);

    private static final int CLreplaced_ID = 20;

    private static final ObisCode OBIS_CODE = new ObisCode("0.0.13.0.0.255");

    private static final int ATTRIBUTE_ID_CALENDAR_NAME_PreplacedIVE = 6;

    private static final int ATTRIBUTE_ID_SEASON_PROFILE_PreplacedIVE = 7;

    private static final int ATTRIBUTE_ID_WEEK_PROFILE_TABLE_PreplacedIVE = 8;

    private static final int ATTRIBUTE_ID_DAY_PROFILE_TABLE_PreplacedIVE = 9;

    @Autowired
    private ConfigurationMapper configurationMapper;

    @Autowired
    private SetActivityCalendarCommandActivationExecutor setActivityCalendarCommandActivationExecutor;

    @Autowired
    private DlmsHelper dlmsHelper;

    public SetActivityCalendarCommandExecutor() {
        super(ActivityCalendarDataDto.clreplaced);
    }

    @Override
    public ActivityCalendarDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        final ActivityCalendarDataDto activityCalendarDataDto = (ActivityCalendarDataDto) bundleInput;
        return activityCalendarDataDto.getActivityCalendar();
    }

    @Override
    public ActionResponseDto asBundleResponse(final AccessResultCode executionResult) throws ProtocolAdapterException {
        this.checkAccessResultCode(executionResult);
        return new ActionResponseDto("Set Activity Calendar Result is OK");
    }

    @Override
    public AccessResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final ActivityCalendarDto activityCalendar) throws ProtocolAdapterException {
        LOGGER.debug("SetActivityCalendarCommandExecutor.execute {} called", activityCalendar.getCalendarName());
        final List<SeasonProfileDto> seasonProfileList = activityCalendar.getSeasonProfileList();
        final Set<WeekProfileDto> weekProfileSet = this.getWeekProfileSet(seasonProfileList);
        final Set<DayProfileDto> dayProfileSet = this.getDayProfileSet(weekProfileSet);
        final DataObjectAttrExecutors dataObjectExecutors = new DataObjectAttrExecutors("SetActivityCalendar").addExecutor(this.getCalendarNameExecutor(activityCalendar)).addExecutor(this.getSeasonProfileExecutor(seasonProfileList)).addExecutor(this.getWeekProfileTableExecutor(weekProfileSet)).addExecutor(this.getDayProfileTablePreplacediveExecutor(dayProfileSet));
        conn.getDlmsMessageListener().setDescription("SetActivityCalendar for calendar " + activityCalendar.getCalendarName() + ", set attributes: " + dataObjectExecutors.describeAttributes());
        dataObjectExecutors.execute(conn);
        LOGGER.info("Finished setting the preplacedive activity calendar");
        // Now activate the newly set activity calendar
        // In case of an exception include the activity calendar set here above
        // in the exception to throw
        try {
            this.setActivityCalendarCommandActivationExecutor.execute(conn, device, null);
            LOGGER.info("Finished activating the preplacedive to the active activity calendar");
        } catch (final ProtocolAdapterException e) {
            final StringBuilder message = new StringBuilder();
            for (final DataObjectAttrExecutor executor : dataObjectExecutors.getDataObjectAttrExecutorList()) {
                message.append(executor.createRequestAndResultCodeInfo());
            }
            throw new ProtocolAdapterException(e.getMessage() + message, e);
        }
        return AccessResultCode.SUCCESS;
    }

    private DataObjectAttrExecutor getCalendarNameExecutor(final ActivityCalendarDto activityCalendar) {
        final AttributeAddress calendarNamePreplacedive = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_CALENDAR_NAME_PreplacedIVE);
        final DataObject value = DataObject.newOctetStringData(activityCalendar.getCalendarName().getBytes());
        return new DataObjectAttrExecutor("CALENDARNAME", calendarNamePreplacedive, value, CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_CALENDAR_NAME_PreplacedIVE);
    }

    private DataObjectAttrExecutor getDayProfileTablePreplacediveExecutor(final Set<DayProfileDto> dayProfileSet) {
        final AttributeAddress dayProfileTablePreplacedive = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_DAY_PROFILE_TABLE_PreplacedIVE);
        final DataObject dayArray = DataObject.newArrayData(this.configurationMapper.mapAsList(dayProfileSet, DataObject.clreplaced));
        LOGGER.info("DayProfileTablePreplacedive to set is: {}", this.dlmsHelper.getDebugInfo(dayArray));
        return new DataObjectAttrExecutor("DAYS", dayProfileTablePreplacedive, dayArray, CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_DAY_PROFILE_TABLE_PreplacedIVE);
    }

    /**
     * get all day profiles from all the week profiles
     */
    private Set<DayProfileDto> getDayProfileSet(final Set<WeekProfileDto> weekProfileSet) {
        final Set<DayProfileDto> dayProfileHashSet = new HashSet<>();
        for (final WeekProfileDto weekProfile : weekProfileSet) {
            dayProfileHashSet.addAll(weekProfile.getAllDaysAsList());
        }
        return dayProfileHashSet;
    }

    private DataObjectAttrExecutor getWeekProfileTableExecutor(final Set<WeekProfileDto> weekProfileSet) {
        final AttributeAddress weekProfileTablePreplacedive = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_WEEK_PROFILE_TABLE_PreplacedIVE);
        final DataObject weekArray = DataObject.newArrayData(this.configurationMapper.mapAsList(weekProfileSet, DataObject.clreplaced));
        LOGGER.info("WeekProfileTablePreplacedive to set is: {}", this.dlmsHelper.getDebugInfo(weekArray));
        return new DataObjectAttrExecutor("WEEKS", weekProfileTablePreplacedive, weekArray, CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_WEEK_PROFILE_TABLE_PreplacedIVE);
    }

    private Set<WeekProfileDto> getWeekProfileSet(final List<SeasonProfileDto> seasonProfileList) {
        // Use HashSet to ensure that unique WeekProfiles are returned. For
        // there can be duplicates.
        final Set<WeekProfileDto> weekProfileSet = new HashSet<>();
        for (final SeasonProfileDto seasonProfile : seasonProfileList) {
            weekProfileSet.add(seasonProfile.getWeekProfile());
        }
        return weekProfileSet;
    }

    private DataObjectAttrExecutor getSeasonProfileExecutor(final List<SeasonProfileDto> seasonProfileList) {
        final AttributeAddress seasonProfilePreplacedive = new AttributeAddress(CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_SEASON_PROFILE_PreplacedIVE);
        final DataObject seasonsArray = DataObject.newArrayData(this.configurationMapper.mapAsList(seasonProfileList, DataObject.clreplaced));
        LOGGER.info("SeasonProfilePreplacedive to set is: {}", this.dlmsHelper.getDebugInfo(seasonsArray));
        return new DataObjectAttrExecutor("SEASONS", seasonProfilePreplacedive, seasonsArray, CLreplaced_ID, OBIS_CODE, ATTRIBUTE_ID_SEASON_PROFILE_PreplacedIVE);
    }
}

19 Source : SetActivityCalendarCommandActivationExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced SetActivityCalendarCommandActivationExecutor extends AbstractCommandExecutor<Void, MethodResultCode> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SetActivityCalendarCommandActivationExecutor.clreplaced);

    private static final int CLreplaced_ID = 20;

    private static final ObisCode OBIS_CODE = new ObisCode("0.0.13.0.0.255");

    private static final int METHOD_ID_ACTIVATE_PreplacedIVE_CALENDAR = 1;

    @Override
    public MethodResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final Void v) throws ProtocolAdapterException {
        LOGGER.info("ACTIVATING PreplacedIVE CALENDAR");
        final MethodParameter method = new MethodParameter(CLreplaced_ID, OBIS_CODE, METHOD_ID_ACTIVATE_PreplacedIVE_CALENDAR, DataObject.newInteger32Data(0));
        conn.getDlmsMessageListener().setDescription("SetActivityCalendarActivation, call method: " + JdlmsObjectToStringUtil.describeMethod(method));
        final MethodResult methodResultCode;
        try {
            methodResultCode = conn.getConnection().action(method);
        } catch (final IOException e) {
            throw new ConnectionException(e);
        }
        if (!MethodResultCode.SUCCESS.equals(methodResultCode.getResultCode())) {
            throw new ProtocolAdapterException("Activating the activity calendar failed. MethodResult is: " + methodResultCode.getResultCode() + " ClreplacedId: " + CLreplaced_ID + " obisCode: " + OBIS_CODE + " method id: " + METHOD_ID_ACTIVATE_PreplacedIVE_CALENDAR);
        }
        return MethodResultCode.SUCCESS;
    }
}

19 Source : SetAlarmNotificationsCommandExecutor.java
with Apache License 2.0
from OSGP

@Component()
public clreplaced SetAlarmNotificationsCommandExecutor extends AbstractCommandExecutor<AlarmNotificationsDto, AccessResultCode> {

    private static final Logger LOGGER = LoggerFactory.getLogger(SetAlarmNotificationsCommandExecutor.clreplaced);

    private static final int NUMBER_OF_BITS_IN_ALARM_FILTER = 32;

    private final AlarmHelperService alarmHelperService = new AlarmHelperService();

    private final DlmsObjectConfigService dlmsObjectConfigService;

    @Autowired
    public SetAlarmNotificationsCommandExecutor(final DlmsObjectConfigService dlmsObjectConfigService) {
        super(SetAlarmNotificationsRequestDto.clreplaced);
        this.dlmsObjectConfigService = dlmsObjectConfigService;
    }

    @Override
    public AlarmNotificationsDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException {
        this.checkActionRequestType(bundleInput);
        final SetAlarmNotificationsRequestDto setAlarmNotificationsRequestDto = (SetAlarmNotificationsRequestDto) bundleInput;
        return setAlarmNotificationsRequestDto.getAlarmNotifications();
    }

    @Override
    public ActionResponseDto asBundleResponse(final AccessResultCode executionResult) throws ProtocolAdapterException {
        this.checkAccessResultCode(executionResult);
        return new ActionResponseDto("Set alarm notifications was successful");
    }

    @Override
    public AccessResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final AlarmNotificationsDto alarmNotifications) throws ProtocolAdapterException {
        try {
            final AttributeAddress alarmFilterValue = this.getAttributeAddress(device);
            final AlarmNotificationsDto alarmNotificationsOnDevice = this.retrieveCurrentAlarmNotifications(conn, alarmFilterValue);
            LOGGER.info("Alarm Filter on device before setting notifications: {}", alarmNotificationsOnDevice);
            final long alarmFilterLongValueOnDevice = this.alarmFilterLongValue(alarmNotificationsOnDevice);
            final long updatedAlarmFilterLongValue = this.calculateAlarmFilterLongValue(alarmNotificationsOnDevice, alarmNotifications);
            if (alarmFilterLongValueOnDevice == updatedAlarmFilterLongValue) {
                return AccessResultCode.SUCCESS;
            }
            LOGGER.info("Modified Alarm Filter long value for device: {}", updatedAlarmFilterLongValue);
            return this.writeUpdatedAlarmNotifications(conn, updatedAlarmFilterLongValue, alarmFilterValue);
        } catch (final IOException e) {
            throw new ConnectionException(e);
        }
    }

    private AlarmNotificationsDto retrieveCurrentAlarmNotifications(final DlmsConnectionManager conn, final AttributeAddress alarmFilterValue) throws IOException, ProtocolAdapterException {
        conn.getDlmsMessageListener().setDescription("SetAlarmNotifications retrieve current value, retrieve attribute: " + JdlmsObjectToStringUtil.describeAttributes(alarmFilterValue));
        LOGGER.info("Retrieving current alarm filter by issuing get request for for address: {}", alarmFilterValue);
        final GetResult getResult = conn.getConnection().get(alarmFilterValue);
        if (getResult == null) {
            throw new ProtocolAdapterException("No GetResult received while retrieving current alarm filter.");
        }
        return this.alarmNotifications(getResult.getResultData());
    }

    private AccessResultCode writeUpdatedAlarmNotifications(final DlmsConnectionManager conn, final long alarmFilterLongValue, final AttributeAddress alarmFilterValue) throws IOException {
        final DataObject value = DataObject.newUInteger32Data(alarmFilterLongValue);
        final SetParameter setParameter = new SetParameter(alarmFilterValue, value);
        conn.getDlmsMessageListener().setDescription("SetAlarmNotifications write updated value " + alarmFilterLongValue + ", set attribute: " + JdlmsObjectToStringUtil.describeAttributes(alarmFilterValue));
        return conn.getConnection().set(setParameter);
    }

    private AlarmNotificationsDto alarmNotifications(final DataObject alarmFilter) throws ProtocolAdapterException {
        if (alarmFilter == null) {
            throw new ProtocolAdapterException("DataObject expected to contain an alarm filter is null.");
        }
        if (!alarmFilter.isNumber()) {
            throw new ProtocolAdapterException("DataObject isNumber is expected to be true for alarm notifications.");
        }
        if (!(alarmFilter.getValue() instanceof Number)) {
            throw new ProtocolAdapterException("Value in DataObject is not a java.lang.Number: " + alarmFilter.getValue().getClreplaced().getName());
        }
        final Number alarmFilterValue = alarmFilter.getValue();
        return this.alarmNotifications(alarmFilterValue.longValue());
    }

    private long calculateAlarmFilterLongValue(final AlarmNotificationsDto alarmNotificationsOnDevice, final AlarmNotificationsDto alarmNotificationsToSet) {
        /*
         * Create a new (modifiable) set of alarm notifications, based on the
         * notifications to set.
         *
         * Next, add all notifications on the device. These will only really be
         * added to the new set of notifications if it did not contain a
         * notification for the alarm type for which the notification is added.
         *
         * This works because of the specification of addAll for the set,
         * claiming elements will only be added if not already present, and the
         * definition of equals on the AlarmNotification, ensuring only a single
         * setting per AlarmType.
         */
        final Set<AlarmNotificationDto> notificationsToSet = new TreeSet<>(alarmNotificationsToSet.getAlarmNotificationsSet());
        notificationsToSet.addAll(alarmNotificationsOnDevice.getAlarmNotificationsSet());
        return this.alarmFilterLongValue(new AlarmNotificationsDto(notificationsToSet));
    }

    private AlarmNotificationsDto alarmNotifications(final long alarmFilterLongValue) {
        final BitSet bitSet = BitSet.valueOf(new long[] { alarmFilterLongValue });
        final Set<AlarmNotificationDto> notifications = new TreeSet<>();
        final AlarmTypeDto[] alarmTypes = AlarmTypeDto.values();
        for (final AlarmTypeDto alarmType : alarmTypes) {
            final boolean enabled = bitSet.get(this.alarmHelperService.getAlarmRegisterBitIndexPerAlarmType().get(alarmType));
            notifications.add(new AlarmNotificationDto(alarmType, enabled));
        }
        return new AlarmNotificationsDto(notifications);
    }

    private long alarmFilterLongValue(final AlarmNotificationsDto alarmNotifications) {
        final BitSet bitSet = new BitSet(NUMBER_OF_BITS_IN_ALARM_FILTER);
        for (final AlarmNotificationDto alarmNotification : alarmNotifications.getAlarmNotificationsSet()) {
            bitSet.set(this.alarmHelperService.getAlarmRegisterBitIndexPerAlarmType().get(alarmNotification.getAlarmType()), alarmNotification.isEnabled());
        }
        /*
         * If no alarmType has isEnabled is true in the request, bitSet stays
         * empty. Value 0 should then be returned because nothing has to be
         * enabled. Then the alarmFilter value to write to the device will be
         * calculated with this input.
         */
        if (bitSet.isEmpty()) {
            return 0L;
        } else {
            return bitSet.toLongArray()[0];
        }
    }

    private AttributeAddress getAttributeAddress(final DlmsDevice device) throws ProtocolAdapterException {
        final Optional<AttributeAddress> alarmFilterValueOpt = this.dlmsObjectConfigService.findAttributeAddress(device, DlmsObjectType.ALARM_FILTER, null);
        return alarmFilterValueOpt.orElseThrow(() -> new ProtocolAdapterException("Could not find any configuration for " + DlmsObjectType.ALARM_FILTER));
    }
}

19 Source : UnassignVnf.java
with Apache License 2.0
from onap

@Component()
public clreplaced UnreplacedignVnf {

    private static final Logger logger = LoggerFactory.getLogger(UnreplacedignVnf.clreplaced);

    @Autowired
    private ExceptionBuilder exceptionUtil;

    @Autowired
    private ExtractPojosForBB extractPojosForBB;

    @Autowired
    private AAIInstanceGroupResources aaiInstanceGroupResources;

    @Autowired
    private AAIObjectInstanceNameGenerator aaiObjectInstanceNameGenerator;

    /**
     * BPMN access method to deleting instanceGroup in AAI.
     *
     * It will extract the vnf from BBobject ,It will get the instance group from the vnf and add it into a list.
     *
     * Then iterate that list and check the ModelInfoInstanceGroup type.
     *
     * Then it will delete that.
     *
     * @param execution
     */
    public void deleteInstanceGroups(BuildingBlockExecution execution) {
        try {
            GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
            List<InstanceGroup> instanceGroups = vnf.getInstanceGroups();
            for (InstanceGroup instanceGroup : instanceGroups) {
                if (ModelInfoInstanceGroup.TYPE_VNFC.equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) {
                    aaiInstanceGroupResources.deleteInstanceGroup(instanceGroup);
                }
            }
        } catch (Exception ex) {
            logger.error("Exception occurred in UnreplacedignVnf deleteInstanceGroups", ex);
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
        }
    }
}

19 Source : CatalogDbClientPortChanger.java
with Apache License 2.0
from onap

@Component()
public clreplaced CatalogDbClientPortChanger extends CatalogDbClient {

    public String wiremockPort;

    CatalogDbClientPortChanger() {
    }

    CatalogDbClientPortChanger(String baseUri, String auth, String wiremockPort) {
        super(baseUri, auth);
        this.wiremockPort = wiremockPort;
    }

    protected URI getUri(String template) {
        URI uri = URI.create(template);
        String path = uri.getPath();
        String prefix = "http://localhost:" + wiremockPort;
        String query = uri.getQuery();
        return URI.create(prefix + path + (query == null || query.isEmpty() ? "" : "?" + query));
    }
}

19 Source : IdGenerator.java
with Apache License 2.0
from MissThee

@Component()
public clreplaced IdGenerator {

    /**
     * 起始的时间戳
     */
    // Tue Oct 22 10:41:44 CST 2019 ;
    private final static long START_TIMESTAMP = 1571712039678L;

    private final static long DATA_CENTER_ID = 0;

    private final static long MACHINE_ID = 0;

    /**
     * 每一部分占用的位数
     */
    // 数据中心占用的位数
    private final static long DATA_CENTER_BIT = 5;

    // 机器标识占用的位数
    private final static long MACHINE_BIT = 5;

    // 序列号占用的位数
    private final static long SEQUENCE_BIT = 12;

    /**
     * 每一部分的最大值
     */
    private final static long MAX_DATA_CENTER_NUM = ~(-1L << DATA_CENTER_BIT);

    private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);

    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);

    /**
     * 每一部分向左的位移
     */
    private final static long MACHINE_ID_LEFT = SEQUENCE_BIT;

    private final static long DATA_CENTER_ID_LEFT = SEQUENCE_BIT + MACHINE_BIT;

    private final static long START_TIMESTAMP_LEFT = DATA_CENTER_ID_LEFT + DATA_CENTER_BIT;

    // 序列号
    private long sequence = 0L;

    // 上一次时间戳
    private long lastStamp = -1L;

    public IdGenerator() {
        if (DATA_CENTER_ID > MAX_DATA_CENTER_NUM || DATA_CENTER_ID < 0) {
            throw new IllegalArgumentException("DATA_CENTER_ID can't be greater than MAX_DATA_CENTER_NUM or less than 0");
        }
        if (MACHINE_ID > MAX_MACHINE_NUM || MACHINE_ID < 0) {
            throw new IllegalArgumentException("MACHINE_ID can't be greater than MAX_MACHINE_NUM or less than 0");
        }
    }

    /**
     * 产生下一个ID
     */
    public synchronized long nextId() {
        long newStamp = getNewStamp();
        if (newStamp < lastStamp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }
        if (newStamp == lastStamp) {
            // 相同毫秒内,序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                newStamp = getNextMill();
            }
        } else {
            // 不同毫秒内,序列号置为0
            sequence = 0L;
        }
        lastStamp = newStamp;
        return // 时间戳部分
        (newStamp - START_TIMESTAMP) << START_TIMESTAMP_LEFT | // 数据中心部分
        DATA_CENTER_ID << DATA_CENTER_ID_LEFT | // 机器标识部分
        MACHINE_ID << MACHINE_ID_LEFT | // 序列号部分
        sequence;
    }

    private long getNextMill() {
        long mill = getNewStamp();
        while (mill <= lastStamp) {
            mill = getNewStamp();
        }
        return mill;
    }

    private long getNewStamp() {
        return System.currentTimeMillis();
    }
}

19 Source : MessageProducerSpringTemplate.java
with Apache License 2.0
from kiegroup

@org.springframework.stereotype.Component()
public clreplaced MessageProducer extends AbstractMessageProducer<$DataType$, $DataEventType$> {

    @org.springframework.beans.factory.annotation.Autowired()
    MessageProducer(CloudEventEmitter emitter, ConfigBean configBean) {
        super(emitter, new DefaultEventMarshaller(), "$Trigger$", configBean.useCloudEvents());
    }

    protected $DataEventType$ dataEventTypeConstructor($DataType$ e, KogitoProcessInstance pi, String trigger) {
        return new $DataEventType$(trigger, "", e, pi.getStringId(), pi.getParentProcessInstanceStringId(), pi.getRootProcessInstanceId(), pi.getProcessId(), pi.getRootProcessId(), String.valueOf(pi.getState()), pi.getReferenceId());
    }
}

19 Source : MessageConsumerSpringTemplate.java
with Apache License 2.0
from kiegroup

@org.springframework.stereotype.Component()
public clreplaced $Type$MessageConsumer extends AbstractMessageConsumer<$Type$, $DataType$, $DataEventType$> {

    @org.springframework.beans.factory.annotation.Autowired()
    $Type$MessageConsumer(Application application, @org.springframework.beans.factory.annotation.Qualifier("$ProcessName$") Process<$Type$> process, ConfigBean configBean, @org.springframework.beans.factory.annotation.Qualifier(KogitoEventStreams.PUBLISHER) Publisher<String> eventPublisher) {
        super(application, process, $DataType$.clreplaced, $DataEventType$.clreplaced, "$Trigger$", new DefaultEventConsumerFactory(), configBean.useCloudEvents());
        Flux.from(eventPublisher).subscribe(this::consume);
    }

    protected $Type$ eventToModel($DataType$ event) {
        $Type$ model = new $Type$();
        model.set$DataType$(event);
        return model;
    }
}

19 Source : SpringTopicsInformationResource.java
with Apache License 2.0
from kiegroup

@RestController
@RequestMapping("/messaging/topics")
@Component()
public clreplaced SpringTopicsInformationResource extends AbstractTopicsInformationResource {

    @Autowired
    public SpringTopicsInformationResource(TopicDiscovery topicDiscovery, List<CloudEventMeta> cloudEventMetaIterable) {
        setup(topicDiscovery, cloudEventMetaIterable);
    }

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEnreplacedy<List<Topic>> getTopics() {
        return ResponseEnreplacedy.ok(getTopicList());
    }
}

19 Source : Autor.java
with The Unlicense
from diegopacheco

@Component()
public clreplaced Autor {

    private Integer id;

    private String nome;

    @Autowired
    private Livro livro;

    public Autor() {
        id = 0;
        nome = "Sem nome";
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Livro getLivro() {
        return livro;
    }

    public void setLivro(Livro livro) {
        this.livro = livro;
    }

    @Override
    public String toString() {
        return "id: " + id + ",Nome: " + nome + ", Livro: " + livro;
    }
}

19 Source : VanillaItemTypeProvider_v1_12_2.java
with MIT License
from CleanstoneMC

@Component()
public clreplaced VanillaItemTypeProvider_v1_12_2 {

    private final MaterialRegistry materialRegistry;

    public VanillaItemTypeProvider_v1_12_2(MaterialRegistry materialRegistry) {
        this.materialRegistry = materialRegistry;
    }

    @PostConstruct
    public void registerVanillaItemTypes() {
        Arrays.stream(VanillaItemType_v1_12_2.values()).forEach(materialRegistry::registerItemType);
    }
}