Java Code Examples for org.springframework.util.Assert

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project addressbook-sample-mongodb, under directory /contacts/src/main/java/nl/enovation/addressbook/cqrs/commandhandler/.

Source file: ContactCommandHandler.java

  21 
vote

/** 
 * Adds a new phone number to the list of phone numbers of the provided contact. <p/> An  {@code AggregateNotFoundException} is thrown if the identifier does not represent a valid contact.
 * @param command UpdateContactCommand that contains the identifier and the data to be updated
 * @param unitOfWork Unit of work for the current running thread
 */
@CommandHandler public void handleCreatePhoneNumber(final CreatePhoneNumberCommand command,UnitOfWork unitOfWork){
  LOGGER.debug("Received a updateContactCommand for id : {}",command.getContactId());
  Assert.notNull(command.getContactId(),"ContactIdentifier may not be null");
  Contact contact=contactRepository.load(command.getContactId());
  Assert.notNull(contact.getIdentifier(),"Contact identifier cannot be null");
  contact.addPhoneNumber(command.getPhoneNumber());
}
 

Example 2

From project ANNIS, under directory /annis-service/src/main/java/annis/ql/parser/.

Source file: NodeRelationNormalizer.java

  21 
vote

@Override public void caseAAndExpr(AAndExpr node){
  boolean check=true;
  while (check) {
    check=false;
    SearchExpressionCounter counter=new SearchExpressionCounter();
    node.apply(counter);
    RelationCollector relcheck=new RelationCollector();
    node.apply(relcheck);
    for (    Entry<String,List<ALinguisticConstraintExpr>> e : relcheck.getIsIn().entrySet()) {
      if (e.getValue().size() > 1) {
        ALinguisticConstraintExpr relation=e.getValue().get(0);
        Assert.notNull(relation.getRhs(),"Only binary operators should be considerd in NodeRelationNormalizer");
        boolean leftSide=true;
        if (relation.getRhs().getText().equals(e.getKey())) {
          leftSide=false;
        }
        split(node,relation,counter,leftSide);
        check=true;
        break;
      }
    }
  }
}
 

Example 3

From project api-sdk-java, under directory /api-sdk/src/main/java/com/smartling/api/sdk/file/commandline/.

Source file: RetrieveFile.java

  20 
vote

private static RetrieveFileParams getParameters(String[] args){
  Assert.isTrue(args.length == 6,"Invalid number of arguments");
  RetrieveFileParams retrieveFileParams=new RetrieveFileParams();
  retrieveFileParams.setProductionMode(Boolean.valueOf(args[0]));
  retrieveFileParams.setApiKey(args[1]);
  retrieveFileParams.setProjectId(args[2]);
  retrieveFileParams.setPathToFile(args[3]);
  retrieveFileParams.setLocale(args[4]);
  retrieveFileParams.setPathToStoreFile(args[5]);
  return retrieveFileParams;
}
 

Example 4

From project aranea, under directory /server/src/test/java/no/dusken/aranea/admin/security/.

Source file: TestRoleHiearchy.java

  19 
vote

/** 
 * Test what happens when the setup Ansv. red > *red is tried
 */
@Test @Ignore public void testRoleHiearchyAstericsBehavior(){
  GrantedAuthority maskinist=new GrantedAuthorityImpl("maskinist");
  RoleHierarchyImpl testhierachy=new RoleHierarchyImpl();
  testhierachy.setHierarchy("maskinist > ansvred " + "ansvred > *red" + "nyhetsred > nyhet"+ "kulturred > kultur");
  Collection<GrantedAuthority> reachable=hierachy.getReachableGrantedAuthorities(new LinkedList<GrantedAuthority>(Arrays.asList(maskinist)));
  Assert.notNull(reachable,"reachable was null");
  for (  GrantedAuthority ga : reachable) {
    if (ga.getAuthority().equals("kulturred")) {
      return;
    }
  }
  fail("*red not matched");
}
 

Example 5

From project Axon-trader, under directory /users/src/main/java/org/axonframework/samples/trader/users/util/.

Source file: DigestUtils.java

  19 
vote

