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:org.springframework.batch.item.database.AbstractCursorItemReader.java

/**
 * Execute the statement to open the cursor.
 *//*from w  ww  .j  a v a  2 s  .c o  m*/
@Override
protected void doOpen() throws Exception {

    Assert.state(!initialized, "Stream is already initialized.  Close before re-opening.");
    Assert.isNull(rs, "ResultSet still open!  Close before re-opening.");

    initializeConnection();
    openCursor(con);
    initialized = true;

}

From source file:org.springframework.batch.item.database.AbstractCursorItemReader.java

protected void initializeConnection() {
    Assert.state(getDataSource() != null, "DataSource must not be null.");

    try {/*from  w ww  .  ja v  a2s.  co m*/
        if (useSharedExtendedConnection) {
            if (!(getDataSource() instanceof ExtendedConnectionDataSourceProxy)) {
                throw new InvalidDataAccessApiUsageException(
                        "You must use a ExtendedConnectionDataSourceProxy for the dataSource when "
                                + "useSharedExtendedConnection is set to true.");
            }
            this.con = DataSourceUtils.getConnection(dataSource);
            ((ExtendedConnectionDataSourceProxy) dataSource).startCloseSuppression(this.con);
        } else {
            this.con = dataSource.getConnection();
        }
    } catch (SQLException se) {
        close();
        throw getExceptionTranslator().translate("Executing query", getSql(), se);
    }
}

From source file:org.springframework.batch.item.database.AbstractPagingItemReader.java

@Override
protected void doOpen() throws Exception {

    Assert.state(!initialized, "Cannot open an already opened ItemReader, call close first");
    initialized = true;/* w ww.  j  a  va2s  .  c om*/

}

From source file:org.springframework.batch.item.database.HibernateItemWriter.java

/**
 * Check mandatory properties - there must be a sessionFactory.
 *///  www  . ja va2  s  . c om
@Override
public void afterPropertiesSet() {
    Assert.state(sessionFactory != null, "SessionFactory must be provided");
}

From source file:org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder.java

/**
 * Builds the {@link FlatFileItemReader}.
 *
 * @return a {@link FlatFileItemReader}/*w  ww. j  av  a 2s.  c  o  m*/
 * @throws Exception
 */
public FlatFileItemReader<T> build() throws Exception {
    if (this.saveState) {
        Assert.state(StringUtils.hasText(this.name), "A name is required when saveSate is set to true.");
    }

    if (this.resource == null) {
        logger.debug("The resource is null.  This is only a valid scenario when "
                + "injecting it later as in when using the MultiResourceItemReader");
    }

    Assert.notNull(this.recordSeparatorPolicy, "A RecordSeparatorPolicy is required.");
    int validatorValue = this.tokenizerValidator.intValue();
    Assert.state(validatorValue == 1 || validatorValue == 2 || validatorValue == 4,
            "Only one LineTokenizer option may be configured");

    FlatFileItemReader<T> reader = new FlatFileItemReader<>();

    if (StringUtils.hasText(this.name)) {
        reader.setName(this.name);
    }

    reader.setResource(this.resource);

    if (this.lineMapper != null) {
        reader.setLineMapper(this.lineMapper);
    } else {
        DefaultLineMapper<T> lineMapper = new DefaultLineMapper<>();

        if (this.lineTokenizer != null && this.fieldSetMapper != null) {
            lineMapper.setLineTokenizer(this.lineTokenizer);
        } else if (this.fixedLengthBuilder != null) {
            lineMapper.setLineTokenizer(this.fixedLengthBuilder.build());
        } else if (this.delimitedBuilder != null) {
            lineMapper.setLineTokenizer(this.delimitedBuilder.build());
        } else {
            throw new IllegalStateException("No LineTokenizer implementation was provided.");
        }

        if (this.targetType != null || StringUtils.hasText(this.prototypeBeanName)) {
            BeanWrapperFieldSetMapper<T> mapper = new BeanWrapperFieldSetMapper<>();
            mapper.setTargetType(this.targetType);
            mapper.setPrototypeBeanName(this.prototypeBeanName);
            mapper.setStrict(this.beanMapperStrict);
            mapper.setBeanFactory(this.beanFactory);
            mapper.setDistanceLimit(this.distanceLimit);
            mapper.setCustomEditors(this.customEditors);
            mapper.afterPropertiesSet();

            lineMapper.setFieldSetMapper(mapper);
        } else if (this.fieldSetMapper != null) {
            lineMapper.setFieldSetMapper(this.fieldSetMapper);
        } else {
            throw new IllegalStateException("No FieldSetMapper implementation was provided.");
        }

        reader.setLineMapper(lineMapper);
    }

    reader.setLinesToSkip(this.linesToSkip);

    if (!this.comments.isEmpty()) {
        reader.setComments(this.comments.toArray(new String[this.comments.size()]));
    }

    reader.setSkippedLinesCallback(this.skippedLinesCallback);
    reader.setRecordSeparatorPolicy(this.recordSeparatorPolicy);
    reader.setMaxItemCount(this.maxItemCount);
    reader.setSaveState(this.saveState);
    reader.setStrict(this.strict);

    return reader;
}

