Authored by ken.hu

delete useless

Showing 21 changed files with 2 additions and 1378 deletions
package com.yohoufo.resource.helper;
/**
* Created by chenchao on 2017/8/29.
*/
public enum DisplayType {
//1:商品价格;2:店铺;
product(1), shop(2);
private int intVal;
DisplayType(int intVal) {
this.intVal = intVal;
}
public int getIntVal() {
return intVal;
}
}
package com.yohoufo.resource.helper;
/**
* Created by chenchao on 2017/8/29.
*/
public class FilterNode {
public int displayType;
public int urlType;
public FilterNode(int displayType, int urlType) {
this.displayType = displayType;
this.urlType = urlType;
}
}
... ... @@ -24,8 +24,8 @@ import com.yoho.core.rest.client.ServiceCaller;
import com.yoho.product.model.BrandBo;
import com.yoho.product.request.BaseRequest;
import com.yohoufo.common.redis.NoSyncGracefulRedisTemplate;
import com.yohoufo.common.utils.Constant;
import com.yohoufo.resource.service.impl.cache.ExpireTime;
import com.yohoufo.resource.util.Constant;
import com.yohoufo.resource.util.ResourcesKeyBuilder;
/**
... ...
package com.yohoufo.resource.helper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yoho.product.model.plan.ProductPricePlanBo;
import com.yohoufo.resource.util.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ProductPricePlanHelper {
public static void handlerPrice(JSONObject product) {
JSONArray planList =product.getJSONArray("product_price_plan_list");
if(CollectionUtils.isEmpty(planList)){
return;
}
ProductPricePlanBo productPricePlanBo=ProductPricePlanHelper.getEffectProductPricePlan(convert(planList));
//没有符合的价格计划,直接返回
if(null==productPricePlanBo){
return;
}
if(null!=productPricePlanBo.getCurrentSalePrice()){
product.replace("sales_price", getIntCeilPrice(productPricePlanBo.getCurrentSalePrice()));
}
if(null!=productPricePlanBo.getVip1Price()){
product.replace("vip1_price", productPricePlanBo.getVip1Price());
}
if(null!=productPricePlanBo.getVip2Price()){
product.replace("vip2_price", productPricePlanBo.getVip2Price());
}
if(null!=productPricePlanBo.getVip3Price()){
product.replace("vip3_price", productPricePlanBo.getVip3Price());
}
if(null!=productPricePlanBo.getVipDiscountType()){
product.replace("vip_discount_type", productPricePlanBo.getVipDiscountType());
}
if(null!=product.get("student_price") && !"Y".equalsIgnoreCase(product.getString("is_student_price"))){
product.replace("student_price", product.getBigDecimal("sales_price").multiply(new BigDecimal("0.9")));
}
}
public static List<ProductPricePlanBo> convert(JSONArray planList){
if(CollectionUtils.isEmpty(planList)){
return null;
}
List<ProductPricePlanBo> productPricePlanBoList=Lists.newArrayList();
ProductPricePlanBo productPricePlanBo=null;
for (int index = 0; index < planList.size(); index++) {
productPricePlanBo =new ProductPricePlanBo();
JSONObject product = planList.getJSONObject(index);
productPricePlanBo.setCurrentSalePrice(product.getDouble("current_saleprice"));
productPricePlanBo.setEffectTime(product.getInteger("effect_time"));
productPricePlanBo.setEndTime(product.getInteger("end_time"));
productPricePlanBo.setProductSkn(product.getInteger("product_skn"));
productPricePlanBo.setSpecialPrice(product.getDouble("special_price"));
productPricePlanBoList.add(productPricePlanBo);
}
return productPricePlanBoList;
}
//获取取整的价格
public static Integer getIntCeilPrice(Double price){
return (int)Math.ceil(price);
}
/**
* 获取一个生效的变价计划
* @param list
* @return
*/
public static ProductPricePlanBo getEffectProductPricePlan(List<ProductPricePlanBo> list){
if(CollectionUtils.isEmpty(list)){
return null;
}
//先计算匹配到的价格计划,然后根据匹配到的价格计划求优先级
long currentTime= DateUtils.getDateOfSenconds();
List<ProductPricePlanBo> fitProductPricePlanBoList=Lists.newArrayList();
for (ProductPricePlanBo productPricePlanBo : list) {
//当前时间大于等于生效时间且当前时间小于结束时间或没有结束时间的
if(currentTime>=productPricePlanBo.getEffectTime() && (currentTime<=productPricePlanBo.getEndTime()||productPricePlanBo.getEndTime()==0)){
fitProductPricePlanBoList.add(productPricePlanBo);
}
}
if(CollectionUtils.isNotEmpty(fitProductPricePlanBoList)){
//在多个价格计划都满足的情况下,生效时间越大越靠前
Collections.sort(fitProductPricePlanBoList, new Comparator<ProductPricePlanBo>() {
@Override
public int compare(ProductPricePlanBo o1, ProductPricePlanBo o2) {
return o2.getEffectTime().compareTo(o1.getEffectTime());
}
});
return fitProductPricePlanBoList.get(0);
}
return null;
}
}
package com.yohoufo.resource.helper;
import com.google.common.collect.Maps;
import com.yohoufo.dal.resource.model.ResourcesContentData;
import org.apache.commons.collections.CollectionUtils;
import java.util.List;
import java.util.Map;
/**
* Created by chenchao on 2017/6/29.
*/
public class ResourcesContentDataHelper {
public static ResourcesContentData getResourcesContentData(Integer resourcesContentId, Map<Integer,ResourcesContentData> map) {
if(!map.containsKey(resourcesContentId)){
return null;
}else{
return map.get(resourcesContentId);
}
}
public static Map<Integer,ResourcesContentData> buildResourcesContentDataMap(List<ResourcesContentData> resourcesContentDatas) {
if (CollectionUtils.isEmpty(resourcesContentDatas)){
return Maps.newHashMap();
}
final Map<Integer,ResourcesContentData> map = Maps.newHashMap();
resourcesContentDatas.forEach(rcd -> {
map.put(rcd.getResourceContentId(), rcd);
});
return map;
}
}
package com.yohoufo.resource.helper;
import org.apache.commons.lang3.StringUtils;
/**
* Created by chenchao on 2017/8/29.
*/
public final class UrlHelper {
public static final String H5_DOMAIN = "https://m.yohobuy.com";
public static final String URL = "www.yohobuy.com";
/**
* https://m.yohobuy.com/product/51152801.html
* @param skn
* @return
*/
public static String makePrdUrl(String skn){
if (StringUtils.isBlank(skn)){
return null;
}
return new StringBuilder(H5_DOMAIN).append("/product/").append(skn).append(".html").toString();
}
}
package com.yohoufo.resource.helper;
import com.alibaba.fastjson.JSONObject;
/**
* Created by chenchao on 2017/8/29.
*/
public class UrlNode {
public String url = "www.yohobuy.com";
JSONObject params ;
public String clientType;
public String gender;
public UrlNode(String url, JSONObject params, String clientType, String gender) {
this.url = url;
this.params = params;
this.clientType = clientType;
this.gender = gender;
}
}
package com.yohoufo.resource.helper;
/**
* Created by chenchao on 2017/8/29.
*/
public enum UrlType {
//1:商品详情;2:商品列表
detail(1), list(2);
private int intVal;
UrlType(int intVal){
this.intVal = intVal;
}
public int getIntVal() {
return intVal;
}
public static UrlType getUrlType(int intVal){
if(intVal == detail.intVal){
return detail;
}
if(intVal == list.intVal){
return list;
}
return detail;
}
}
... ... @@ -10,12 +10,12 @@ import com.yoho.product.request.ShopsFocusRequest;
import com.yoho.service.model.resource.request.RecommendReqVO;
import com.yoho.service.model.resource.resource.FocusParsedResource;
import com.yohoufo.common.redis.NoSyncGracefulRedisTemplate;
import com.yohoufo.common.utils.JSONConvert;
import com.yohoufo.resource.helper.MakeUrlService;
import com.yohoufo.resource.service.IResourceParse;
import com.yohoufo.resource.service.Resource;
import com.yohoufo.resource.service.impl.cache.ExpireTime;
import com.yohoufo.resource.service.impl.cache.FocusCacheService;
import com.yohoufo.resource.util.JSONConvert;
import com.yohoufo.resource.util.ResourcesKeyBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
... ...
package com.yohoufo.resource.util;
import com.yoho.error.ServiceError;
import com.yoho.error.exception.ServiceException;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.Map;
/**
* Created by yoho on 2015/11/9.
*/
public abstract class Assert {
public static void isTrue(boolean expression, ServiceError errorCode) {
if (!expression) {
throw new ServiceException(errorCode);
}
}
public static void isTrue(boolean expression) {
isTrue(expression, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void isNull(Object object, ServiceError errorCode) {
if (object != null) {
throw new ServiceException(errorCode);
}
}
public static void isNull(Object object) {
isNull(object, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void notNull(Object object, ServiceError errorCode) {
if (object == null) {
throw new ServiceException(errorCode);
}
}
public static void notNull(Object object) {
notNull(object, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void hasLength(String text, ServiceError errorCode) {
if (!StringUtils.hasLength(text)) {
throw new ServiceException(errorCode);
}
}
public static void hasLength(String text) {
hasLength(text, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void hasText(String text, ServiceError errorCode) {
if (!StringUtils.hasText(text)) {
throw new ServiceException(errorCode);
}
}
public static void hasText(String text) {
hasText(text, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void doesNotContain(String textToSearch, String substring, ServiceError errorCode) {
if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) && textToSearch.contains(substring)) {
throw new ServiceException(errorCode);
}
}
public static void doesNotContain(String textToSearch, String substring) {
doesNotContain(textToSearch, substring, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void notEmpty(Object[] array, ServiceError errorCode) {
if (ObjectUtils.isEmpty(array)) {
throw new ServiceException(errorCode);
}
}
public static void notEmpty(Object[] array) {
notEmpty(array, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void noNullElements(Object[] array, ServiceError errorCode) {
if (array != null) {
Object[] var2 = array;
int var3 = array.length;
for (int var4 = 0; var4 < var3; ++var4) {
Object element = var2[var4];
if (element == null) {
throw new ServiceException(errorCode);
}
}
}
}
public static void noNullElements(Object[] array) {
noNullElements(array, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void notEmpty(Collection<?> collection, ServiceError errorCode) {
if (CollectionUtils.isEmpty(collection)) {
throw new ServiceException(errorCode);
}
}
public static void notEmpty(Collection<?> collection) {
notEmpty(collection, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void notEmpty(Map<?, ?> map, ServiceError errorCode) {
if (CollectionUtils.isEmpty(map)) {
throw new ServiceException(errorCode);
}
}
public static void notEmpty(Map<?, ?> map) {
notEmpty(map, ServiceError.RESOURCES_REQUEST_ERROR);
}
public static void state(boolean expression, ServiceError errorCode) {
if (!expression) {
throw new ServiceException(errorCode);
}
}
public static void state(boolean expression) {
state(expression, ServiceError.RESOURCES_SERVICE_ERROR);
}
}
\ No newline at end of file
package com.yohoufo.resource.util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanCopier;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BeanUtils {
static Logger log = LoggerFactory.getLogger(BeanUtils.class);
public static <T>T copyBeans(Class<T> targetClazz, Object... sources){
if(null == sources || sources.length == 0){
return null;
}
T targetObj = null;
try{
targetObj = targetClazz.newInstance();
for(Object sourceObj: sources){
BeanCopier copier = BeanCopier.create(sourceObj.getClass(), targetClazz, false);
copier.copy(sourceObj, targetObj, null);
}
}catch(Exception e){
e.printStackTrace();
return null;
}
return targetObj;
}
/**
* 将list转为map
* @param list
* @param keyName
* @param keyClass
* @param valueClass
* @return
*/
public static <K, V> Map<K, V> list2map(List<V> list, String keyName, Class<K> keyClass, Class<V> valueClass) {
if (list == null || StringUtils.isEmpty(keyName)) {
return null;
}
Map<K, V> map = new HashMap<K, V>();
for (V o : list) {
for (Field field : valueClass.getDeclaredFields()) {
field.setAccessible(true);
if (keyName.equals(field.getName())) {
try {
map.put((K) field.get(o), o);
} catch (IllegalArgumentException | IllegalAccessException e) {
log.error("", e);
}
break;
}
}
}
return map;
}
/**
* arr转为map
* @param arr
* @param keyName
* @param keyClass
* @param valueClass
* @return
*/
public static <K, V> Map<K, V> array2map(V[] arr, String keyName, Class<K> keyClass, Class<V> valueClass) {
if (arr == null || StringUtils.isEmpty(keyName)) {
return null;
}
Map<K, V> map = new HashMap<K, V>();
for (V o : arr) {
for (Field field : valueClass.getDeclaredFields()) {
field.setAccessible(true);
if (keyName.equals(field.getName())) {
try {
map.put((K) field.get(o), o);
} catch (IllegalArgumentException | IllegalAccessException e) {
log.error("", e);
}
break;
}
}
}
return map;
}
//list 转逗号分隔String
public static String listToString(List list) {
StringBuilder sb = new StringBuilder();
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) {
sb.append(list.get(i)).append(',');
} else {
sb.append(list.get(i));
}
}
}
return sb.toString();
}
}
package com.yohoufo.resource.util;
public enum ClientType {
IPHONE,ANDROID,H5,WEB,IPAD,YOHO
}
package com.yohoufo.resource.util;
/**
* 模块中的常量声明
*/
public final class Constant {
/**
* html 版本 用于修改静态文件和逛html结构时更新缓存
*/
public static final String HTML_VERSION = "1.0.0";
public static final String UTF8 = "UTF-8";
public static final String EMPTY_STRING = "";
public static final String WEB = "web";
public static final String RESOURCES_METADATA_CACHE = "resources_metadata_cache";
}
package com.yohoufo.resource.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* @author xieyong
*
*/
public final class DateUtils {
private final static String DEFAULT_FOMARTPATTER="yyyy-MM-dd HH:mm:ss";
public final static String DEFAULT_FOMART_DATE="yyyy-MM-dd";
/**
* 将数据库中的UNIX_Time(该时间是距离1970年的秒数,在转换过程中先要换算成毫秒)转换成UTC时间
* @param time
* @return
*/
public static String getDateString(long time)
{
SimpleDateFormat sdf=new SimpleDateFormat(DEFAULT_FOMARTPATTER);
Calendar c=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.setTime(new Date (time*1000));
return sdf.format(c.getTime());
}
/**
*
* @param time 获取数据库中的UNIX_Time(该时间是距离1970年的秒数,在转换过程中先要换算成毫秒)中的月份信息
* @return
*/
public static int getDateOfMonth(long time)
{
Calendar c=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.setTime(new Date (time*1000));
return c.get(Calendar.MONTH)+1;
}
/**
* @param time 获取数据库中的UNIX_Time(该时间是距离1970年的秒数,在转换过程中先要换算成毫秒)中的天信息
* @return
*/
public static int getDateOfDay(long time)
{
Calendar c=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.setTime(new Date (time*1000));
return c.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取 格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数
* @return
* @throws ParseException
*/
public static long getDateOfSenconds()
{
Calendar c=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.setTime(new Date());
return c.getTimeInMillis()/1000;
}
/**
* 获取 格林威治时间 2050 年 1 月 1 日 00:00:00)减去某时间差
* @return
* @throws ParseException
*/
public static long getTimeDifference(long dateSecond)
{
Calendar c=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.set(2050, 1, 1);
return c.getTimeInMillis()/1000 - dateSecond;
}
/**
* 获取unix的秒时间
* @return
*/
public static int getUnixTime()
{
return (int)(new Date().getTime() / 1000);
}
/**
* 获取unix的秒时间
* @return
*/
public static int getDateOfSenconds(String dateStr, String dateFormat)
{
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date parse;
try {
parse = sdf.parse(dateStr);
} catch (ParseException e) {
parse = new Date();
}
return (int)(parse.getTime() / 1000);
}
/**
* 目的是:搜索命中缓存
*/
public static int getIntervalTimeSecondStart(int interval){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_YEAR, interval);
return (int)(cal.getTimeInMillis() / 1000);
}
/**
* 目的是:搜索命中缓存
*/
public static int getCurrentTimeSecondEnd(){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 24);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return (int)(cal.getTimeInMillis() / 1000);
}
}
package com.yohoufo.resource.util;
import java.security.MessageDigest;
public class EncoderUtil {
private static final String ALGORITHM = "MD5";
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* encode string
*
* @param algorithm
* @param str
* @return String
*/
public static String encode(String algorithm, String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* encode By MD5
*
* @param str
* @return String
*/
public static String encodeByMD5(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM);
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Takes the raw bytes from the digest and formats them correct.
*
* @param bytes the raw bytes from the digest.
* @return the formatted bytes.
*/
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j < len;
j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
public static void main(String[] args) {
System.out.println("111111 MD5 :"
+ EncoderUtil.encodeByMD5("111111"));
System.out.println("111111 MD5 :"
+ EncoderUtil.encode("MD5", "111111"));
System.out.println("111111 SHA1 :"
+ EncoderUtil.encode("SHA1", "111111"));
}
}
\ No newline at end of file
package com.yohoufo.resource.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created by yoho on 2015/11/12.
*/
public class ExecutorServiceUtil {
private static Logger logger = LoggerFactory.getLogger(ExecutorServiceUtil.class);
public static void shutdownAndAwaitTermination(ExecutorService pool) {
shutdownAndAwaitTermination(pool, 10, TimeUnit.SECONDS);
}
public static void shutdownAndAwaitTermination(ExecutorService pool, long timeout, TimeUnit unit) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(timeout, unit)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(timeout, unit)) {
logger.error("Pool did not terminate");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
}
package com.yohoufo.resource.util;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.CRC32;
/**
* Created by yoho on 2015/11/4.
*/
public class Images {
private static final Map<String, String[]> DOMAINS;
private static final String QINIU_DOMAIN = "yhfair.qiniudn.com";
public static final List<String> IMAGESERVICES;
static {
DOMAINS = new HashMap<String, String[]>();
DOMAINS.put( "01", new String[] { "img10.static.yhbimg.com", "img11.static.yhbimg.com" } );
DOMAINS.put( "02", new String[] { "img12.static.yhbimg.com", "img13.static.yhbimg.com" } );
DOMAINS.put( "yhb-head", new String[] { "head.static.yhbimg.com" } );
}
static {
IMAGESERVICES = new ArrayList<>();
IMAGESERVICES.add( "http://img03.static.yhbimg.com" );
IMAGESERVICES.add( "http://img04.static.yhbimg.com" );
IMAGESERVICES.add( "http://img05.static.yhbimg.com" );
IMAGESERVICES.add( "http://img06.static.yhbimg.com" );
}
/**
* 根据尺寸获得图片url
*/
public static String getImageUrl( String fileName, int width, int height ) {
return getImageUrl( fileName, width, height, 1 );
}
/**
* 根据尺寸获得图片url
*/
public static String getImageUrl( String fileName, int width, int height, int mode ) {
return getImageUrl( fileName, width, height, mode, "yhfair" );
}
/**
* 根据尺寸获得图片url
*/
public static String getImageUrl( String fileName, int width, int height, int mode, String bucket ) {
if ( !fileName.contains( "http://" ) ) {
fileName = template( fileName, bucket, mode );
}
return fileName.replace( "{width}", String.valueOf( width ) ).replace( "{height}", String.valueOf( height ) )
.replace( "{mode}", String.valueOf( mode ) );
}
/**
* 缩略图模板
*/
public static String template( String fileName, String bucket ) {
return template( fileName, bucket, 1 );
}
/**
* 缩略图模板
*/
public static String template( String fileName, String bucket, int mode ) {
if ( StringUtils.isEmpty( bucket ) ) {
bucket = "yhfair";
}
return url( fileName, bucket, mode );
}
/**
* 缩略图模板
*
* @return
*/
public static String template2( String fileName, String bucket ) {
return template2( fileName, bucket, "center" );
}
/**
* 缩略图模板
*
* @return
*/
public static String template2( String fileName, String bucket, String position ) {
return template2( fileName, bucket, position, "d2hpdGU=" );
}
/**
* 缩略图模板
*
* @return
*/
public static String template2( String fileName, String bucket, String position, String background ) {
String domain = getDomain( bucket, fileName );
String key = bucket + fileName;
StringBuilder template = new StringBuilder();
template.append( makeBaseUrl( domain, key ) );
template.append( "?imageMogr2/thumbnail/{width}x{height}/extent/{width}x{height}/background/" );
template.append( background );
template.append( "/position/" );
template.append( position );
template.append( "/quality/90" );
return template.toString();
}
/**
* 获取图片URL模板
*/
public static String url( String fileName, String bucket, int mode ) {
String domain = getDomain( bucket, fileName );
return getImgTemplateUrl( bucket + fileName, mode, domain );
}
public static String makeUrl( String fileName, String bucket ) {
if ( StringUtils.isEmpty( bucket ) ) {
bucket = "yhfair";
}
String domain = getDomain( bucket, fileName );
if ( domain == null ) {
return QINIU_DOMAIN;
}
return makeBaseUrl( domain, bucket + fileName );
}
public static String getDomain( String bucket, String fileName ) {
if ( DOMAINS.get( bucket ) != null ) {
String[] domains = DOMAINS.get( bucket );
return domains[ 0 ];
} else if ( fileName != null && fileName.length() > 17 ) {
String node = fileName.substring( 15, 17 );
if ( DOMAINS.get( node ) != null ) {
String[] domains = DOMAINS.get( node );
int nodeNum = (int) ( crc32( fileName ) % domains.length );
return domains[ nodeNum ];
}
}
return Constant.EMPTY_STRING;
}
private static long crc32( String fileName ) {
CRC32 crc32 = new CRC32();
crc32.update( fileName.getBytes() );
return crc32.getValue();
}
/**
* 获取模板的图片地址
*/
private static String getImgTemplateUrl( String fileName, int mode, String domain ) {
if ( domain == null ) {
return QINIU_DOMAIN;
}
String baseUrl = makeBaseUrl( domain, fileName );
return makeTemplateRequest( baseUrl );
}
private static String makeBaseUrl( String domain, String key ) {
try {
String keyEsc = URLEncoder.encode( key, StandardCharsets.UTF_8.name() ).replace( "%2F", "/" );
return String.format( "http://%s/%s", domain, keyEsc );
} catch ( UnsupportedEncodingException e ) {
return Constant.EMPTY_STRING;
}
}
//20160418增加需求,七牛图片解析地址由 ?imageView/{mode}修改为?imageView2/{mode}:防止图片过大
public static String makeTemplateRequest( String url ) {
return url + "?imageView2/{mode}/w/{width}/h/{height}";
}
}
package com.yohoufo.resource.util;
/**
* 图片路径中“Bucket”定义,用于分类管理
* Created by xueyin on 16/3/8.
* ISSUE1: 新平台端供应商使用yhb-img01/02方式
* ISSUE2: 新平台端店铺使用yhb-img01/02方式
*/
public interface ImagesConstant {
//
String YHB_HEAD = "yhb-head";
// 系统Bucket常量定义
// 兼容bucket,当找不到时,默认使用以下两个bucket
String BUCKET_YHB_IMG01 = "yhb-img01";
String BUCKET_YHB_IMG02 = "yhb-img02";
// 如ISSUES: 下面两个bucket是为了兼容线上平台端
String BUCKET_SUPPLIER = BUCKET_YHB_IMG02;
String BUCKET_SHOPS = BUCKET_YHB_IMG01;
String BUCKET_PASSPORT = "PASSPORT";
// 商品图片,与前台兼容
String BUCKET_GOODS_IMG = "goodsimg";
// 商品视频图片,新增
String BUCKET_GOODS_VIDEO = "goodsvideo";
// 晒单图片,与前台兼容
String BUCKET_SNS = "sns";
// 退换货图片,与前台兼容
String BUCKET_EVIDENCE = "evidenceImages";
// 品牌图片,与前台兼容
String BUCKET_BRAND_LOGO = "brandLogo";
// 销售类目图片
String BUCKET_SALES_CATEGORY = "taobaocms";
// 活动图片
String BUCKET_ACTIVITY_PIC = "activity";
// 逛-资讯图片
String BUCKET_ARTICLE = "article";
// 逛-作者图片
String BUCKET_AUTHOR = "author";
// 逛明星图片
String BUCKET_PLUSTAR = "plustar";
String BUCKET_TAGS = "articleTags";
// 逛-品牌关注图片
String BUCKET_RELATIONSHIP = "relationship";
// 模特卡片
String BUCKET_MODELCARD = "modelCard";
//品牌款型系列
String BUCKET_BRANDBANNER = "brandBanner";
//颜色
String BUCKET_COLOR = "color";
//文件
String BUCKET_ZIP = "yohobuyzip";
//优惠券活动-分享图片
String BUCKET_COUPON_IMAGE = "couponImage";
//优惠券活动-背景图片
String BUCKET_COUPON_BG_IMAGE = "couponBgImg";
// 帮助中心
String BUCKET_HELPER_LOGO = "helper";
}
package com.yohoufo.resource.util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
/**
* 七牛云图片上传辅助工具类 qianjun
*/
public class ImagesHelper {
private static final Logger logger = LoggerFactory.getLogger(ImagesHelper.class);
// 当前域名列表
private static final Map<String, String[]> DOMAIN_LIST;
// 当前bucket列表
private static final Map<String, String> BUCKET_LIST;
static {
DOMAIN_LIST = new HashMap<>();
DOMAIN_LIST.put("01", new String[] { "img10.static.yhbimg.com", "img11.static.yhbimg.com" });
DOMAIN_LIST.put("02", new String[] { "img12.static.yhbimg.com", "img13.static.yhbimg.com" });
DOMAIN_LIST.put("03", new String[] { "flv01.static.yhbimg.com", "flv01.static.yhbimg.com" });
DOMAIN_LIST.put("yhb-head", new String[] { "head.static.yhbimg.com", "head.static.yhbimg.com" });
BUCKET_LIST = new HashMap<>();
BUCKET_LIST.put(ImagesConstant.BUCKET_YHB_IMG01, ImagesConstant.BUCKET_YHB_IMG01);
BUCKET_LIST.put(ImagesConstant.BUCKET_YHB_IMG02, ImagesConstant.BUCKET_YHB_IMG02);
BUCKET_LIST.put(ImagesConstant.BUCKET_PASSPORT, ImagesConstant.YHB_HEAD);
BUCKET_LIST.put(ImagesConstant.BUCKET_GOODS_IMG, ImagesConstant.BUCKET_GOODS_IMG);
BUCKET_LIST.put(ImagesConstant.BUCKET_SNS, ImagesConstant.BUCKET_SNS);
BUCKET_LIST.put(ImagesConstant.BUCKET_EVIDENCE, ImagesConstant.BUCKET_EVIDENCE);
BUCKET_LIST.put(ImagesConstant.BUCKET_BRAND_LOGO, ImagesConstant.BUCKET_BRAND_LOGO);
BUCKET_LIST.put(ImagesConstant.BUCKET_GOODS_VIDEO, ImagesConstant.BUCKET_GOODS_VIDEO);
BUCKET_LIST.put(ImagesConstant.BUCKET_ACTIVITY_PIC, ImagesConstant.BUCKET_ACTIVITY_PIC);
BUCKET_LIST.put(ImagesConstant.BUCKET_PLUSTAR, ImagesConstant.BUCKET_PLUSTAR);
BUCKET_LIST.put(ImagesConstant.BUCKET_TAGS, ImagesConstant.BUCKET_TAGS);
BUCKET_LIST.put(ImagesConstant.BUCKET_RELATIONSHIP, ImagesConstant.BUCKET_RELATIONSHIP);
BUCKET_LIST.put(ImagesConstant.BUCKET_AUTHOR, ImagesConstant.BUCKET_AUTHOR);
BUCKET_LIST.put(ImagesConstant.BUCKET_ARTICLE, ImagesConstant.BUCKET_ARTICLE);
BUCKET_LIST.put(ImagesConstant.BUCKET_MODELCARD, ImagesConstant.BUCKET_MODELCARD);
BUCKET_LIST.put(ImagesConstant.BUCKET_BRANDBANNER, ImagesConstant.BUCKET_BRANDBANNER);
BUCKET_LIST.put(ImagesConstant.BUCKET_COLOR, ImagesConstant.BUCKET_COLOR);
BUCKET_LIST.put(ImagesConstant.BUCKET_SALES_CATEGORY, ImagesConstant.BUCKET_SALES_CATEGORY);
BUCKET_LIST.put(ImagesConstant.BUCKET_ZIP, ImagesConstant.BUCKET_ZIP);
BUCKET_LIST.put(ImagesConstant.BUCKET_COUPON_IMAGE, ImagesConstant.BUCKET_COUPON_IMAGE);
BUCKET_LIST.put(ImagesConstant.BUCKET_COUPON_BG_IMAGE, ImagesConstant.BUCKET_COUPON_BG_IMAGE);
BUCKET_LIST.put(ImagesConstant.BUCKET_HELPER_LOGO, ImagesConstant.BUCKET_HELPER_LOGO);
}
/**
* 场景:前台传的是图片绝对路径,数据库存储需要图片相对路径 获取图片相对路径
*
* @param fileName
* 图片的绝对地址
* http://img01.static.yhbimg.com/goodsimg/2016/03/07/13/01f
* 0024f3dc6f0885f370281a2b41c8bfb.png
* @param bucket
* bucket, 由ImageConstant中定义
*
*/
public static String getImageRelativeUrl(String fileName, String bucket) {
if (fileName == null) {
logger.warn("getImageRelativeUrl fail, fileName is null");
return null;
}
if (StringUtils.isEmpty(fileName) || !isValidBucket(bucket)) {
logger.warn("getImageRelativeUrl fail, invalid param[file:{}, bucket:{}].", fileName, bucket);
return "";
}
logger.info("getImageRelativeUrl by fileName[{}] bucket[{}].", fileName, bucket);
String subfileName = fileName.substring(fileName.indexOf(bucket));
return subfileName.substring(subfileName.indexOf('/'));
}
/**
* 场景:前台传的是图片绝对路径,数据库存储需要图片相对路径 批量图片处理 获取图片相对路径
*
* @param fileName
* 图片的绝对地址
* @param bucket
* bucket, 由ImageConstant中定义
*
*/
public static String getBatchImageRelativeUrls(String fileName, String bucket) {
if (StringUtils.isEmpty(fileName) || !isValidBucket(bucket)) {
logger.warn("getImageRelativeUrls fail, invalid param[file:{}, bucket:{}].", fileName, bucket);
return null;
}
logger.info("getImageRelativeUrls by fileName[{}] bucket[{}].", fileName, bucket);
String[] imagePaths = fileName.split(",");
List<String> imageRelativeUrls = new ArrayList<String>(imagePaths.length);
for (String imagePath : imagePaths) {
String subImagePath = imagePath.substring(fileName.indexOf(bucket));
imageRelativeUrls.add(subImagePath.substring(subImagePath.indexOf('/')));
}
return StringUtils.join(imageRelativeUrls, ",");
}
/**
* 场景:数据库存储是图片相对路径,前台需要图片绝对路径 获取图片绝对路径
*
* @param fileName
* 图片的相对地址 /2016/03/07/13/01f0024f3dc6f0885f370281a2b41c8bfb.png
* @param bucket
* bucket, 由ImageConstant中定义
*
*/
public static String getImageAbsoluteUrl(String fileName, String bucket) {
if (StringUtils.isEmpty(fileName) || !isValidBucket(bucket)) {
logger.warn("getImageAbsoluteUrl fail, invalid param[file:{}, bucket:{}].", fileName, bucket);
return "";
}
// 兼容旧版本绝对URL地址
if (fileName.trim().toLowerCase().startsWith("http://")) {
// 旧版本url中可能会带参数,直接去掉
if (-1 != fileName.indexOf('?')) {
// 去掉后面的参数后返回
return fileName.substring(0, fileName.indexOf('?'));
} else {
return fileName;
}
}
logger.info("getImageAbsoluteUrl by fileName[{}] bucket[{}].", fileName, bucket);
if (fileName.length() <= 17) { // 不合法的脏数据,直接返回空
return "";
}
String fileMode = "";
try {
fileMode = fileName.substring(15, 17);
if (DOMAIN_LIST.get(fileMode) == null) {
logger.warn("getImageAbsoluteUrl by fileName[{}] bucket[{}] fail.", fileName, bucket);
return "";
}
} catch (Exception e) {
logger.warn("getImageAbsoluteUrl exception:", e);
return fileName;
}
// 随机从两个域名中获取
String[] domains = DOMAIN_LIST.get(fileMode);
int domainMode = new Random().nextInt(2);
return "http://" + domains[domainMode] + File.separator + bucket + fileName;
}
/**
* 场景:数据库存储是图片相对路径,前台需要图片绝对路径 批量图片处理 获取图片绝对路径
*
* @param fileName
* 图片的相对地址 /2016/03/07/13/01f0024f3dc6f0885f370281a2b41c8bfb.png
* @param bucket
* bucket, 由ImageConstant中定义
*
*/
public static String getBatchImageAbsoluteUrls(String fileName, String bucket) {
if (StringUtils.isEmpty(fileName) || !isValidBucket(bucket)) {
logger.warn("getImageAbsoluteUrls fail, invalid param[file:{}, bucket:{}].", fileName, bucket);
return "";
}
logger.info("getImageAbsoluteUrls by fileName[{}] bucket[{}].", fileName, bucket);
String[] imagePaths = fileName.split(",");
List<String> imageAbsoluteUrls = new ArrayList<String>(imagePaths.length);
int domainMode = new Random().nextInt(2);
for (String imagePath : imagePaths) {
String fileMode = imagePath.substring(15, 17);
if (DOMAIN_LIST.get(fileMode) == null) {
logger.warn("getImageAbsoluteUrls by fileName[{}] bucket[{}] fail.", fileName, bucket);
return "";
}
// 随机从两个域名中获取
String[] domains = DOMAIN_LIST.get(fileMode);
imageAbsoluteUrls.add("http://" + domains[domainMode] + File.separator + bucket + imagePath);
}
return StringUtils.join(imageAbsoluteUrls, ",");
}
/**
* 检查bucket是否有效
*
* @param bucket
*/
public static boolean isValidBucket(String bucket) {
return BUCKET_LIST.containsKey(bucket);
}
}
\ No newline at end of file
package com.yohoufo.resource.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.HashSet;
import java.util.Set;
/**
* Created by yoho on 2016/4/14.
*/
public class JSONConvert {
/**
* PHP JSONArray {"0":"a","1":"b","2","c"} 转换成 JAVA JSONArray ["a","b","c"]
*
* @param json
* @return
*/
public static JSONArray transform2JSONArray(JSONObject json) {
if (json.isEmpty()) {
return new JSONArray();
}
Set<Integer> keys = new HashSet<>(json.size());
for (String key : json.keySet()) {
// 如果KEY不是非负整数
if (!key.matches("^\\d+$")) {
continue;
}
keys.add(Integer.valueOf(key));
}
JSONArray array = new JSONArray();
for (Integer key : keys) {
array.add(json.get(key.toString()));
}
return array;
}
}
package com.yohoufo.resource.util;
import com.google.common.base.Charsets;
import com.yoho.core.common.utils.MD5;
import com.yoho.service.model.order.response.shopping.PromotionFormula;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.List;
/**
* Created by JXWU on 2015/11/19.
*/
public class YHStringUtil {
private final static Logger logger = LoggerFactory.getLogger(YHStringUtil.class);
private YHStringUtil() {
}
public static String truncate(String str, int length) {
if (StringUtils.isNotEmpty(str) && str.length() > length) {
return str.substring(0, length);
}
return str;
}
public static String filterEmojiCharacter(String str) {
if (StringUtils.isNotEmpty(str)) {
return filterUtf8mb4String(str);
} else {
return str;
}
}
public static String truncateAndFilterEmojiCharacter(String str, int length) {
if (StringUtils.isNotEmpty(str)) {
String filterStr = filterEmojiCharacter(str);
if (StringUtils.isNotEmpty(filterStr) && filterStr.length() > length) {
filterStr = filterStr.substring(0, length);
}
return filterStr;
}
return str;
}
public static String md5(String str) {
return MD5.md5(str);
}
public static String toString(List<PromotionFormula> promotionFormulaList) {
StringBuilder textBuilder = new StringBuilder();
for (PromotionFormula promotionFormula : promotionFormulaList) {
textBuilder.append(promotionFormula.formula());
}
return textBuilder.toString();
}
public static String filterUtf8mb4String(String text) {
try {
byte[] bytes = text.getBytes(Charsets.UTF_8);
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
int i = 0;
while (i < bytes.length) {
short b = bytes[i];
if (b > 0) {
buffer.put(bytes[i++]);
continue;
}
b += 256;
if ((b ^ 0xC0) >> 4 == 0) {
buffer.put(bytes, i, 2);
i += 2;
} else if ((b ^ 0xE0) >> 4 == 0) {
buffer.put(bytes, i, 3);
i += 3;
} else if ((b ^ 0xF0) >> 4 == 0) {
i += 4;
}
}
buffer.flip();
return new String(buffer.array(), Charsets.UTF_8);
} catch (Exception e) {
logger.warn("filterUtf8mb4String error ,text is {}", text);
return "";
}
}
public static int parseInt(String str) {
if (StringUtils.isEmpty(str)) {
return 0;
}
try {
return Integer.parseInt(str);
} catch (NumberFormatException ex) {
logger.warn("parse {} to int error", str, ex);
return 0;
}
}
}