/** 
 * Calculate the SHA1 hash for a given string.
 * @param text the given text to hash to a SHA1
 * @return the SHA1 Hash
 */
public static String sha1(String text){
  Assert.notNull(text);
  try {
    MessageDigest md=MessageDigest.getInstance("SHA1");
    return hex(md.digest(text.getBytes("UTF-8")));
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new IllegalStateException("Unable to calculate hash. No SHA1 hasher available in this Java implementation",ex);
  }
catch (  UnsupportedEncodingException ex) {
    throw new IllegalStateException("Unable to calculate hash. UTF-8 encoding is not available in this Java implementation",ex);
  }
}
 

Example 6

From project banshun, under directory /banshun/web/src/main/java/com/griddynamics/banshun/web/.

Source file: ContextParentAnnotationHandlerMapping.java

  19 
vote

private void register(String[] urls,Object handler){
  if (!ObjectUtils.isEmpty(urls)) {
    Assert.notNull(urls,"URL path array must not be null");
    for (int j=0; j < urls.length; j++) {
      registerHandler(urls[j],handler);
    }
  }
 else {
    if (logger.isDebugEnabled()) {
      logger.debug("Rejected bean '" + handler + "': no URL paths identified");
    }
  }
}
 

Example 7

From project Blitz, under directory /src/com/laxser/blitz/lama/core/.

Source file: BeanPropertyRowMapper.java

  19 
vote

/** 
 * Create a new BeanPropertyRowMapper, accepting unpopulated properties in the target bean.
 * @param mappedClass the class that each row should be mapped to
 */
public BeanPropertyRowMapper(Class<?> mappedClass,boolean checkColumns,boolean checkProperties){
  this.mappedClass=mappedClass;
  Assert.state(this.mappedClass != null,"Mapped class was not specified");
  this.checkProperties=checkProperties;
  this.checkColumns=checkColumns;
  initialize();
}
 

Example 8

From project c24-spring, under directory /c24-spring-batch/src/main/java/biz/c24/io/spring/batch/reader/.

Source file: C24ItemReader.java

  19 
vote

/** 
 * Asserts that we have been properly configured
 */
@PostConstruct public void validateConfiguration(){
  Assert.notNull(elementType,"Element type must be set, either explicitly or by setting the model");
  Assert.notNull(source,"Source must be set");
  if (elementStopPattern != null) {
    Assert.notNull(elementStartPattern,"elementStopPattern can only be used if an elementStartPattern is also set");
  }
}
 

Example 9

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/authentication/.

Source file: AbstractAuthentication.java

  19 
vote

public AbstractAuthentication(final Principal principal,final Map<String,Object> attributes){
  Assert.notNull(principal,"principal cannot be null");
  Assert.notNull(attributes,"attributes cannot be null");
  this.principal=principal;
  this.attributes=attributes;
}
 

Example 10

From project constretto-core, under directory /constretto-spring/src/main/java/org/constretto/spring/internal/.

Source file: ConstrettoNamespaceHandler.java

  19 
vote

public List<Element> getAllChildElements(Element element){
  Assert.notNull(element,"Element must not be null");
  NodeList childNodes=element.getChildNodes();
  List<Element> childElements=new ArrayList<Element>();
  for (int i=0; i < childNodes.getLength(); i++) {
    Node node=childNodes.item(i);
    if (node instanceof Element) {
      childElements.add((Element)node);
    }
  }
  return childElements;
}
 

Example 11

From project data-access, under directory /test-src/org/pentaho/platform/dataaccess/datasource/wizard/csv/.

Source file: FileUploadServiceTest.java

  19 
vote

public void setAttribute(String name,Object value){
  Assert.notNull(name,"Attribute name must not be null");
  if (value != null) {
    this.attributes.put(name,value);
    if (value instanceof HttpSessionBindingListener) {
      ((HttpSessionBindingListener)value).valueBound(new HttpSessionBindingEvent(this,name,value));
    }
  }
 else {
    removeAttribute(name);
  }
}
 

Example 12

From project droolsjbpm-build-distribution, under directory /drools-osgi-bundles/org.drools.osgi.test/src/test/java/org/drools/osgi/test/.

Source file: AbstractDroolsSpringDMTest.java

  19 
