@Transactional(readOnly = true) public int build(String templatePath, String staticPath, Map<String, Object> model) { Assert.hasText(templatePath); Assert.hasText(staticPath); FileOutputStream fileOutputStream = null; OutputStreamWriter outputStreamWriter = null; Writer writer = null; try { freemarker.template.Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templatePath); File staticFile = new File(servletContext.getRealPath(staticPath)); File staticDirectory = staticFile.getParentFile(); if (!staticDirectory.exists()) { staticDirectory.mkdirs(); } fileOutputStream = new FileOutputStream(staticFile); outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); writer = new BufferedWriter(outputStreamWriter); template.process(model, writer); writer.flush(); return 1; } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(outputStreamWriter); IOUtils.closeQuietly(fileOutputStream); } return 0; }
@Override public User login(User user) { Assert.hasText(user.getLoginName()); Assert.hasText(user.getPassword()); user.setPassword(Encrypt.e(user.getPassword().trim())); return this.userDao.login(user); }
public void updateSystemUser(SystemUser systemUser) { Assert.notNull(systemUser.getId(), "id数据不能为空"); Assert.hasText(systemUser.getEmpId(), "empId不能为空!"); Assert.hasText(systemUser.getLastName(), "lastName不能为空!"); Assert.hasText(systemUser.getNickName(), "nickName不能为空!"); systemUserDao.updateSystemUser(systemUser); }
@Transactional public void addSystemUser(SystemUser systemUser) { Assert.hasText(systemUser.getEmpId(), "empId不能为空!"); Assert.hasText(systemUser.getLastName(), "lastName不能为空!"); Assert.hasText(systemUser.getNickName(), "nickName不能为空!"); systemUserDao.addSystemUser(systemUser); }
/** * Configure a base URL to prepend URI templates with. The base URL must have a scheme and host * but may optionally contain a port and a path. The base URL must be fully expanded and encoded * which can be done via {@link UriComponentsBuilder}. * * @param baseUrl the base URL. */ public void setBaseUrl(String baseUrl) { if (baseUrl != null) { UriComponents uriComponents = UriComponentsBuilder.fromUriString(baseUrl).build(); Assert.hasText(uriComponents.getScheme(), "'baseUrl' must have a scheme"); Assert.hasText(uriComponents.getHost(), "'baseUrl' must have a host"); Assert.isNull(uriComponents.getQuery(), "'baseUrl' cannot have a query"); Assert.isNull(uriComponents.getFragment(), "'baseUrl' cannot have a fragment"); } this.baseUrl = baseUrl; }
/** * Creates a new {@link Address} from the given street, city and country. * * @param street must not be {@literal null} or empty. * @param city must not be {@literal null} or empty. * @param country must not be {@literal null} or empty. */ public Address(String street, String city, String country) { Assert.hasText(street, "Street must not be null or empty!"); Assert.hasText(city, "City must not be null or empty!"); Assert.hasText(country, "Country must not be null or empty!"); this.street = street; this.city = city; this.country = country; }
@Override public void validateBeforeSave(String name, String definition) { Assert.hasText(name, "name cannot be blank or null"); D definitionFromRepo = getDefinitionRepository().findOne(name); if (definitionFromRepo != null) { throwDefinitionAlreadyExistsException(definitionFromRepo); } Assert.hasText(definition, "definition cannot be blank or null"); parser.parse(name, definition, definitionKind); }
/** @return */ @Action(value = "/offlinePay/onlinePaySave") public void doSave() { JSONResult result = new JSONResult(); try { Assert.hasText(paymentTradeNo, "对账流水号不可以为空"); Assert.hasText(gatewayTradeNo, "银行交易流水号不可以为空"); Assert.hasText(refundSerial, "退款流水号不可以为空"); Assert.notNull(callbackTime, "交易时间不可以为空"); PayPayment payment = payPaymentService.selectByPaymentTradeNoAndObjectId(paymentTradeNo, orderId + ""); payment.setStatus(Constant.PAYMENT_SERIAL_STATUS.SUCCESS.name()); payment.setCallbackTime(callbackTime); payment.setRefundSerial(refundSerial.trim()); payment.setGatewayTradeNo(gatewayTradeNo.trim()); payment.setCallbackInfo("[线下支付]" + memo.trim()); payment.setStatus(Constant.PAYMENT_SERIAL_STATUS.SUCCESS.name()); payment.setOperator(getOperatorName()); payPaymentService.updatePayment(payment); if (payment.isPrePayment()) { // 更新预授权支付数据 payPaymentService.updatePrePayment(payment); } paymentId = payment.getPaymentId(); if (payment != null && payment.isSuccess()) { if (Constant.PAYMENT_BIZ_TYPE.SUPER_ORDER.name().equalsIgnoreCase(payment.getBizType())) { OrdOrder order = orderServiceProxy.queryOrdOrderByOrderId(payment.getObjectId()); if (payment.isPrePayment() && order.isApprovePass()) { Message msg = MessageFactory.newOrderApproveBeforePrepayMessage(order.getOrderId()); msg.setAddition(Constant.PAYMENT_BIZ_TYPE.SUPER_ORDER.name()); orderMessageProducer.sendMsg(msg); } else if (order.isApproveFail()) { orderServiceProxy.autoCreateOrderFullRefund(order, super.getOperatorName(), "资源审核不通过"); } } ComLog log = new ComLog(); log.setObjectId(payment.getPaymentId()); log.setObjectType("PAY_PAYMENT"); log.setParentId(payment.getObjectId()); log.setParentType("ORD_ORDER"); log.setLogType("PAYMENT_TYPE_OFFLINE"); log.setLogName("手工线下支付"); log.setOperatorName(this.getOperatorName()); log.setContent("由操作人员" + getOperatorName() + "使用" + payment.getPayWayZh() + "线下支付方式支付"); log.setCreateTime(new Date()); comLogService.addComLog(log); resourceMessageProducer.sendMsg( MessageFactory.newPaymentSuccessCallMessage(payment.getPaymentId())); } result.put("paymentId", paymentId); } catch (Exception ex) { result.raise(new JSONResultException(ex.getMessage())); } result.output(getResponse()); }
protected void login(String username, String password) { Assert.hasText(username); Assert.hasText(password); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); Authentication authentication = authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); session.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); }
@Override public void unfollow(String followerUsername, String username) { Assert.hasText(followerUsername); Assert.hasText(username); // make sure id's are valid User followerUser = userRepository.findByUsername(followerUsername); User followedUser = userRepository.findByUsername(username); Follower findFollower = followerRepository.findFollower(followedUser.getId(), followerUser.getId()); followerRepository.delete(findFollower); }
protected void buildClient() throws Exception { client = TransportClient.builder().settings(settings()).build(); Assert.hasText(clusterNodes, "[Assertion failed] clusterNodes settings missing."); for (String clusterNode : split(clusterNodes, COMMA)) { String hostName = substringBeforeLast(clusterNode, COLON); String port = substringAfterLast(clusterNode, COLON); Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'"); Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'"); logger.info("adding transport node : " + clusterNode); client.addTransportAddress( new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port))); } client.connectedNodes(); }
@Override public void follow(String followerUsername, String username) { Assert.hasText(followerUsername); Assert.hasText(username); // make sure id's are valid User followerUser = userRepository.findByUsername(followerUsername); User followedUser = userRepository.findByUsername(username); Follower follower = new Follower(); follower.setFollowerId(followerUser.getId()); follower.setUserId(followedUser.getId()); followerRepository.save(follower); }
/** * Set the name of the <em>default</em> {@code Servlet}. * * <p>Also {@link #unregisterNamedDispatcher unregisters} the current default {@link * javax.servlet.RequestDispatcher} and {@link #registerNamedDispatcher replaces} it with a {@link * org.springframework.mock.web.MockRequestDispatcher} for the provided {@code * defaultServletName}. * * @param defaultServletName the name of the <em>default</em> {@code Servlet}; never {@code null} * or empty * @see #getDefaultServletName */ public void setDefaultServletName(String defaultServletName) { Assert.hasText(defaultServletName, "defaultServletName must not be null or empty"); unregisterNamedDispatcher(this.defaultServletName); this.defaultServletName = defaultServletName; registerNamedDispatcher( this.defaultServletName, new MockRequestDispatcher(this.defaultServletName)); }
/** 创建Criteria对象,带排序字段与升降序字段. */ public Criteria createCriteria(String orderBy, boolean isAsc, Criterion... criterions) { Assert.hasText(orderBy); Criteria criteria = createCriteria(criterions); if (isAsc) criteria.addOrder(Order.asc(orderBy)); else criteria.addOrder(Order.desc(orderBy)); return criteria; }
/** * Returns the projection part of the query, i.e. everything between {@code select} and {@code * from}. * * @param query must not be {@literal null} or empty. * @return * @since 1.10.2 */ public static String getProjection(String query) { Assert.hasText(query, "Query must not be null or empty!"); Matcher matcher = PROJECTION_CLAUSE.matcher(query); return matcher.find() ? matcher.group(1) : ""; }
/** * Creates a count projected query from the given original query. * * @param originalQuery must not be {@literal null}. * @param countProjection may be {@literal null}. * @return * @since 1.6 */ public static String createCountQueryFor(String originalQuery, String countProjection) { Assert.hasText(originalQuery, "OriginalQuery must not be null or empty!"); Matcher matcher = COUNT_MATCH.matcher(originalQuery); String countQuery = null; if (countProjection == null) { String variable = matcher.matches() ? matcher.group(VARIABLE_NAME_GROUP_INDEX) : null; boolean useVariable = variable != null && StringUtils.hasText(variable) && !variable.startsWith("new") && !variable.startsWith("count(") && !variable.contains(","); String replacement = useVariable ? SIMPLE_COUNT_VALUE : COMPLEX_COUNT_VALUE; countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, replacement)); } else { countQuery = matcher.replaceFirst(String.format(COUNT_REPLACEMENT_TEMPLATE, countProjection)); } return countQuery.replaceFirst(ORDER_BY_PART, ""); }
public JythonScriptFactory(String scriptSourceLocator, Class[] scriptInterfaces) { Assert.hasText(scriptSourceLocator); Assert.notEmpty(scriptInterfaces); this.scriptSourceLocator = scriptSourceLocator; this.scriptInterfaces = scriptInterfaces; this.arguments = null; }
/** * Will extract the payload from the Message and store it in the collection identified by the key * (which may be determined by an expression). The type of collection is specified by the {@link * #collectionType} property. The default CollectionType is LIST. * * <p>The rules for storing the payload are: * * <p><b>LIST/SET</b> If the payload is of type Collection and {@link #extractPayloadElements} is * 'true' (default), the payload will be added using the addAll() method. If {@link * #extractPayloadElements} is set to 'false', then regardless of the payload type, the payload * will be added using add(). * * <p><b>ZSET</b> In addition to the rules described for LIST/SET, ZSET allows 'score' information * to be provided. The score can be provided using the {@link RedisHeaders#ZSET_SCORE} message * header when the payload is not a Map, or by sending a Map as the payload where each Map 'key' * is a value to be saved and each corresponding Map 'value' is the score assigned to it. If * {@link #extractPayloadElements} is set to 'false' the map will be stored as a single entry. If * the 'score' can not be determined, the default value (1) will be used. * * <p><b>MAP/PROPERTIES</b> You can also add items to a Map or Properties based store. If the * payload itself is of type Map or Properties, it can be stored either as a batch or single item * following the same rules as described above for other collection types. If the payload itself * needs to be stored as a value of the map/property then the map key must be specified via the * mapKeyExpression (default {@link RedisHeaders#MAP_KEY} Message header). */ @SuppressWarnings("unchecked") @Override protected void handleMessageInternal(Message<?> message) throws Exception { String key = this.keyExpression.getValue(this.evaluationContext, message, String.class); Assert.hasText( key, "Failed to determine a key for the Redis store using expression: " + this.keyExpression.getExpressionString()); RedisStore store = this.createStoreView(key); Assert.state( this.initialized, "handler not initialized - afterPropertiesSet() must be called before the first use"); try { if (collectionType == CollectionType.ZSET) { this.writeToZset((RedisZSet<Object>) store, message); } else if (collectionType == CollectionType.SET) { this.writeToSet((RedisSet<Object>) store, message); } else if (collectionType == CollectionType.LIST) { this.writeToList((RedisList<Object>) store, message); } else if (collectionType == CollectionType.MAP) { this.writeToMap((RedisMap<Object, Object>) store, message); } else if (collectionType == CollectionType.PROPERTIES) { this.writeToProperties((RedisProperties) store, message); } } catch (Exception e) { throw new MessageHandlingException( message, "Failed to store Message data in Redis collection", e); } }
@Override public void generateAngularGlobalEntity(GrailsDomainClass grailsDomainClass, String destDir) throws IOException { Assert.hasText(destDir, "Argument [destdir] not specified"); /* Get global template list */ File viewsDir = new File(destDir, "web-app/js/app"); if (!viewsDir.exists()) { viewsDir.mkdirs(); } for (String name : getTemplateNamesFromPath("js/entity")) { File viewsEntityDir = new File(viewsDir.getAbsolutePath() + "/" + grailsDomainClass.getPropertyName()); if (!viewsEntityDir.exists()) { viewsEntityDir.mkdirs(); } generateText( grailsDomainClass, name, viewsDir.getAbsolutePath() + "/" + grailsDomainClass.getPropertyName(), "js/entity", "js"); } }
/** 按属性查找对象列表 */ @Override @SuppressWarnings("unchecked") public List<T> findByProperty(String property, Object value) { Assert.hasText(property); List<T> result = createCriteria(Restrictions.eq(property, value)).list(); return result; }
/** * 使用HQL进行分页查询. * * @param hql 查询条件 * @param pageNo 页号,从1开始. * @param pageSize 每页中的记录数 * @param args HQL的参数 * @return 当前页的分页对象 */ public Page pagedQuery(String hql, int pageNo, int pageSize, Object... args) { Assert.hasText(hql); // 创建查询 Query query = getSession().createQuery(hql); // 根据华南提出的bug做出修正,做是否为null的判断 if (args != null) { for (int i = 0; i < args.length; i++) { query.setParameter(i, args[i]); } } String countQueryString = " SELECT count (*) " + removeSelect(removeOrders(hql)); List countlist = getHibernateTemplate().find(countQueryString, args); long totalCount = (Long) countlist.get(0); // 返回分页对象 if (totalCount < 1) return new Page(); int startIndex = Page.getStartOfPage(pageNo, pageSize); List list; if (!entityQueryCache.isCached(hql, pageNo, pageSize, args)) { logger.debug("Not Using Cache for query: " + hql); list = query.setFirstResult(startIndex).setMaxResults(pageSize).list(); } else { logger.debug("Using Cache for query: " + hql); list = new ArrayList(); for (Iterator it = query.setFirstResult(startIndex).setMaxResults(pageSize).iterate(); it.hasNext(); ) { list.add(it.next()); } } return new Page(startIndex, totalCount, pageSize, list); }
@Override public List<Article> query(String queryString, int size) { Assert.hasText(queryString, "queryString must not be empty!"); SearchResponse searchResponse = transportClient .prepareSearch(INDICE) .setTypes(TYPE) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(QueryBuilders.queryString(queryString)) .setFrom(0) .setSize(size) .setExplain(true) .execute() .actionGet(); SearchHits hits = searchResponse.getHits(); long total = hits.getTotalHits(); logger.debug("search articles result total:{}", total); List<Article> list = new ArrayList<Article>(); Article article = null; for (SearchHit hit : hits) { Long id = (Long) hit.getSource().get("id"); String title = (String) hit.getSource().get(TITLE); String summary = (String) hit.getSource().get(SUMMARY); logger.debug("id:{},title:{},summary:{}", id, title, summary); article = new Article(); article.setId(id); article.setTitle(title); article.setSummary(summary); list.add(article); } return list; }
public SubscribableRedisChannel(RedisConnectionFactory connectionFactory, String topicName) { Assert.notNull(connectionFactory, "'connectionFactory' must not be null"); Assert.hasText(topicName, "'topicName' must not be empty"); this.connectionFactory = connectionFactory; this.redisTemplate = new StringRedisTemplate(connectionFactory); this.topicName = topicName; }
/** * Generate the default classpath resource locations array based on the supplied class. * * <p>For example, if the supplied class is <code>com.example.MyTest</code>, the generated * locations will contain a single string with a value of "classpath:/com/example/MyTest * <code><suffix></code>", where <code><suffix></code> is the value of the {@link * #getResourceSuffix() resource suffix} string. * * <p>As of Spring 3.1, the implementation of this method adheres to the contract defined in the * {@link SmartContextLoader} SPI. Specifically, this method will <em>preemptively</em> verify * that the generated default location actually exists. If it does not exist, this method will log * a warning and return an empty array. * * <p>Subclasses can override this method to implement a different <em>default location * generation</em> strategy. * * @param clazz the class for which the default locations are to be generated * @return an array of default application context resource locations * @since 2.5 * @see #getResourceSuffix() */ protected String[] generateDefaultLocations(Class<?> clazz) { Assert.notNull(clazz, "Class must not be null"); String suffix = getResourceSuffix(); Assert.hasText(suffix, "Resource suffix must not be empty"); String resourcePath = SLASH + ClassUtils.convertClassNameToResourcePath(clazz.getName()) + suffix; String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath; ClassPathResource classPathResource = new ClassPathResource(resourcePath, clazz); if (classPathResource.exists()) { if (logger.isInfoEnabled()) { logger.info( String.format( "Detected default resource location \"%s\" for test class [%s].", prefixedResourcePath, clazz.getName())); } return new String[] {prefixedResourcePath}; } // else if (logger.isInfoEnabled()) { logger.info( String.format( "Could not detect default resource locations for test class [%s]: " + "%s does not exist.", clazz.getName(), classPathResource)); } return EMPTY_STRING_ARRAY; }
/** * Adds single mapping: class <-> alias (id). * * @param clazz * @param id */ public void addClassToId(final Class<?> clazz, final String id) { Assert.notNull(clazz, "Class cannot be null"); Assert.hasText(id, "Alias (id) cannot be null or contain only whitespaces"); if (classToId.containsKey(clazz)) { throw new IllegalArgumentException( "Class " + clazz + " has already defined alias (id) " + classToId.get(clazz) + " cannot set another alias " + id); } if (idToClass.containsKey(id)) { throw new IllegalArgumentException( "Alias (id) " + id + " is used by another class " + idToClass.get(id) + " and cannot be used by " + clazz); } classToId.put(clazz, id); idToClass.put(id, clazz); }
/** 按属性条件参数创建Criterion,辅助函数. */ protected Criterion buildCriterion( final String propertyName, final Object propertyValue, final MatchType matchType) { Assert.hasText(propertyName, "propertyName不能为空"); Criterion criterion = null; // 根据MatchType构造criterion switch (matchType) { case EQ: criterion = Restrictions.eq(propertyName, propertyValue); break; case LIKE: criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE); break; case LE: criterion = Restrictions.le(propertyName, propertyValue); break; case LT: criterion = Restrictions.lt(propertyName, propertyValue); break; case GE: criterion = Restrictions.ge(propertyName, propertyValue); break; case GT: criterion = Restrictions.gt(propertyName, propertyValue); } return criterion; }
/** * Adds {@literal order by} clause to the JPQL query. * * @param query * @param sort * @param alias * @return */ public static String applySorting(String query, Sort sort, String alias) { Assert.hasText(query); if (null == sort || !sort.iterator().hasNext()) { return query; } StringBuilder builder = new StringBuilder(query); if (!ORDER_BY.matcher(query).matches()) { builder.append(" order by "); } else { builder.append(", "); } Set<String> aliases = getOuterJoinAliases(query); for (Order order : sort) { builder.append(getOrderClause(aliases, alias, order)).append(", "); } builder.delete(builder.length() - 2, builder.length()); return builder.toString(); }
/** * 添加cookie * * @param request HttpServletRequest * @param response HttpServletResponse * @param name cookie名称 * @param value cookie�? * @param maxAge 有效�?单位: �? * @param path 路径 * @param domain �? * @param secure 是否启用加密 */ public static void addCookie( HttpServletRequest request, HttpServletResponse response, String name, String value, Integer maxAge, String path, String domain, Boolean secure) { Assert.notNull(request); Assert.notNull(response); Assert.hasText(name); try { name = URLEncoder.encode(name, "UTF-8"); value = URLEncoder.encode(value, "UTF-8"); Cookie cookie = new Cookie(name, value); if (maxAge != null) { cookie.setMaxAge(maxAge); } if (StringUtils.isNotEmpty(path)) { cookie.setPath(path); } if (StringUtils.isNotEmpty(domain)) { cookie.setDomain(domain); } if (secure != null) { cookie.setSecure(secure); } response.addCookie(cookie); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
/** 按属性查找唯一对象 */ @Override @SuppressWarnings("unchecked") public T findUniqueByProperty(String property, Object value) { Assert.hasText(property); Assert.notNull(value); return (T) createCriteria(Restrictions.eq(property, value)).uniqueResult(); }
/** * Creates a new {@link DefaultCurieProvider} for the given curies using the one with the given * name as default, which means to expand unprefixed, non-IANA link relations. * * @param curies must not be {@literal null}. * @param defaultCurieName can be {@literal null}. * @since 0.19 */ public DefaultCurieProvider(Map<String, UriTemplate> curies, String defaultCurieName) { Assert.notNull(curies, "Curies must not be null!"); Map<String, Curie> map = new HashMap<String, Curie>(curies.size()); for (Entry<String, UriTemplate> entry : curies.entrySet()) { String name = entry.getKey(); UriTemplate template = entry.getValue(); Assert.hasText(name, "Curie name must not be null or empty!"); Assert.notNull(template, "UriTemplate must not be null!"); Assert.isTrue( template.getVariableNames().size() == 1, String.format( "Expected a single template variable in the UriTemplate %s!", template.toString())); map.put(name, new Curie(name, template.toString())); } this.defaultCurie = StringUtils.hasText(defaultCurieName) ? map.get(defaultCurieName) : map.size() == 1 ? map.values().iterator().next() : null; this.curies = Collections.unmodifiableMap(map); }