From source file:org.springframework.batch.item.jms.JmsItemReader.java

@Override
@SuppressWarnings("unchecked")
public T read() {
    if (itemType != null && itemType.isAssignableFrom(Message.class)) {
        return (T) jmsTemplate.receive();
    }//ww  w  .  j a va  2  s  . co m
    Object result = jmsTemplate.receiveAndConvert();
    if (itemType != null && result != null) {
        Assert.state(itemType.isAssignableFrom(result.getClass()),
                "Received message payload of wrong type: expected [" + itemType + "]");
    }
    return (T) result;
}

From source file:org.springframework.batch.item.support.AbstractFileItemWriter.java

protected OutputState getOutputState() {
    if (state == null) {
        File file;//from  www.  jav  a 2s. co  m
        try {
            file = resource.getFile();
        } catch (IOException e) {
            throw new ItemStreamException("Could not convert resource to file: [" + resource + "]", e);
        }
        Assert.state(!file.exists() || file.canWrite(), "Resource is not writable: [" + resource + "]");
        state = new OutputState();
        state.setDeleteIfExists(shouldDeleteIfExists);
        state.setAppendAllowed(append);
        state.setEncoding(encoding);
    }
    return state;
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriter.java

/**
 * Helper method for opening output source at given file position
 *///w w w  . j  a  v  a 2 s .c o  m
private void open(long position) {

    File file;
    FileOutputStream os = null;
    FileChannel fileChannel = null;

    try {
        file = resource.getFile();
        FileUtils.setUpOutputFile(file, restarted, false, overwriteOutput);
        Assert.state(resource.exists(), "Output resource must exist");
        os = new FileOutputStream(file, true);
        fileChannel = os.getChannel();
        channel = os.getChannel();
        setPosition(position);
    } catch (IOException ioe) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                ioe);
    }

    XMLOutputFactory outputFactory = createXmlOutputFactory();

    if (outputFactory.isPropertySupported("com.ctc.wstx.automaticEndElements")) {
        // If the current XMLOutputFactory implementation is supplied by
        // Woodstox >= 3.2.9 we want to disable its
        // automatic end element feature (see:
        // http://jira.codehaus.org/browse/WSTX-165) per
        // http://jira.spring.io/browse/BATCH-761).
        outputFactory.setProperty("com.ctc.wstx.automaticEndElements", Boolean.FALSE);
    }
    if (outputFactory.isPropertySupported("com.ctc.wstx.outputValidateStructure")) {
        // On restart we don't write the root element so we have to disable
        // structural validation (see:
        // http://jira.spring.io/browse/BATCH-1681).
        outputFactory.setProperty("com.ctc.wstx.outputValidateStructure", Boolean.FALSE);
    }

    try {
        final FileChannel channel = fileChannel;
        if (transactional) {
            TransactionAwareBufferedWriter writer = new TransactionAwareBufferedWriter(channel, new Runnable() {
                @Override
                public void run() {
                    closeStream();
                }
            });

            writer.setEncoding(encoding);
            writer.setForceSync(forceSync);
            bufferedWriter = writer;
        } else {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, encoding));
        }
        delegateEventWriter = createXmlEventWriter(outputFactory, bufferedWriter);
        eventWriter = new NoStartEndDocumentStreamWriter(delegateEventWriter);
        initNamespaceContext(delegateEventWriter);
        if (!restarted) {
            startDocument(delegateEventWriter);
            if (forceSync) {
                channel.force(false);
            }
        }
    } catch (XMLStreamException xse) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                xse);
    } catch (UnsupportedEncodingException e) {
        throw new DataAccessResourceFailureException(
                "Unable to write to file resource: [" + resource + "] with encoding=[" + encoding + "]", e);
    } catch (IOException e) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]", e);
    }
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriter.java