vote

/** 
 * Use Eclipse artifact locator as default, falls back on Maven artifact locator in artifact is not found.
 */
protected Resource locateBundle(String bundleId){
  Assert.hasText(bundleId,"bundleId should not be empty");
  Resource result=null;
  String[] artifactId=StringUtils.commaDelimitedListToStringArray(bundleId);
  Assert.isTrue(artifactId.length >= 3,"the CSV string " + bundleId + " contains too few values");
  for (int i=0; i < artifactId.length; i++) {
    artifactId[i]=StringUtils.trimWhitespace(artifactId[i]);
  }
  if (m_EclipseArtifactLocator == null) {
    m_EclipseArtifactLocator=new EclipseWorkspaceArtifactLocator();
  }
  result=(artifactId.length == 3 ? m_EclipseArtifactLocator.locateArtifact(artifactId[0],artifactId[1],artifactId[2]) : m_EclipseArtifactLocator.locateArtifact(artifactId[0],artifactId[1],artifactId[2],artifactId[3]));
  if (result == null) {
    if (m_MavenArtifactLocator == null) {
      m_MavenArtifactLocator=getLocator();
    }
    result=(artifactId.length == 3 ? m_MavenArtifactLocator.locateArtifact(artifactId[0],artifactId[1],artifactId[2]) : m_MavenArtifactLocator.locateArtifact(artifactId[0],artifactId[1],artifactId[2],artifactId[3]));
  }
  if (result == null) {
    throw new IllegalStateException(bundleId + " not found");
  }
  return result;
}
 

Example 13

From project egov-data, under directory /easyCompany2/src/main/java/egovframework/rte/tex/gds/web/.

Source file: EgovGoodsController.java

  19 
vote

/** 
 * ??????? ??????
 * @param goodsVO ???? ??????
 * @param searchVO - ??? ?????? ???? ??? VO
 * @param Model
 * @param status
 * @return String ?????? ??? ???
 */
@RequestMapping("/gds/insertGoods.do") public String insertGoods(final HttpServletRequest request,@ModelAttribute("searchVO") SearchVO searchVO,GoodsVO goodsVO,BindingResult bindingResult,Model model,SessionStatus status) throws Exception {
  beanValidator.validate(goodsVO,bindingResult);
  Assert.state(request instanceof MultipartHttpServletRequest,"request !instanceof MultipartHttpServletRequest");
  final MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
  if (bindingResult.hasErrors()) {
    model.addAttribute("goodsVO",goodsVO);
    return "/gds/EgovGoodsRegist";
  }
  List<GoodsImageVO> imageList=new ArrayList<GoodsImageVO>();
  final Map<String,MultipartFile> files=multiRequest.getFileMap();
  String uploadLastPath=fileUploadProperties.getProperty("file.upload.path");
  String uploadPath=request.getSession().getServletContext().getRealPath("/") + uploadLastPath;
  File saveFolder=new File(uploadPath);
  boolean isDir=false;
  if (!saveFolder.exists() || saveFolder.isFile()) {
    saveFolder.mkdirs();
  }
  if (!isDir) {
    Iterator<Entry<String,MultipartFile>> itr=files.entrySet().iterator();
    MultipartFile file;
    String filePath;
    while (itr.hasNext()) {
      Entry<String,MultipartFile> entry=itr.next();
      file=entry.getValue();
      if (!"".equals(file.getOriginalFilename())) {
        String saveFileName=egovIdGnrServiceImage.getNextStringId();
        int index=file.getOriginalFilename().lastIndexOf(".");
        String fileExtension="." + file.getOriginalFilename().substring(index + 1);
        imageList.add(new GoodsImageVO(saveFileName + fileExtension,file.getOriginalFilename()));
        filePath=uploadPath + "\\" + saveFileName+ fileExtension;
        file.transferTo(new File(filePath));
      }
    }
  }
  goodsVO.setGoodsImageVO(imageList.get(0));
  goodsVO.setDetailImageVO(imageList.get(1));
  egovGoodsService.insertGoods(goodsVO);
  status.setComplete();
  return "redirect:/gds/selectListGoods.do";
}
 

