public void generateView(GrailsDomainClass domainClass, String viewName, Writer out)
      throws IOException {
    String templateText =
        getTemplateTextView(
            viewName + ".gsp", "/WEB-INF/templates/angular-scaffolding/views/", "views");

    if (!StringUtils.hasLength(templateText)) {
      return;
    }

    GrailsDomainClassProperty multiPart = null;
    for (GrailsDomainClassProperty property : domainClass.getProperties()) {
      if (property.getType() == Byte[].class || property.getType() == byte[].class) {
        multiPart = property;
        break;
      }
    }

    String packageName =
        StringUtils.hasLength(domainClass.getPackageName())
            ? "<%@ page import=\"" + domainClass.getFullName() + "\" %>"
            : "";
    Map<String, Object> binding = createBinding(domainClass);
    binding.put("packageName", packageName);
    binding.put("multiPart", multiPart);
    binding.put("propertyName", getPropertyName(domainClass));

    generate(templateText, binding, out);
  }
 public void afterPropertiesSet() throws JiBXException {
   if (this.targetClass != null) {
     if (StringUtils.hasLength(this.bindingName)) {
       if (logger.isInfoEnabled()) {
         logger.info(
             "Configured for target class ["
                 + this.targetClass
                 + "] using binding ["
                 + this.bindingName
                 + "]");
       }
       this.bindingFactory = BindingDirectory.getFactory(this.bindingName, this.targetClass);
     } else {
       if (logger.isInfoEnabled()) {
         logger.info("Configured for target class [" + this.targetClass + "]");
       }
       this.bindingFactory = BindingDirectory.getFactory(this.targetClass);
     }
   } else if (this.targetPackage != null) {
     if (!StringUtils.hasLength(bindingName)) {
       bindingName = DEFAULT_BINDING_NAME;
     }
     if (logger.isInfoEnabled()) {
       logger.info(
           "Configured for target package ["
               + targetPackage
               + "] using binding ["
               + bindingName
               + "]");
     }
     this.bindingFactory = BindingDirectory.getFactory(bindingName, targetPackage);
   } else {
     throw new IllegalArgumentException("either 'targetClass' or 'targetPackage' is required");
   }
 }
 /**
  * Determines the {@link MediaType} for the given filename.
  *
  * <p>The default implementation will check the {@linkplain #setMediaTypes(Map) media types}
  * property first for a defined mapping. If not present, and if the Java Activation Framework can
  * be found on the classpath, it will call {@link FileTypeMap#getContentType(String)}
  *
  * <p>This method can be overridden to provide a different algorithm.
  *
  * @param filename the current request file name (i.e. {@code hotels.html})
  * @return the media type, if any
  */
 protected MediaType getMediaTypeFromFilename(String filename) {
   String extension = StringUtils.getFilenameExtension(filename);
   if (!StringUtils.hasText(extension)) {
     return null;
   }
   extension = extension.toLowerCase(Locale.ENGLISH);
   MediaType mediaType = this.mediaTypes.get(extension);
   if (mediaType == null) {
     String mimeType = getServletContext().getMimeType(filename);
     if (StringUtils.hasText(mimeType)) {
       mediaType = MediaType.parseMediaType(mimeType);
     }
     if (this.useJaf
         && (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType))) {
       MediaType jafMediaType = ActivationMediaTypeFactory.getMediaType(filename);
       if (jafMediaType != null && !MediaType.APPLICATION_OCTET_STREAM.equals(jafMediaType)) {
         mediaType = jafMediaType;
       }
     }
     if (mediaType != null) {
       this.mediaTypes.putIfAbsent(extension, mediaType);
     }
   }
   return mediaType;
 }
  public void writeSelectRightFormula(RedFormulaCaclMulForcast forcast) {
    String selectNums = forcast.getSelectNums();
    String selectFormulas = forcast.getSelectFormulas();
    String selectNumRst = forcast.getSelectNumsResult();

    String selectRightFormulas = "";

    if (StringUtils.hasLength(selectNums)
        && StringUtils.hasLength(selectFormulas)
        && StringUtils.hasLength(selectNumRst)) {
      String[] tmp1 = selectNums.split(",");
      String[] tmp2 = selectFormulas.split(",");
      Map<String, String> map = new HashMap<String, String>();
      for (int i = 0; i < tmp1.length; i++) {
        map.put(tmp2[i], tmp1[i]);
      }

      String[] tmp = selectNumRst.split(",");
      for (int i = 0; i < tmp.length; i++) {
        for (String key : map.keySet()) {
          String value = map.get(key);
          if (value.equals(tmp[i])) {
            selectRightFormulas = selectRightFormulas + key + ",";
            map.remove(key);
            break;
          }
        }
      }
    }
    forcast.setSelectRightFormulas(selectRightFormulas);
  }
  /**
   * Get a {@link PagingQueryProvider} instance using the provided properties and appropriate for
   * the given database type.
   *
   * @see FactoryBean#getObject()
   */
  @Override
  public PagingQueryProvider getObject() throws Exception {

    DatabaseType type;
    try {
      type =
          databaseType != null
              ? DatabaseType.valueOf(databaseType.toUpperCase())
              : DatabaseType.fromMetaData(dataSource);
    } catch (MetaDataAccessException e) {
      throw new IllegalArgumentException(
          "Could not inspect meta data for database type.  You have to supply it explicitly.", e);
    }

    AbstractSqlPagingQueryProvider provider = providers.get(type);
    Assert.state(
        provider != null,
        "Should not happen: missing PagingQueryProvider for DatabaseType=" + type);

    provider.setFromClause(fromClause);
    provider.setWhereClause(whereClause);
    provider.setSortKeys(sortKeys);
    if (StringUtils.hasText(selectClause)) {
      provider.setSelectClause(selectClause);
    }
    if (StringUtils.hasText(groupClause)) {
      provider.setGroupClause(groupClause);
    }

    provider.init(dataSource);

    return provider;
  }
 @Transactional
 public ResultInfo manageEditOrder(
     String id, String employerAddress, String price, String beginDate, String endDate) {
   try {
     long idl = Long.valueOf(id);
     ServiceOrder order = dao.getResultById(ServiceOrder.class, idl);
     if (order == null) return ResultInfo.SERVICE_ORDER_NULL;
     // String hql =
     // "from Employer e where e.ovld = true and e.mobilePhone = ?";
     // Employer employer = dao.getSingleResultByHQL(Employer.class, hql,
     // employerTelephone);
     // if (employer == null)
     // return ResultInfo.EMPLOYER_NULL;
     // if (!StringUtils.isEmpty(employerName))
     // employer.setUsername(employerName);
     // if (!StringUtils.isEmpty(employerTelephone))
     // employer.setMobilePhone(employerTelephone);
     if (!StringUtils.isEmpty(employerAddress)) order.setAddress(employerAddress);
     if (!StringUtils.isEmpty(price)) order.setOrderPrice(Long.parseLong(price));
     if (!StringUtils.isEmpty(beginDate))
       order.setServiceBeginDate(ExpectedDateCreate.parseDate(beginDate));
     if (!StringUtils.isEmpty(endDate))
       order.setServiceEndDate(ExpectedDateCreate.parseDate(endDate));
     // order.setEmployer(employer);
     order.setUpdateDate(new Date());
     dao.update(order);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return ResultInfo.SUCCESS;
 }
  @Override
  public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry registry) {
    Map<String, Object> attrs = meta.getAnnotationAttributes(EnableReactor.class.getName());

    // Create a root Enivronment
    if (!registry.containsBeanDefinition(Environment.class.getName())) {
      BeanDefinitionBuilder envBeanDef =
          BeanDefinitionBuilder.rootBeanDefinition(Environment.class);

      String configReaderBean = (String) attrs.get("configurationReader");
      if (StringUtils.hasText(configReaderBean)) {
        envBeanDef.addConstructorArgReference(configReaderBean);
      } else {
        String profileName = (String) attrs.get("value");
        if (StringUtils.hasText(profileName)) {
          envBeanDef.addConstructorArgValue(new PropertiesConfigurationReader(profileName));
        }
      }
      registry.registerBeanDefinition(Environment.class.getName(), envBeanDef.getBeanDefinition());
    }

    // Create a ConsumerBeanPostProcessor
    if (!registry.containsBeanDefinition(ConsumerBeanPostProcessor.class.getName())) {
      BeanDefinitionBuilder envBeanDef =
          BeanDefinitionBuilder.rootBeanDefinition(ConsumerBeanPostProcessor.class);
      registry.registerBeanDefinition(
          ConsumerBeanPostProcessor.class.getName(), envBeanDef.getBeanDefinition());
    }
  }
  @Bean
  @RefreshScope
  public WsFederationConfiguration wsFedConfig() {
    final WsFederationConfiguration config = new WsFederationConfiguration();
    final WsFederationProperties wsfed = casProperties.getAuthn().getWsfed();
    config.setAttributesType(
        WsFederationConfiguration.WsFedPrincipalResolutionAttributesType.valueOf(
            wsfed.getAttributesType()));
    config.setIdentityAttribute(wsfed.getIdentityAttribute());
    config.setIdentityProviderIdentifier(wsfed.getIdentityProviderIdentifier());
    config.setIdentityProviderUrl(wsfed.getIdentityProviderUrl());
    config.setTolerance(wsfed.getTolerance());
    config.setRelyingPartyIdentifier(wsfed.getRelyingPartyIdentifier());
    org.springframework.util.StringUtils.commaDelimitedListToSet(
            wsfed.getSigningCertificateResources())
        .forEach(
            s -> config.getSigningCertificateResources().add(this.resourceLoader.getResource(s)));

    org.springframework.util.StringUtils.commaDelimitedListToSet(wsfed.getEncryptionPrivateKey())
        .forEach(s -> config.setEncryptionPrivateKey(this.resourceLoader.getResource(s)));

    org.springframework.util.StringUtils.commaDelimitedListToSet(wsfed.getEncryptionCertificate())
        .forEach(s -> config.setEncryptionCertificate(this.resourceLoader.getResource(s)));

    config.setEncryptionPrivateKeyPassword(wsfed.getEncryptionPrivateKeyPassword());
    config.setAttributeMutator(this.attributeMutator);
    return config;
  }
 @Bean
 public JwtAccessTokenConverter jwtTokenEnhancer() {
   JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
   String keyValue = this.resource.getJwt().getKeyValue();
   if (!StringUtils.hasText(keyValue)) {
     try {
       keyValue = getKeyFromServer();
     } catch (ResourceAccessException ex) {
       logger.warn(
           "Failed to fetch token key (you may need to refresh "
               + "when the auth server is back)");
     }
   }
   if (StringUtils.hasText(keyValue) && !keyValue.startsWith("-----BEGIN")) {
     converter.setSigningKey(keyValue);
   }
   if (keyValue != null) {
     converter.setVerifierKey(keyValue);
   }
   AnnotationAwareOrderComparator.sort(this.configurers);
   for (JwtAccessTokenConverterConfigurer configurer : this.configurers) {
     configurer.configure(converter);
   }
   return converter;
 }
