Example usage for org.springframework.util Assert state

List of usage examples for org.springframework.util Assert state

Introduction

In this page you can find the example usage for org.springframework.util Assert state.

Prototype

public static void state(boolean expression, Supplier<String> messageSupplier) 

Source Link

Document

Assert a boolean expression, throwing an IllegalStateException if the expression evaluates to false .

Usage

From source file:com.joshlong.esb.springintegration.modules.services.amazon.sqs.AmazonSQS2Client.java

private String send(QueueService queueService, String queueId, String msgPayload) throws Exception {
    Assert.state(!StringUtils.isEmpty(queueId), "the 'queueId' can't be empty!");

    MessageQueue messageQueue = getAndCacheMessageQueue(queueService, queueId);
    logger.debug("obtained messageQueue " + messageQueue.getUrl());

    String msgId = messageQueue.sendMessage(msgPayload);
    logger.debug(String.format("sent message '%s' on messagesNotYetRecieved ID '%s'", msgId, queueId));

    return msgId;
}

From source file:lcn.module.batch.core.launch.support.CommandLineRunner.java

/**
 * Batch Job? ./*from   w w w.java2  s  .  co m*/
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        context = new ClassPathXmlApplicationContext(jobPath);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        // Batch Job? .
        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // ? Batch Job? ? abandon .
        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // Batch Job? .
        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("CommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        CommandLineRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:egovframework.rte.bat.core.launch.support.EgovCommandLineRunner.java

/**
 * Batch Job? ./*from  www  .j av a2 s . co  m*/
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        context = new ClassPathXmlApplicationContext(jobPath);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        // Batch Job? .
        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // ? Batch Job? ? abandon .
        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // Batch Job? .
        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("EgovCommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        EgovCommandLineRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java

/**
 * {@inheritDoc}/*from   w w w .j av a 2  s  .com*/
 */
@Override
public OAuth2Authentication loadAuthentication(final String accessToken)
        throws AuthenticationException, InvalidTokenException {
    final long start = System.nanoTime();
    try {
        final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add(TOKEN_NAME_KEY, accessToken);
        formData.add(CLIENT_ID_KEY, this.clientId);
        formData.add(CLIENT_SECRET_KEY, this.clientSecret);
        formData.add(GRANT_TYPE_KEY, GRANT_TYPE);

        final Map<String, Object> map = this.postForMap(this.checkTokenEndpointUrl, formData);

        if (map.containsKey(ERROR_KEY)) {
            final String error = map.get(ERROR_KEY).toString();
            log.debug("Validating the token produced an error: {}", error);
            throw new InvalidTokenException(error);
        }

        Assert.state(map.containsKey(CLIENT_ID_KEY), "Client id must be present in response from auth server");
        Assert.state(map.containsKey(SCOPE_KEY), "No scopes included in response from authentication server");
        this.convertScopes(map);
        final OAuth2Authentication authentication = this.converter.extractAuthentication(map);
        log.info("User {} authenticated with authorities {}", authentication.getPrincipal(),
                authentication.getAuthorities());
        return authentication;
    } finally {
        final long finished = System.nanoTime();
        this.authenticationTimer.record(finished - start, TimeUnit.NANOSECONDS);
    }
}

From source file:com.github.springtestdbunit.DbUnitRunner.java

private org.dbunit.operation.DatabaseOperation getDbUnitDatabaseOperation(DbUnitTestContext testContext,
        DatabaseOperation operation, DatabaseOperation lastOperation) {
    if ((operation == DatabaseOperation.CLEAN_INSERT) && (lastOperation == DatabaseOperation.CLEAN_INSERT)) {
        operation = DatabaseOperation.INSERT;
    }/*from   ww  w.j  ava 2  s.co m*/
    org.dbunit.operation.DatabaseOperation databaseOperation = testContext.getDatbaseOperationLookup()
            .get(operation);
    Assert.state(databaseOperation != null, "The databse operation " + operation + " is not supported");
    return databaseOperation;
}

From source file:org.cleverbus.component.asynchchild.AsynchChildProducer.java

/**
 * Gets {@link ProducerTemplate} default instance from Camel Context.
 *
 * @return ProducerTemplate//  www .  j  a  va2 s.  c  o  m
 * @throws IllegalStateException when there is no ProducerTemplate
 */
protected ProducerTemplate getProducerTemplate() {
    if (!isStarted() && !isStarting()) {
        throw new IllegalStateException(getClass().getName() + " is not started so far!");
    }

    Set<ProducerTemplate> templates = getEndpoint().getCamelContext().getRegistry()
            .findByType(ProducerTemplate.class);
    Assert.state(templates.size() >= 1, "ProducerTemplate must be at least one.");

    return templates.iterator().next();
}

From source file:de.escalon.hypermedia.spring.AffordanceBuilder.java

/**
 * Builds affordance with one or multiple rels which must have been defined previously using {@link #rel(String)} or
 * {@link #reverseRel(String, String)}. <p>The motivation for multiple rels is this statement in the web linking
 * rfc-5988: &quot;Note that link-values can convey multiple links between the same target and context IRIs; for
 * example:</p>//from   w ww. j av a  2 s . c  om
 * <pre>
 * Link: &lt;http://example.org/&gt;
 *       rel="start http://example.net/relation/other"
 * </pre>
 * Here, the link to 'http://example.org/' has the registered relation type 'start' and the extension relation type
 * 'http://example.net/relation/other'.&quot;
 *
 * @return affordance
 * @see <a href="https://tools.ietf.org/html/rfc5988#section-5.5">Web Linking Examples</a>
 */
public Affordance build() {
    Assert.state(!(rels.isEmpty() && reverseRels.isEmpty()),
            "no rels or reverse rels found, call rel() or rev() before building the affordance");
    final Affordance affordance;
    affordance = new Affordance(new PartialUriTemplate(this.toString()), actionDescriptors,
            rels.toArray(new String[rels.size()]));
    for (Map.Entry<String, List<String>> linkParamEntry : linkParams.entrySet()) {
        final List<String> values = linkParamEntry.getValue();
        for (String value : values) {
            affordance.addLinkParam(linkParamEntry.getKey(), value);
        }
    }
    for (String reverseRel : reverseRels) {
        affordance.addRev(reverseRel);
    }
    affordance.setCollectionHolder(collectionHolder);
    return affordance;
}

From source file:com.hundsun.sso.controller.OAuthRestController.java

@Override
public void afterPropertiesSet() throws Exception {

    Assert.state(clientDetailsService != null, "ClientDetailsService must be provided");
    Assert.state(authenticationManager != null, "AuthenticationManager must be provided");

    oAuth2RequestFactory = new DefaultOAuth2RequestFactory(clientDetailsService);
}

From source file:com.dexcoder.dal.spring.mapper.JdbcRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData/*from w  w  w  .j a  v  a2s.  com*/
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        String field = lowerCaseName(column.replaceAll(" ", ""));
        PropertyDescriptor pd = this.mappedFields.get(field);
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (rowNumber == 0 && logger.isDebugEnabled()) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type ["
                            + ClassUtils.getQualifiedName(pd.getPropertyType()) + "]");
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException ex) {
                    if (value == null && this.primitivesDefaultedForNullValue) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Intercepted TypeMismatchException for row " + rowNumber
                                    + " and column '" + column + "' with null value when setting property '"
                                    + pd.getName() + "' of type ["
                                    + ClassUtils.getQualifiedName(pd.getPropertyType()) + "] on object: "
                                    + mappedObject, ex);
                        }
                    } else {
                        throw ex;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column '" + column + "' to property '" + pd.getName() + "'", ex);
            }
        } else {
            // No PropertyDescriptor found
            if (rowNumber == 0 && logger.isDebugEnabled()) {
                logger.debug("No property found for column '" + column + "' mapped to field '" + field + "'");
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException(
                "Given ResultSet does not contain all fields " + "necessary to populate object of class ["
                        + this.mappedClass.getName() + "]: " + this.mappedProperties);
    }

    return mappedObject;
}