Example 14

From project ehour, under directory /eHour-service/src/main/java/net/rrm/ehour/export/service/importer/.

Source file: XmlImporterBuilder.java

  19 
vote

public XmlImporter build() throws XMLStreamException {
  Assert.notNull(xmlReader);
  Assert.notNull(configurationDao);
  Assert.notNull(domainObjectParserDao);
  Assert.notNull(userRoleParserDao);
  PrimaryKeyCache keyCache=new PrimaryKeyCache();
  DomainObjectParser parser=new DomainObjectParser(xmlReader,domainObjectParserDao,keyCache);
  ConfigurationParser configurationParser=new ConfigurationParser(configurationParserDao);
  UserRoleParser userRoleParser=new UserRoleParser(userRoleParserDao,keyCache);
  return new XmlImporter(configurationDao,parser,configurationParser,userRoleParser,skipValidation);
}
 

Example 15

From project excilys-bank, under directory /excilys-bank-service-impl/src/main/java/com/excilys/ebi/bank/service/impl/security/.

Source file: BankAclService.java

  19 
vote

@Override @Cacheable(cacheName=IConstants.Cache.ACL_CACHE,[email protected](name="StringCacheKeyGenerator")) @Transactional(readOnly=true) public Acl readAclById(ObjectIdentity object,List<Sid> sids) throws NotFoundException {
  SimpleAclImpl acl=new SimpleAclImpl(object);
  logger.info("type={} id={}",object.getType(),object.getIdentifier());
  for (  Sid sid : sids) {
    if (sid instanceof GrantedAuthoritySid && GrantedAuthoritySid.class.cast(sid).getGrantedAuthority().equals(Role.ROLE_ADMIN.name())) {
      acl.getEntries().add(new SimpleAccessControlEntryImpl(acl,sid,BasePermission.READ,true));
      acl.getEntries().add(new SimpleAccessControlEntryImpl(acl,sid,BasePermission.WRITE,true));
      acl.getEntries().add(new SimpleAccessControlEntryImpl(acl,sid,BasePermission.ADMINISTRATION,true));
    }
 else     if (sid instanceof PrincipalSid) {
      Integer accountId=Integer.class.cast(object.getIdentifier());
      String login=((PrincipalSid)sid).getPrincipal();
      Assert.notNull(accountId,"accountId is required");
      Assert.notNull(login,"login is required");
      if (aclDao.isAccountOfUser(accountId,login)) {
        acl.getEntries().add(new SimpleAccessControlEntryImpl(acl,sid,BasePermission.READ,true));
        acl.getEntries().add(new SimpleAccessControlEntryImpl(acl,sid,BasePermission.WRITE,true));
      }
    }
  }
  return acl;
}
 

Example 16

From project FunctionalTestsPortlet, under directory /src/main/java/org/springframework/portlet/filter/.

Source file: GenericPortletFilterBean.java

  19 
vote

@Override public void init(FilterConfig filterConfig) throws PortletException {
  Assert.notNull(filterConfig,"FilterConfig must not be null");
  if (logger.isDebugEnabled()) {
    logger.debug("Initializing filter '" + filterConfig.getFilterName() + "'");
  }
  this.filterConfig=filterConfig;
  try {
    PropertyValues pvs=new FilterConfigPropertyValues(filterConfig,this.requiredProperties);
    BeanWrapper bw=PropertyAccessorFactory.forBeanPropertyAccess(this);
    ResourceLoader resourceLoader=new PortletContextResourceLoader(filterConfig.getPortletContext());
    bw.registerCustomEditor(Resource.class,new ResourceEditor(resourceLoader));
    initBeanWrapper(bw);
    bw.setPropertyValues(pvs,true);
  }
 catch (  BeansException ex) {
    String msg="Failed to set bean properties on filter '" + filterConfig.getFilterName() + "': "+ ex.getMessage();
    logger.error(msg,ex);
    throw new PortletException(msg,ex);
  }
  initFilterBean();
  if (logger.isDebugEnabled()) {
    logger.debug("Filter '" + filterConfig.getFilterName() + "' configured successfully");
  }
}
 

Example 17