Exemple #10
0
 /**
  * Check the given property values against the required fields, generating missing field errors
  * where appropriate.
  *
  * @param mpvs the property values to be bound (can be modified)
  * @see #getRequiredFields
  * @see #getBindingErrorProcessor
  * @see BindingErrorProcessor#processMissingFieldError
  */
 protected void checkRequiredFields(MutablePropertyValues mpvs) {
   String[] requiredFields = getRequiredFields();
   if (!ObjectUtils.isEmpty(requiredFields)) {
     Map<String, PropertyValue> propertyValues = new HashMap<String, PropertyValue>();
     PropertyValue[] pvs = mpvs.getPropertyValues();
     for (PropertyValue pv : pvs) {
       String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
       propertyValues.put(canonicalName, pv);
     }
     for (String field : requiredFields) {
       PropertyValue pv = propertyValues.get(field);
       boolean empty = (pv == null || pv.getValue() == null);
       if (!empty) {
         if (pv.getValue() instanceof String) {
           empty = !StringUtils.hasText((String) pv.getValue());
         } else if (pv.getValue() instanceof String[]) {
           String[] values = (String[]) pv.getValue();
           empty = (values.length == 0 || !StringUtils.hasText(values[0]));
         }
       }
       if (empty) {
         // Use bind error processor to create FieldError.
         getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult());
         // Remove property from property values to bind:
         // It has already caused a field error with a rejected value.
         if (pv != null) {
           mpvs.removePropertyValue(pv);
           propertyValues.remove(field);
         }
       }
     }
   }
 }
  private static String[] createContainerCommands(SpringYarnAppmasterLaunchContextProperties syalcp)
      throws Exception {
    LaunchCommandsFactoryBean factory = new LaunchCommandsFactoryBean();
    String containerJar = syalcp.getArchiveFile();

    if (StringUtils.hasText(containerJar) && containerJar.endsWith("jar")) {
      factory.setJarFile(containerJar);
    } else if (StringUtils.hasText(syalcp.getRunnerClass())) {
      factory.setRunnerClass(syalcp.getRunnerClass());
    } else if (StringUtils.hasText(containerJar) && containerJar.endsWith("zip")) {
      factory.setRunnerClass("org.springframework.boot.loader.PropertiesLauncher");
    }

    factory.setArgumentsList(syalcp.getArgumentsList());

    if (syalcp.getArguments() != null) {
      Properties arguments = new Properties();
      arguments.putAll(syalcp.getArguments());
      factory.setArguments(arguments);
    }

    factory.setOptions(syalcp.getOptions());

    factory.setStdout("<LOG_DIR>/Container.stdout");
    factory.setStderr("<LOG_DIR>/Container.stderr");
    factory.afterPropertiesSet();
    return factory.getObject();
  }
  @RequestMapping(
      value = {"/welcome"},
      method = {RequestMethod.POST, RequestMethod.GET})
  public ModelAndView welcome(HttpServletRequest request, HttpServletResponse response) {
    try {
      String openid = (String) request.getSession().getAttribute("openid");
      if (StringUtils.isEmpty(openid)) {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        if (code == null) {
          response.sendRedirect("/weixin/error/oauthError.html");
          return null;
        }
        openid = OAuthService.getOauthAccessToke(code);
        if (!StringUtils.isEmpty(openid)) {
          HttpSession session = request.getSession();
          session.setAttribute("openid", openid);
        }
      }

      ModelAndView mav = null;
      mav = new ModelAndView("jsp/index");
      List<WxArticle> list = indexService.welcome();
      mav.addObject("list", list);
      return mav;
    } catch (Exception e) {
      logger.error(e);
    }
    return null;
  }
 public BaasUser register(String appId, String plat, BaasUser user) {
   String username = user.getUsername();
   String password = user.getPassword();
   if (StringUtils.isEmpty(password)) {
     // 密码禁止为空
     throw new SimpleError(SimpleCode.USER_EMPTY_PASSWORD);
   }
   if (StringUtils.isEmpty(username)) {
     // 用户名禁止为空
     throw new SimpleError(SimpleCode.USER_EMPTY_USERNAME);
   }
   if (!isNameValid(username)) {
     // 用户名不合法
     throw new SimpleError(SimpleCode.USER_INVALID_USERNAME);
   }
   BaasUser exist = get(appId, plat, username, null, true);
   if (exist != null) {
     // 用户已存在
     throw new SimpleError(SimpleCode.USER_ALREADY_EXIST);
   }
   user.setPassword(encrypt(username, password));
   user.setSessionToken(getSessionToken());
   // 禁止设置ACL字段
   user.remove("acl");
   BaasObject object = objectService.insert(appId, plat, USER_CLASS_NAME, user, null, true);
   return new BaasUser(object);
 }
 public BaasUser updatePassword(
     String appId,
     String plat,
     String id,
     String oldPassword,
     String newPassword,
     BaasUser currentUser) {
   if (currentUser == null || !currentUser.getId().equals(id)) {
     // 非本人禁止修改用户信息
     throw new SimpleError(SimpleCode.USER_NOT_MATCH);
   }
   if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword)) {
     throw new SimpleError(SimpleCode.REQUEST_PARAM_ERROR);
     // 参数不足
   }
   BaasUser user = get(appId, plat, currentUser.getUsername(), null, true);
   String username = user.getUsername();
   String passwordMd5 = encrypt(username, oldPassword);
   String passwordExist = user.getPassword();
   if (!passwordMd5.equals(passwordExist)) {
     // 密码错误
     throw new SimpleError(SimpleCode.USER_WRONG_PASSWORD);
   }
   // 修改密码
   user.setPassword(encrypt(username, newPassword));
   // 重置SessionToken
   String oldSessionToken = user.getSessionToken();
   user.setSessionToken(getSessionToken());
   objectService.update(appId, plat, UserService.USER_CLASS_NAME, id, user, null, true);
   // 更新成功 清除用户缓存
   deleteUserCache(appId, oldSessionToken);
   return user;
 }
  private void checkPasswordChangeIsAllowed(String userId, String oldPassword) {
    if (securityContextAccessor.isClient()) {
      // Trusted client (not acting on behalf of user)
      return;
    }

    // Call is by or on behalf of end user
    String currentUser = securityContextAccessor.getUserId();

    if (securityContextAccessor.isAdmin()) {

      // even an admin needs to provide the old value to change his
      // password
      if (userId.equals(currentUser) && !StringUtils.hasText(oldPassword)) {
        throw new InvalidPasswordException("Previous password is required even for admin");
      }

    } else {

      if (!userId.equals(currentUser)) {
        logger.warn(
            "User with id " + currentUser + " attempting to change password for user " + userId);
        // TODO: This should be audited when we have non-authentication
        // events in the log
        throw new InvalidPasswordException("Not permitted to change another user's password");
      }

      // User is changing their own password, old password is required
      if (!StringUtils.hasText(oldPassword)) {
        throw new InvalidPasswordException("Previous password is required");
      }
    }
  }
  @Override
  protected void doParse(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    String connectionFactoryRef = element.getAttribute(CONNECTION_FACTORY_ATTRIBUTE);

    if (!StringUtils.hasText(connectionFactoryRef)) {
      parserContext
          .getReaderContext()
          .error("A '" + CONNECTION_FACTORY_ATTRIBUTE + "' attribute must be set.", element);
    }

    if (StringUtils.hasText(connectionFactoryRef)) {
      // Use constructor with connectionFactory parameter
      builder.addConstructorArgReference(connectionFactoryRef);
    }

    NamespaceUtils.setValueIfAttributeDefined(builder, element, CHANNEL_TRANSACTED_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, QUEUE_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, EXCHANGE_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, ROUTING_KEY_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, REPLY_TIMEOUT_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, ENCODING_ATTRIBUTE);
    NamespaceUtils.setReferenceIfAttributeDefined(builder, element, MESSAGE_CONVERTER_ATTRIBUTE);
    NamespaceUtils.setReferenceIfAttributeDefined(builder, element, REPLY_QUEUE);
  }
  public Pagination<ServiceOrderView> manageOrderList(
      Pagination<ServiceOrder> page, String exployerName, String telephone) {
    List<Object> params = new ArrayList<Object>();
    StringBuffer hql = new StringBuffer("from ServiceOrder r where ovld = true ");
    if (!StringUtils.isEmpty(telephone)) {
      hql.append(" and r.mobilePhone = ? ");
      params.add(telephone);
    }
    if (!StringUtils.isEmpty(exployerName)) {
      hql.append(" and r.employer.username like ? ");
      params.add("%" + exployerName + "%");
    }

    StringBuffer countHql = new StringBuffer(" select count(r.id) ");
    countHql.append(hql);
    Object[] objParams = new Object[params.size()];
    for (int i = 0; i < objParams.length; i++) {
      objParams[i] = params.get(i);
    }
    Pagination<ServiceOrder> p =
        dao.getPageResultObjectParams(
            ServiceOrder.class, hql.toString(), page.getPageNo(), page.getPageSize(), objParams);
    List<ServiceOrder> list = p.getResult();
    List<ServiceOrderView> viewList = new ArrayList<ServiceOrderView>();
    for (ServiceOrder order : list) {
      viewList.add(order.view());
    }

    Pagination<ServiceOrderView> pa =
        new Pagination<ServiceOrderView>(viewList, p.getPageNo(), p.getPageSize());
    Long count = dao.getSingleResultByHQLObjectParams(Long.class, countHql.toString(), objParams);
    pa.setResultSize(count);
    return pa;
  }
  @Override
  protected void doInit() {
    BeanFactory beanFactory = getBeanFactory();

    if (StringUtils.hasText(this.requestChannel)) {
      this.gatewayProxyFactoryBean.setDefaultRequestChannel(
          beanFactory.getBean(this.requestChannel, MessageChannel.class));
    }

    if (StringUtils.hasText(this.replyChannel)) {
      this.gatewayProxyFactoryBean.setDefaultReplyChannel(
          beanFactory.getBean(this.replyChannel, MessageChannel.class));
    }

    if (StringUtils.hasText(this.errorChannel)) {
      this.gatewayProxyFactoryBean.setErrorChannel(
          beanFactory.getBean(this.errorChannel, MessageChannel.class));
    }

    if (beanFactory instanceof ConfigurableListableBeanFactory) {
      ((ConfigurableListableBeanFactory) beanFactory)
          .initializeBean(this.gatewayProxyFactoryBean, null);
    }
    try {
      this.exchanger = (RequestReplyExchanger) this.gatewayProxyFactoryBean.getObject();
    } catch (Exception e) {
      throw new BeanCreationException("Can't instantiate the GatewayProxyFactoryBean: " + this, e);
    }
  }
