List of usage examples for org.springframework.util Assert state
public static void state(boolean expression, Supplier<String> messageSupplier)
From source file:net.sf.gazpachoquest.services.core.impl.ResearchServiceImpl.java
@Override @Transactional(readOnly = false)/*from w w w . java 2s .c o m*/ public void addRespondent(Integer researchId, User respondent) { Assert.state(!respondent.isNew(), "Persist respondent before using inside a research."); Research research = repository.findOne(researchId); Assert.state(research.getType().equals(ResearchAccessType.BY_INVITATION), "Tracked participants are not supported in anonymous researches"); QuestionnaireDefinition questionnaireDefinition = research.getQuestionnaireDefinition(); Questionnaire questionnaire = Questionnaire.with().status(research.getStatus()).research(research) .questionnaireDefinition(questionnaireDefinition).respondent(respondent).build(); questionnaire = questionnaireRepository.save(questionnaire); // Create answers holder QuestionnaireAnswers questionnaireAnswers = new QuestionnaireAnswers(); questionnaireAnswers = questionnaireAnswersRepository .save(questionnaire.getQuestionnaireDefinition().getId(), questionnaireAnswers); questionnaire.setAnswersId(questionnaireAnswers.getId()); // Grant permissions over questionnaire to respondent QuestionnairePermission permission = QuestionnairePermission.with().addPerm(Perm.READ).addPerm(Perm.UPDATE) .user(respondent).target(questionnaire).build(); questionnairePermissionRepository.save(permission); String token = tokenGenerator.generate(); PersonalInvitation personalInvitation = PersonalInvitation.with().research(research).token(token) .status(InvitationStatus.ACTIVE).respondent(respondent).build(); invitationRepository.save(personalInvitation); // Add the respondent to respondents groups Group example = Group.with().name("Respondents").build(); Group respondentsGroup = groupRepository.findOneByExample(example, new SearchParameters()) .orElseThrow(() -> new EmptyResultDataAccessException( String.format("No %s entity with name %s found!", Group.class, "Respondents"), 1)); if (groupRepository.isUserInGroup(respondent.getId(), "Respondents") == 0) { respondentsGroup.assignUser(respondent); } }
From source file:com.clican.pluto.common.support.spring.BeanPropertyRowMapper.java
/** * Extract the values for all columns in the current row. * <p>//from w ww . j a va2 s .c o m * Utilizes public setters and result set metadata. * * @see java.sql.ResultSetMetaData */ public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); Object mappedObject = BeanUtils.instantiateClass(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).toLowerCase(); PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column); if (pd != null) { try { Object value = getColumnValue(rs, index, pd); if (logger.isDebugEnabled() && rowNumber == 0) { logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type " + pd.getPropertyType()); } bw.setPropertyValue(pd.getName(), value); if (populatedProperties != null) { populatedProperties.add(pd.getName()); } } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column " + column + " to property " + pd.getName(), ex); } } } 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 + "]: " + this.mappedProperties); } return mappedObject; }
From source file:org.cleverbus.component.asynchchild.AsynchChildProducer.java
/** * Gets {@link MessageService} instance from Camel Context. * * @return MessageService/*from w w w .ja v a2s. c o m*/ * @throws IllegalStateException when there is no MessageService */ protected MessageService getMessageService() { if (!isStarted() && !isStarting()) { throw new IllegalStateException(getClass().getName() + " is not started so far!"); } Set<MessageService> services = getEndpoint().getCamelContext().getRegistry() .findByType(MessageService.class); Assert.state(services.size() >= 1, "MessageService must be at least one."); return services.iterator().next(); }
From source file:com._4dconcept.springframework.data.marklogic.datasource.UserCredentialsContentSourceAdapter.java
/** * This implementation delegates to the {@code newSession(username, password)} * method of the target ContentSource, passing in the specified user credentials. * If the specified username is empty, it will simply delegate to the standard * {@code newSession()} method of the target ContentSource. * @param username the username to use/*from w w w .j av a 2s . c om*/ * @param password the password to use * @return the Session * @see com.marklogic.xcc.ContentSource#newSession(String, String) * @see com.marklogic.xcc.ContentSource#newSession() */ protected Session doGetSession(String username, String password) { Assert.state(getTargetContentSource() != null, "'targetContentSource' is required"); if (StringUtils.hasLength(username)) { return getTargetContentSource().newSession(username, password); } else { return getTargetContentSource().newSession(); } }
From source file:com.sshdemo.common.schedule.generate.quartz.EwcmsMethodInvokingJobDetailFactoryBean.java
@Override public Object getTargetObject() { Object targetObject = super.getTargetObject(); if (targetObject == null && targetBeanName != null) { Assert.state(beanFactory != null, "BeanFactory must be set when using 'targetBeanName'"); targetObject = beanFactory.getBean(targetBeanName); }//from ww w .j a v a2 s . com return targetObject; }
From source file:org.pmedv.core.app.SplashScreen.java
/** * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() *///from www. jav a2 s . co m public void afterPropertiesSet() throws Exception { if (context.containsBean("lookAndFeelConfigurer")) { context.getBean("lookAndFeelConfigurer"); progressBar = new JProgressBar(); } Assert.state(StringUtils.hasText(imageResourcePath), "The splash screen image resource path is required"); if (showProgressLabel) { progressBar.setStringPainted(true); progressBar.setString("Loading context"); } progressBar.setMinimum(0); progressBar.setMaximum(context.getBeanDefinitionCount() - NUM_OF_NON_SINGLETON_BEANS); splash(); }
From source file:org.cloudfoundry.identity.uaa.oauth.JwtTokenEnhancer.java
@Override public void afterPropertiesSet() throws Exception { // Check the signing and verification keys match if (signer instanceof RsaSigner) { RsaVerifier verifier;//w w w. j a v a2 s . co m try { verifier = new RsaVerifier(verifierKey); } catch (Exception e) { logger.warn("Unable to create an RSA verifier from verifierKey"); return; } byte[] test = "test".getBytes(); try { verifier.verify(test, signer.sign(test)); logger.info("Signing and verification RSA keys match"); } catch (InvalidSignatureException e) { logger.error("Signing and verification RSA keys do not match"); } } else { // Avoid a race condition where Assert.state(this.signingKey == this.verifierKey, "For MAC signing you do not need to specify the verifier key separately, and if you do it must match the signing key"); } }
From source file:sample.client.Application.java
@Bean BeanPostProcessor gemfireCacheServerAvailabilityBeanPostProcessor( @Value("${gemfire.cache.server.host:localhost}") final String host, @Value("${gemfire.cache.server.port:12480}") final int port) { // <5> return new BeanPostProcessor() { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof PoolFactoryBean || bean instanceof Pool) { if (!waitForCacheServerToStart(host, port)) { Application.this.logger.warn("No GemFire Cache Server found on [host: {}, port: {}]", host, port);//from w ww. j a va 2 s . c o m } } return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof PoolFactoryBean || bean instanceof Pool) { try { Assert.state(latch.await(DEFAULT_WAIT_DURATION, TimeUnit.MILLISECONDS), String.format( "GemFire Cache Server failed to start on [host: %1$s, port: %2$d]", host, port)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } return bean; } }; }
From source file:org.green.code.async.executor.ThreadPoolTaskExecutor.java
/** * Return the underlying ThreadPoolExecutor for native access. * //from w ww . j ava 2 s . c o m * @return the underlying ThreadPoolExecutor (never {@code null}) * @throws IllegalStateException * if the ThreadPoolTaskExecutor hasn't been initialized yet */ public ThreadPoolExecutor getThreadPoolExecutor() throws IllegalStateException { Assert.state(this.threadPoolExecutor != null, "ThreadPoolTaskExecutor not initialized"); return this.threadPoolExecutor; }
From source file:org.cloudfoundry.identity.uaa.oauth.ClientAdminEndpoints.java
@Override public void afterPropertiesSet() throws Exception { Assert.state(clientRegistrationService != null, "A ClientRegistrationService must be provided"); Assert.state(clientDetailsService != null, "A ClientDetailsService must be provided"); }