From project fuzzydb-samples, under directory /sample-webapp/src/main/java/org/fuzzydb/samples/.

Source file: Utils.java

  19 
vote

public static <T>List<T> toList(Iterator<T> items){
  Assert.notNull(items);
  List<T> list=new LinkedList<T>();
  for (Iterator<T> iterator=items; iterator.hasNext(); ) {
    T item=iterator.next();
    list.add(item);
  }
  return list;
}
 

Example 18

From project Gemini-Blueprint, under directory /core/src/main/java/org/eclipse/gemini/blueprint/bundle/.

Source file: BundleFactoryBean.java

  19 
vote

public void afterPropertiesSet() throws Exception {
  Assert.notNull(bundleContext,"BundleContext is required");
  if (bundle == null && !StringUtils.hasText(symbolicName) && !StringUtils.hasText(location))   throw new IllegalArgumentException("at least one of symbolicName, location, bundle properties is required ");
  if (getLocation() != null) {
    resource=resourceLoader.getResource(getLocation());
  }
  if (bundle == null) {
    bundle=findBundle();
  }
  updateStartLevel(getStartLevel());
  if (log.isDebugEnabled())   log.debug("working with bundle[" + OsgiStringUtils.nullSafeNameAndSymName(bundle));
  if (log.isDebugEnabled())   log.debug("executing start-up action " + action);
  if (action != null) {
    executeAction(action);
  }
}
 

Example 19

From project github-java-api, under directory /src/main/java/de/linsin/github/rest/service/.

Source file: IssueBrowser.java

  19 
vote

/** 
 * Opens the passed  {@link Issue} in the passed {@link Repository}Note: so far only title and body are used from passed instance
 * @param argRepository {@link Repository} instance used to open issue
 * @param argIssue      {@link Issue} instance containing title and body of the issue
 * @return the {@link Issue} instance which was opened and contains assigned id
 * @throws IllegalArgumentException in case passed Issue doesn't contain a body or title
 * @throws NullPointerException     in case passed repository or issue is null
 * @throws HttpClientErrorException in case passed user or repository doesn't exist
 */
public Issue open(Repository argRepository,Issue argIssue){
  RestTemplate template=initTemplate();
  Assert.hasText(argIssue.getTitle());
  Assert.hasText(argIssue.getBody());
  IssueRequest req=new IssueRequest(username,apiToken,argIssue.getTitle(),argIssue.getBody());
  IssueResponse resp=template.postForObject(OPEN_ISSUE_URL,req,IssueResponse.class,argRepository.getOwner(),argRepository.getName());
  return resp.getIssue();
}
 

Example 20

From project grails-data-mapping, under directory /grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/core/.

Source file: AbstractSession.java

  19 
vote

public Serializable persist(Object o){
  Assert.notNull(o,"Cannot persist null object");
  Persister persister=getPersister(o);
  if (persister == null) {
    throw new NonPersistentTypeException("Object [" + o + "] cannot be persisted. It is not a known persistent type.");
  }
  final Serializable key=persister.persist(o);
  cacheObject(key,o);
  return key;
}
 

Example 21

From project grails-searchable, under directory /src/java/grails/plugin/searchable/internal/compass/.

Source file: CompassGpsUtils.java

  19 
vote

/** 
 * Calls CompassGps's index method, starting and stopping it if required
 * @param compassGps aCompassGps instance, cannot be null
 * @param clazz the Class to index instances of, may be null
 */
public static void index(CompassGps compassGps,Class clazz){
  Assert.notNull(compassGps,"compassGps cannot be null");
  long start=System.currentTimeMillis();
  LOG.info("Starting Searchable Plugin bulk index");
  boolean gpsRunning=compassGps.isRunning();
  try {
    if (!gpsRunning) {
      compassGps.start();
    }
    if (clazz != null) {
      compassGps.index(new Class[]{clazz});
    }
 else {
      compassGps.index();
    }
  }
  finally {
    if (!gpsRunning) {
      compassGps.stop();
    }
  }
  LOG.info("Finished Searchable Plugin bulk index, " + TimeUtils.formatMillisAsShortHumanReadablePeriod(System.currentTimeMillis() - start));
}