Exemple #19
0
 private TreeSet retrieveTranslationCodes() throws Exception {
   TreeSet codes = new TreeSet();
   File propertyRoot = WikiUtil.getClassLoaderRoot();
   File[] files = propertyRoot.listFiles();
   File file;
   String filename;
   for (int i = 0; i < files.length; i++) {
     file = files[i];
     if (!file.isFile()) {
       continue;
     }
     filename = file.getName();
     if (!StringUtils.hasText(filename)) {
       continue;
     }
     if (!filename.startsWith("ApplicationResources_") || !filename.endsWith(".properties")) {
       continue;
     }
     String code =
         filename.substring(
             "ApplicationResources_".length(), filename.length() - ".properties".length());
     if (StringUtils.hasText(code)) {
       codes.add(code);
     }
   }
   return codes;
 }
 @ResponseBody
 @RequestMapping("/levelListXY")
 public PageResult getCountyLevelXY(String x, String y) {
   if (StringUtils.isEmpty(x) || StringUtils.isEmpty(y)) return getErrRes(ResultInfo.INF_EMPTY);
   PageResult pres = levelService.countyLevelsXY(x, y, getResult());
   return pres;
 }
Exemple #21
0
  public void writeKillErrorFormula(RedFormulaCaclMulForcast forcast) {
    String killNums = forcast.getKillNums();
    String killFormulas = forcast.getKillFormulas();
    String killNumRst = forcast.getKillNumsResult();

    String killErrorFormulas = "";

    if (StringUtils.hasLength(killNums) && StringUtils.hasLength(killFormulas)) {
      if (killNumRst.indexOf("杀错:") >= 0) {
        String[] tmp1 = killNums.split(",");
        String[] tmp2 = killFormulas.split(",");
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < tmp1.length; i++) {
          map.put(tmp2[i], tmp1[i]);
        }

        String[] tmp = killNumRst.substring(killNumRst.indexOf("杀错:") + 3).split(",");
        for (int i = 0; i < tmp.length; i++) {
          for (String key : map.keySet()) {
            String value = map.get(key);
            if (value.equals(tmp[i])) {
              killErrorFormulas = killErrorFormulas + key + ",";
              map.remove(key);
              break;
            }
          }
        }
      }
    }
    forcast.setKillErrorFormulas(killErrorFormulas);
  }