/**
 * Write the value objects and flush them to the file.
 * /*from   w ww. j  a va 2 s.  c om*/
 * @param items the value object
 * @throws IOException
 * @throws XmlMappingException
 */
@Override
public void write(List<? extends T> items) throws XmlMappingException, Exception {

    if (!this.initialized) {
        throw new WriterNotOpenException("Writer must be open before it can be written to");
    }

    currentRecordCount += items.size();

    for (Object object : items) {
        Assert.state(marshaller.supports(object.getClass()),
                "Marshaller must support the class of the marshalled object");
        Result result = createStaxResult();
        marshaller.marshal(object, result);
    }
    try {
        eventWriter.flush();
        if (forceSync) {
            channel.force(false);
        }
    } catch (XMLStreamException e) {
        throw new WriteFailedException("Failed to flush the events", e);
    } catch (IOException e) {
        throw new WriteFailedException("Failed to flush the events", e);
    }

}

From source file:org.springframework.batch.retry.interceptor.StatefulRetryOperationsInterceptor.java

/**
 * Wrap the method invocation in a stateful retry with the policy and other
 * helpers provided. If there is a failure the exception will generally be
 * re-thrown. The only time it is not re-thrown is when retry is exhausted
 * and the recovery path is taken (though the
 * {@link MethodInvocationRecoverer} provided if there is one). In that case
 * the value returned from the method invocation will be the value returned
 * by the recoverer (so the return type for that should be the same as the
 * intercepted method)./*from  ww w. j av a 2  s.  c  o  m*/
 * 
 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
 * @see MethodInvocationRecoverer#recover(Object[], Throwable)
 * 
 * @throws ExhaustedRetryException if the retry is exhausted and no
 * {@link MethodInvocationRecoverer} is provided.
 */
public Object invoke(final MethodInvocation invocation) throws Throwable {

    logger.debug("Executing proxied method in stateful retry: " + invocation.getStaticPart() + "("
            + ObjectUtils.getIdentityHexString(invocation) + ")");

    Object[] args = invocation.getArguments();
    Assert.state(args.length > 0,
            "Stateful retry applied to method that takes no arguments: " + invocation.getStaticPart());
    Object arg = args;
    if (args.length == 1) {
        arg = args[0];
    }
    final Object item = arg;

    RetryState retryState = new DefaultRetryState(keyGenerator != null ? keyGenerator.getKey(args) : item,
            newMethodArgumentsIdentifier != null ? newMethodArgumentsIdentifier.isNew(args) : false);

    Object result = retryOperations.execute(new MethodInvocationRetryCallback(invocation),
            new ItemRecovererCallback(args, recoverer), retryState);

    logger.debug("Exiting proxied method in stateful retry with result: (" + result + ")");

    return result;

}