Exemple #22
0
 /**
  * Assert that the given text does not contain the given substring.
  *
  * <p>
  *
  * <pre class="code">
  * Assert.doesNotContain(name, &quot;rod&quot;, &quot;Name must not contain 'rod'&quot;);
  * </pre>
  *
  * @param textToSearch the text to search
  * @param substring the substring to find within the text
  * @param message the exception message to use if the assertion fails
  */
 public static void doesNotContain(String textToSearch, String substring, String message) {
   if (StringUtils.hasLength(textToSearch)
       && StringUtils.hasLength(substring)
       && textToSearch.contains(substring)) {
     throw new IllegalArgumentException(message);
   }
 }
  public DynamoDBTemplateImpl(String accessKey, String secretKey) {
    Assert.isTrue(
        StringUtils.hasLength(accessKey) && StringUtils.hasLength(secretKey),
        "Please provide accessKey and secretKey");

    ddb = new AmazonDynamoDBClient(new BasicAWSCredentials(accessKey, secretKey));
  }
  /**
   * Extracts a classpath string from a source text.
   *
   * @param source the source string
   * @param delimiter the delimiter
   * @return classpath string
   */
  public static String extractClasspath(String source, String delimiter) {
    if (!StringUtils.hasText(source)) {
      return null;
    }
    StringBuilder buf = new StringBuilder();

    try {
      List<String> lines = readLines(new StringReader(source));
      List<String> linesWithContent = new ArrayList<String>();
      Iterator<String> iterator = lines.iterator();

      // remove empty entries
      while (iterator.hasNext()) {
        String line = iterator.next().trim();
        if (StringUtils.hasText(line)) {
          linesWithContent.add(line);
        }
      }
      iterator = linesWithContent.iterator();

      // finally add entries with content
      while (iterator.hasNext()) {
        buf.append(iterator.next());
        if (iterator.hasNext()) {
          buf.append(delimiter);
        }
      }

    } catch (IOException e) {
      return null;
    }

    return buf.toString();
  }
  /**
   * toString
   *
   * @return a {@link java.lang.String} object.
   */
  public String toString() {
    StringBuffer b = new StringBuffer();

    b.append("constraint ");
    b.append(m_name);

    switch (m_type) {
      case PRIMARY_KEY:
        b.append(" primary key (");
        if (m_columns.size() == 0) {
          throw new IllegalStateException(
              "Primary key has zero constrained columns... not allowed!");
        }
        b.append(StringUtils.collectionToDelimitedString(m_columns, ", "));
        break;

      case FOREIGN_KEY:
        b.append(" foreign key (");
        if (m_columns.size() == 0) {
          throw new IllegalStateException(
              "Foreign key has zero constrained columns... not allowed!");
        }
        b.append(StringUtils.collectionToDelimitedString(m_columns, ", "));
        break;
      case CHECK:
        b.append(" check (");
        if (m_checkExpression == null || m_checkExpression.length() == 0) {
          throw new IllegalStateException(
              "Check constraint has no check expression... not allowed!");
        }
        b.append(m_checkExpression);
        break;
    }

    b.append(")");

    if (m_type == FOREIGN_KEY) {
      b.append(" references ");
      b.append(m_ftable);
      b.append(" (");
      b.append(StringUtils.collectionToDelimitedString(m_fcolumns, ", "));
      b.append(")");
    }

    if ("c".equals(m_fdeltype)) {
      b.append(" on delete cascade");
    } else if ("r".equals(m_fdeltype)) {
      b.append(" on delete restrict");
    } else if ("n".equals(m_fdeltype)) {
      b.append(" on delete set null");
    } else if ("d".equals(m_fdeltype)) {
      b.append(" on delete set default");
    }

    if ("c".equals(m_fupdtype)) {
      b.append(" on update cascade");
    }

    return b.toString();
  }
  /**
   * Writes the event into the servlet output stream and flushes the response. The method does not
   * close the output stream.
   *
   * @param sseEvent the event object
   * @throws IOException
   */
  public void write(SSEvent sseEvent) throws IOException {
    StringBuilder sb = new StringBuilder(32);

    if (StringUtils.hasText(sseEvent.getComment())) {
      for (String line : sseEvent.getComment().split("\\r?\\n|\\r")) {
        sb.append(":").append(line).append("\n");
      }
    }

    if (StringUtils.hasText(sseEvent.getId())) {
      sb.append("id:").append(sseEvent.getId()).append("\n");
    }

    if (StringUtils.hasText(sseEvent.getEvent())) {
      sb.append("event:").append(sseEvent.getEvent()).append("\n");
    }

    if (StringUtils.hasText(sseEvent.getData())) {
      for (String line : sseEvent.getData().split("\\r?\\n|\\r")) {
        sb.append("data:").append(line).append("\n");
      }
    }

    if (sseEvent.getRetry() != null) {
      sb.append("retry:").append(sseEvent.getRetry()).append("\n");
    }

    sb.append("\n");
    response.getOutputStream().write(sb.toString().getBytes(ExtDirectSpringUtil.UTF8_CHARSET));
    response.getOutputStream().flush();
  }
  @Override
  public int findByTieIdAndTeachTypeIdAndPageCount(
      ClassroomTimetableListVo classroomTimetableListVo, int tieId) {
    Condition a =
        Tables.CLASSROOM_COURSE_TIMETABLE_INFO
            .TIE_ID
            .eq((tieId))
            .and(
                Tables.CLASSROOM_COURSE_TIMETABLE_INFO.TEACH_TYPE_ID.eq(
                    classroomTimetableListVo.getTeachTypeId()));

    if (StringUtils.hasLength(classroomTimetableListVo.getTimetableInfoFileName())) {
      a =
          a.and(
              Tables.CLASSROOM_COURSE_TIMETABLE_INFO.TIMETABLE_INFO_FILE_NAME.like(
                  "%" + classroomTimetableListVo.getTimetableInfoFileName() + "%"));
    }

    if (StringUtils.hasLength(classroomTimetableListVo.getTimetableInfoTerm())) {
      a =
          a.and(
              Tables.CLASSROOM_COURSE_TIMETABLE_INFO.TIMETABLE_INFO_TERM.like(
                  "%" + classroomTimetableListVo.getTimetableInfoTerm() + "%"));
    }

    if (StringUtils.hasLength(classroomTimetableListVo.getClassroom())) {
      a =
          a.and(
              Tables.CLASSROOM_COURSE_TIMETABLE_INFO.CLASSROOM.like(
                  "%" + classroomTimetableListVo.getClassroom() + "%"));
    }
    Record1<Integer> record1 =
        create.selectCount().from(Tables.CLASSROOM_COURSE_TIMETABLE_INFO).where(a).fetchOne();
    return record1.value1();
  }
  private ModuleDefinition updateTaskProperties(
      ModuleDefinition moduleDefinition, String taskDefinitionName) {
    ModuleDefinition.Builder builder = ModuleDefinition.Builder.from(moduleDefinition);
    builder.setParameter(
        "spring.datasource.url",
        (StringUtils.hasText(dataSourceUrl)) ? dataSourceUrl : DEFAULT_TASK_DATASOURCE_URL);

    builder.setParameter(
        "spring.datasource.username",
        (StringUtils.hasText(dataSourceUserName))
            ? dataSourceUserName
            : DEFAULT_TASK_DATASOURCE_USER_NAME);

    if (StringUtils.hasText(dataSourcePassword)) { // password may be empty
      builder.setParameter("spring.datasource.password", dataSourcePassword);
    }

    builder.setParameter(
        "spring.datasource.driverClassName",
        (StringUtils.hasText(dataSourceDriverClassName))
            ? dataSourceDriverClassName
            : DEFAULT_TASK_DATASOURCE_DRIVER_CLASS_NAME);

    return builder.build();
  }
  /** Sends email asynchronously through Sendgrid. */
  @Override
  @Async
  public void sendEmail(final EmailMessage message) {
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
      return;
    }

    SendGrid sendgrid = new SendGrid(username, password);
    sendgrid.setFrom(message.getFromEmail());
    sendgrid.setFromName(message.getFromName());
    sendgrid.addTo(message.getToEmail());
    sendgrid.addToName(message.getToName());
    sendgrid.setReplyTo(message.getReplyTo());
    sendgrid.setSubject(message.getSubject());
    sendgrid.setText(message.getBody());

    try {
      LOGGER.info(
          "Try to send email to {}, message is: {}", message.getToEmail(), message.getBody());
      String response = sendgrid.send();
      LOGGER.info("Sent email successfully, response from SendGrid is: {}", response);
    } catch (Exception ex) {
      LOGGER.debug("Exception:", ex);
      LOGGER.error("Got exception when sending email through sendgrid: {}", ex.getMessage());
    }
  }
 public String[] resolveMessageCodes(
     String errorCode, String objectName, String field, Class<?> fieldType) {
   List<String> codeList = new ArrayList<String>();
   List<String> fieldList = new ArrayList<String>();
   buildFieldList(field, fieldList);
   for (String fieldInList : fieldList) {
     if (StringUtils.hasText(fieldInList)) {
       codeList.add(
           postProcessMessageCode(
               objectName + CODE_SEPARATOR + fieldInList + CODE_SEPARATOR + errorCode));
     } else {
       codeList.add(postProcessMessageCode(objectName + CODE_SEPARATOR + errorCode));
     }
   }
   int dotIndex = field.lastIndexOf('.');
   if (dotIndex != -1) {
     buildFieldList(field.substring(dotIndex + 1), fieldList);
   }
   for (String fieldInList : fieldList) {
     if (StringUtils.hasText(fieldInList)) {
       codeList.add(postProcessMessageCode(fieldInList + CODE_SEPARATOR + errorCode));
     }
   }
   if (fieldType != null) {
     codeList.add(postProcessMessageCode(fieldType.getName() + CODE_SEPARATOR + errorCode));
   }
   codeList.add(postProcessMessageCode(errorCode));
   return StringUtils.toStringArray(codeList);
 }