com.baomidou.mybatisplus.mapper.EntityWrapper Java Examples

The following examples show how to use com.baomidou.mybatisplus.mapper.EntityWrapper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppraiseBizService.java    From unimall with Apache License 2.0 6 votes vote down vote up
public Page<AppraiseResponseDTO> getSpuAllAppraise(Long spuId, Integer pageNo, Integer pageSize) throws ServiceException {
    String cacheKey = CA_APPRAISE_KEY + spuId + "_" + pageNo + "_" + pageSize;
    Page obj = cacheComponent.getObj(cacheKey, Page.class);
    if (obj != null) {
        return obj;
    }
    Integer count = appraiseMapper.selectCount(new EntityWrapper<AppraiseDO>().eq("spu_id", spuId));
    Integer offset = pageSize * (pageNo - 1);
    List<AppraiseResponseDTO> appraiseResponseDTOS = appraiseMapper.selectSpuAllAppraise(spuId, offset, pageSize);
    for (AppraiseResponseDTO appraiseResponseDTO : appraiseResponseDTOS) {
        appraiseResponseDTO.setImgList(imgMapper.getImgs(BizType.COMMENT.getCode(), appraiseResponseDTO.getId()));
    }
    Page<AppraiseResponseDTO> page = new Page<>(appraiseResponseDTOS, pageNo, pageSize, count);
    cacheComponent.putObj(cacheKey, page, Const.CACHE_ONE_DAY);
    return page;
}
 
Example #2
Source File: MessageServiceImpl.java    From cola-cloud with MIT License 6 votes vote down vote up
@Override
public List<Message> selectList(Message message, Long userId) {
    EntityWrapper<Message> wrapper = this.newEntityWrapper();

    if (userId != null) {
        wrapper.eq("sys_user_id", userId);
    }
    if (message != null) {
        if (message.getDeleteFlag() != null) {
            wrapper.eq("delete_flag", "N");
        } else {
            wrapper.eq("delete_flag", message.getDeleteFlag());
        }
        if (message.getReadFlag() != null) {
            wrapper.eq("read_flag", "N");
        } else {
            wrapper.eq("read_flag", message.getReadFlag());
        }
    }
    return super.selectList(wrapper);
}
 
Example #3
Source File: AdminUserServiceImpl.java    From unimall with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean addUser(Long adminId, UserDO user) throws ServiceException {
    if (user == null){
        throw new AdminServiceException(ExceptionDefinition.USER_INFORMATION_MISSING);
    }
    if(user.getPhone() == null){
        throw new AdminServiceException(ExceptionDefinition.USER_INFORMATION_MISSING);
    }
    if(userMapper.selectCount(new EntityWrapper<UserDO>().eq("phone",user.getPhone())) > 0){
        throw new AdminServiceException(ExceptionDefinition.USER_PHONE_ALREADY_EXIST);
    }
    Date now = new Date();
    user.setId(null);
    user.setPassword(Md5Crypt.md5Crypt(user.getPassword().getBytes(), "$1$" + user.getPhone().substring(0,7)));
    user.setGmtCreate(now);
    user.setGmtUpdate(now);
    return userMapper.insert(user) > 0;
}
 
Example #4
Source File: SysRoleResourceServiceImpl.java    From watchdog-framework with MIT License 6 votes vote down vote up
@Override
public List<SysResource> findAllResourceByRoleId(String rid) {
    List<SysRoleResource> rps = this.selectList(new EntityWrapper<SysRoleResource>().eq("rid",rid));
    if(rps!=null){
        List<String> pids = new ArrayList<>();
        rps.forEach(v->pids.add(v.getPid()));
        if(pids.size()==0){
            return null;
        }
        return resourceService.selectList(new EntityWrapper<SysResource>()
                .in("id", pids)
                .orderBy("sort",true)
        );
    }
    return null;
}
 
Example #5
Source File: ChannelServiceImpl.java    From app-version with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceResult findByChannelCode(String channelCode) {
    Channel channel = new Channel();
    channel.setChannelCode(channelCode);
    channel.setAppId(ThreadLocalUtils.USER_THREAD_LOCAL.get().getAppId());
    EntityWrapper<Channel> wrapper = new EntityWrapper<>(channel);
    wrapper.last("limit 0,1");
    List<Channel> channels = channelMapper.selectList(wrapper);

    if (!channels.isEmpty()) {
        Channel channel1 = channels.get(0);
        if (!channel1.getAppId().equals(ThreadLocalUtils.USER_THREAD_LOCAL.get().getAppId())) {
            return ServiceResultConstants.RESOURCE_NOT_BELONG_APP;
        }
        return ServiceResult.ok(channel1);
    } else {
        return ServiceResultConstants.CHANNEL_NOT_EXISTS;
    }
}
 
Example #6
Source File: AdminFreightTemplateServiceImpl.java    From unimall with Apache License 2.0 6 votes vote down vote up
@Override
public List<FreightTemplateDTO> getAllFreightTemplate(Long adminId) throws ServiceException {
    List<FreightTemplateDO> freightTemplateDOList = freightTemplateMapper.selectList(null); //查出主表所有数据
    List<FreightTemplateDTO> freightTemplateDTOList = new ArrayList<>();
    if (freightTemplateDOList == null || freightTemplateDOList.size() == 0) { //如果主表没有记录
        return freightTemplateDTOList;
    }
    for (FreightTemplateDO freightTemplateDO : freightTemplateDOList) {  //查出副表中,主表每条数据对应的数据
        FreightTemplateDTO freightTemplateDTO = new FreightTemplateDTO();
        List<FreightTemplateCarriageDO> freightTemplateCarriageDOList = freightTemplateCarriageMapper.selectList(new EntityWrapper<FreightTemplateCarriageDO>()
                .eq("template_id", freightTemplateDO.getId()));
        freightTemplateDTO.setFreightTemplateDO(freightTemplateDO);
        freightTemplateDTO.setFreightTemplateCarriageDOList(freightTemplateCarriageDOList);
        freightTemplateDTOList.add(freightTemplateDTO);
    }
    return freightTemplateDTOList;
}
 
Example #7
Source File: ConstantFactory.java    From MeetingFilm with Apache License 2.0 6 votes vote down vote up
/**
 * 根据字典名称和字典中的值获取对应的名称
 */
@Override
public String getDictsByName(String name, Integer val) {
    Dict temp = new Dict();
    temp.setName(name);
    Dict dict = dictMapper.selectOne(temp);
    if (dict == null) {
        return "";
    } else {
        Wrapper<Dict> wrapper = new EntityWrapper<>();
        wrapper = wrapper.eq("pid", dict.getId());
        List<Dict> dicts = dictMapper.selectList(wrapper);
        for (Dict item : dicts) {
            if (item.getNum() != null && item.getNum().equals(val)) {
                return item.getName();
            }
        }
        return "";
    }
}
 
Example #8
Source File: MenuServiceImpl.java    From WebStack-Guns with MIT License 6 votes vote down vote up
@Override
@Transactional
public void delMenuContainSubMenus(Long menuId) {

    Menu menu = menuMapper.selectById(menuId);

    //删除当前菜单
    delMenu(menuId);

    //删除所有子菜单
    Wrapper<Menu> wrapper = new EntityWrapper<>();
    wrapper = wrapper.like("pcodes", "%[" + menu.getCode() + "]%");
    List<Menu> menus = menuMapper.selectList(wrapper);
    for (Menu temp : menus) {
        delMenu(temp.getId());
    }
}
 
Example #9
Source File: AdminGroupShopGoodsServiceImpl.java    From unimall with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public String deleteGroupShopSpu(Long adminId, Long id) throws ServiceException {

    GroupShopDO groupShopDO = groupShopMapper.selectById(id);
    if (groupShopDO == null) {
        throw new AdminServiceException(ExceptionDefinition.SPU_NO_EXITS_OR_ONLY_SPU);
    }

    if (groupShopDO.getStatus() > 0) {
        throw new AdminServiceException(ExceptionDefinition.GROUP_SHOP_ALREAD_ATCIVE);
    }

    if (groupShopMapper.deleteById(id) <= 0) {
        throw new AdminServiceException(ExceptionDefinition.GROUP_SHOP_SPU_DELETE_SQL_QUERY_ERROR);
    }
    if (groupShopSkuMapper.delete((new EntityWrapper<GroupShopSkuDO>().eq("group_shop_id", id))) <= 0) {
        throw new AdminServiceException(ExceptionDefinition.GROUP_SHOP_SKU_DELETE_SQL_QUERY_ERROR);
    }

    cacheComponent.delPrefixKey(GROUP_SHOP_CACHE);
    return "ok";
}
 
Example #10
Source File: DatabaseCachableClientDetailsService.java    From cola-cloud with MIT License 6 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
@CachePut(value = OAUTH_CLINET_DETAILS_CACHE, key = "#clientDetails.clientId")
public ClientDetails updateCachedClientDetail(ClientDetails clientDetails) throws NoSuchClientException {
    Optional<Client> clientOptional = Optional.of(this.clientService.findOneByColumn("client_id", clientDetails.getClientId()));
    clientOptional.orElseThrow(() -> new NoSuchClientException("Client ID not found"));

    Client client = Client.builder()
            .clientId(clientDetails.getClientId())
            .clientSecret(clientDetails.getClientSecret())
            .accessTokenValiditySeconds(clientDetails.getAccessTokenValiditySeconds())
            .refreshTokenValiditySeconds(clientDetails.getRefreshTokenValiditySeconds()).build();
    client.setId(clientOptional.get().getId());

    client.setGrantType(clientDetails.getAuthorizedGrantTypes().stream().collect(Collectors.joining(",")));
    client.setRedirectUri(clientDetails.getRegisteredRedirectUri().stream().collect(Collectors.joining(",")));
    clientService.insert(client);

    EntityWrapper<Scope> wrapper = new EntityWrapper<>();
    wrapper.eq("client_id", clientOptional.get().getId());
    scopeService.delete(wrapper);

    List<Scope> clientScopes = clientDetails.getScope().stream().map(scope ->
            Scope.builder().clientId(client.getId()).autoApprove(false).scope(scope).build()).collect(Collectors.toList());
    this.scopeService.insertBatch(clientScopes);
    return clientDetails;
}
 
Example #11
Source File: OrderServiceImpl.java    From unimall with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public String refund(String orderNo, Long userId) throws ServiceException {
    OrderDO orderDO = orderBizService.checkOrderExist(orderNo, userId);
    if (PayChannelType.OFFLINE.getCode().equals(orderDO.getPayChannel())) {
        throw new AppServiceException(ExceptionDefinition.ORDER_PAY_CHANNEL_NOT_SUPPORT_REFUND);
    }
    if (OrderStatusType.refundable(orderDO.getStatus())) {
        OrderDO updateOrderDO = new OrderDO();
        updateOrderDO.setStatus(OrderStatusType.REFUNDING.getCode());
        orderBizService.changeOrderStatus(orderNo, orderDO.getStatus() , updateOrderDO);
        GlobalExecutor.execute(() -> {
            OrderDTO orderDTO = new OrderDTO();
            BeanUtils.copyProperties(orderDO, orderDTO);
            List<OrderSkuDO> orderSkuList = orderSkuMapper.selectList(new EntityWrapper<OrderSkuDO>().eq("order_no", orderDO.getOrderNo()));
            orderDTO.setSkuList(orderSkuList);
            adminNotifyBizService.refundOrder(orderDTO);
        });
        return "ok";
    }
    throw new AppServiceException(ExceptionDefinition.ORDER_STATUS_NOT_SUPPORT_REFUND);
}
 
Example #12
Source File: SysLogController.java    From cola-cloud with MIT License 6 votes vote down vote up
/**
 * 查找系统日志
 */
@GetMapping(value = "/list")
@ApiOperation("查找系统日志")
public Result<Page<List<SysLog>>> list(Integer type, String name, Date startDate, Date endDate) {
    EntityWrapper wrapper = new EntityWrapper<>();
    wrapper.like("name", name);
    if (type != null) {
        wrapper.eq("type", type);
    }
    if (startDate != null) {
        wrapper.andNew("create_time >= {0}", startDate);
    }
    //
    if (endDate != null) {
        wrapper.andNew("create_time <= {0}", endDate);
    }
    wrapper.orderBy("id");
    return this.success(sysLogService.selectPage(this.getPagination(), wrapper));
}
 
Example #13
Source File: SysUserServiceImpl.java    From pig with MIT License 6 votes vote down vote up
@Override
@CacheEvict(value = "user_details", key = "#userDto.username")
public Boolean updateUser(UserDTO userDto) {
    SysUser sysUser = new SysUser();
    BeanUtils.copyProperties(userDto, sysUser);
    sysUser.setUpdateTime(new Date());
    this.updateById(sysUser);

    SysUserRole condition = new SysUserRole();
    condition.setUserId(userDto.getUserId());
    sysUserRoleService.delete(new EntityWrapper<>(condition));
    userDto.getRole().forEach(roleId -> {
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(sysUser.getUserId());
        userRole.setRoleId(roleId);
        userRole.insert();
    });
    return Boolean.TRUE;
}
 
Example #14
Source File: DefaultOrderServiceImpl.java    From MeetingFilm with Apache License 2.0 6 votes vote down vote up
@Override
public Page<OrderVO> getOrderByUserId(Integer userId, Page<OrderVO> page) {
    Page<OrderVO> result = new Page<>();
    if (userId == null) {
        log.error("订单查询业务失败,用户编号未传入");
        return null;
    } else {
        List<OrderVO> ordersByUserId = moocOrderTMapper.getOrdersByUserId(userId, page);
        if (ordersByUserId == null && ordersByUserId.size() == 0) {
            result.setTotal(0);
            result.setRecords(new ArrayList<>());
            return result;
        } else {
            // 获取订单总数
            EntityWrapper<MoocOrderT> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("order_user", userId);
            Integer counts = moocOrderTMapper.selectCount(entityWrapper);
            // 将结果放入Page
            result.setTotal(counts);
            result.setRecords(ordersByUserId);

            return result;
        }
    }
}
 
Example #15
Source File: RoleResServiceImpl.java    From Ffast-Java with MIT License 6 votes vote down vote up
@Cacheable(value = "sys", key = "'roleRes_resIds_'+#roleId")
@Override
public List<Long> getRoleResIds(Long roleId) {
    RoleRes m = new RoleRes();
    m.setRoleId(roleId);
    EntityWrapper ew = new EntityWrapper<RoleRes>(m);
    ew.setSqlSelect("res_id");
    List<RoleRes> roleResList = selectList(ew);
    List<Long> resIds = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(roleResList)) {
        for (RoleRes roleRes : roleResList) {
            resIds.add(roleRes.getResId());
        }
    }
    return resIds;
}
 
Example #16
Source File: MenuServiceImpl.java    From MeetingFilm with Apache License 2.0 6 votes vote down vote up
@Override
public void delMenuContainSubMenus(Long menuId) {

    Menu menu = menuMapper.selectById(menuId);

    //删除当前菜单
    delMenu(menuId);

    //删除所有子菜单
    Wrapper<Menu> wrapper = new EntityWrapper<>();
    wrapper = wrapper.like("pcodes", "%[" + menu.getCode() + "]%");
    List<Menu> menus = menuMapper.selectList(wrapper);
    for (Menu temp : menus) {
        delMenu(temp.getId());
    }
}
 
Example #17
Source File: DictTypeServiceImpl.java    From Ffast-Java with MIT License 6 votes vote down vote up
@Override
protected ServiceResult createBefore(DictType m) {
    ServiceResult result = new ServiceResult();
    EntityWrapper ew = new EntityWrapper<DictType>();
    ew.eq("identity", m.getIdentity());
    if (selectCount(ew) > 0) {
        result.setMessage("标识重复,请重新输入");
        return result;
    }
    EntityWrapper ew1 = new EntityWrapper<DictType>();
    ew1.eq("name", m.getName());
    if (selectCount(ew1) > 0) {
        result.setMessage("分类名重复,请重新输入");
        return result;
    }
    return null;
}
 
Example #18
Source File: UserConteroller.java    From mysiteforme with Apache License 2.0 6 votes vote down vote up
@RequiresPermissions("sys:user:list")
@PostMapping("list")
@ResponseBody
public LayerData<User> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                            @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                            ServletRequest request){
    Map map = WebUtils.getParametersStartingWith(request, "s_");
    LayerData<User> userLayerData = new LayerData<>();
    EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
    if(!map.isEmpty()){
        String keys = (String) map.get("key");
        if(StringUtils.isNotBlank(keys)) {
            userEntityWrapper.like("login_name", keys).or().like("tel", keys).or().like("email", keys);
        }
    }
    Page<User> userPage = userService.selectPage(new Page<>(page,limit),userEntityWrapper);
    userLayerData.setCount(userPage.getTotal());
    userLayerData.setData(userPage.getRecords());
    return  userLayerData;
}
 
Example #19
Source File: AdminRecommendServiceImpl.java    From unimall with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean addRecommend(Long adminId, Long spuId, Integer recommendType) throws ServiceException {

    if (!(spuMapper.selectCount(new EntityWrapper<SpuDO>().eq("id", spuId)) > 0)) {
        throw new AdminServiceException(ExceptionDefinition.RECOMMEND_SPU_NO_HAS);
    }

    if (recommendMapper.selectCount(new EntityWrapper<RecommendDO>()
            .eq("spu_id", spuId)
            .eq("recommend_type", recommendType)) > 0) {
        throw new AdminServiceException(ExceptionDefinition.RECOMMEND_ALREADY_HAS);
    }
    RecommendDO recommendDO = new RecommendDO(spuId, recommendType);
    Date now = new Date();
    recommendDO.setGmtCreate(now);
    recommendDO.setGmtUpdate(now);
    if (!(recommendMapper.insert(recommendDO) > 0)) {
        throw new AdminServiceException(ExceptionDefinition.RECOMMEND_SQL_ADD_FAILED);
    }
    cacheComponent.delPrefixKey(RECOMMEND_NAME+recommendType);
    return true;
}
 
Example #20
Source File: AddressServiceImpl.java    From unimall with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean updateAddress(Long addressId, String province, String city, String county, String address, Integer defaultAddress, Long userId, String phone, String consignee) throws ServiceException {
    AddressDO addressDO = new AddressDO(province, city, county, address, defaultAddress, userId, phone, consignee);
    Date now = new Date();
    if (defaultAddress != 0) {
        defaultAddress = 1;
        List<AddressDO> addressDOS = addressMapper.selectList(new EntityWrapper<AddressDO>().eq("user_id", userId).eq("default_address", 1));
        if (addressDOS.size() != 0) {
            AddressDO preDefault = addressDOS.get(0);
            preDefault.setDefaultAddress(0);
            addressMapper.updateById(preDefault);
        }
    }
    addressDO.setDefaultAddress(defaultAddress);
    addressDO.setGmtUpdate(now);
    return addressMapper.update(addressDO, new EntityWrapper<AddressDO>()
            .eq("id", addressId)
            .eq("user_id", userId)) > 0;

}
 
Example #21
Source File: AdminGoodsServiceImpl.java    From unimall with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public String delete(Long spuId, Long adminId) throws ServiceException {
    if (spuMapper.deleteById(spuId) <= 0) {
        throw new AdminServiceException(ExceptionDefinition.GOODS_NOT_EXIST);
    }
    cartMapper.delete(new EntityWrapper<CartDO>().in("sku_id", skuMapper.getSkuIds(spuId)));
    skuMapper.delete(new EntityWrapper<SkuDO>().eq("spu_id", spuId));
    imgMapper.delete(new EntityWrapper<ImgDO>().eq("biz_id", spuId).eq("biz_type", BizType.GOODS.getCode()));
    spuAttributeMapper.delete(new EntityWrapper<SpuAttributeDO>().eq("spu_id", spuId));
    goodsBizService.clearGoodsCache(spuId);
    pluginUpdateInvoke(spuId);

    cacheComponent.delPrefixKey(GoodsBizService.CA_SPU_PAGE_PREFIX);
    return "ok";
}
 
Example #22
Source File: DbValidator.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validate(Credence credence) {
    List<User> users = userMapper.selectList(new EntityWrapper<User>().eq("userName", credence.getCredenceName()));
    if (users != null && users.size() > 0) {
        return true;
    } else {
        return false;
    }
}
 
Example #23
Source File: RepositoryImageServiceImpl.java    From paas with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean hasExist(String fullName) {
    List<RepositoryImage> list = repositoryImageMapper.selectList(
            new EntityWrapper<RepositoryImage>().eq("full_name", fullName));

    RepositoryImage repositoryImage = CollectionUtils.getListFirst(list);

    return repositoryImage != null;
}
 
Example #24
Source File: SysRoleServiceImpl.java    From watchdog-framework with MIT License 5 votes vote down vote up
@Override
public Page<SysRole> list(FindRoleDTO findRoleDTO) {
    EntityWrapper<SysRole> wrapper = new EntityWrapper<>();
    wrapper.orderBy("id",findRoleDTO.getAsc());
    Page<SysRole> rolePage = this.selectPage(new Page<>(findRoleDTO.getPage(),
            findRoleDTO.getPageSize()), wrapper);
    if(findRoleDTO.getHasResource()){
        if(rolePage.getRecords()!=null){
            rolePage.getRecords().forEach(v->
                    v.setResources(roleResourceService.findAllResourceByRoleId(v.getId())));
        }
    }
    return rolePage;
}
 
Example #25
Source File: SysVolumeServiceImpl.java    From paas with Apache License 2.0 5 votes vote down vote up
@Override
public SysVolume getBySource(String source) {
    List<SysVolume> list = volumesMapper.selectList(new EntityWrapper<SysVolume>().eq("source", source));
    SysVolume volume = CollectionUtils.getListFirst(list);
    if(volume == null) {
        return null;
    }
    return volume;
}
 
Example #26
Source File: IosVersionServiceImpl.java    From app-version with Apache License 2.0 5 votes vote down vote up
@Override
public ServiceResult findBetweenVersionList(String version1, String version2, EntityWrapper<IosVersion> wrapper) {
    List<IosVersion> iosVersions = iosVersionMapper.selectList(wrapper);
    String max = VersionCompareUtils.compareVersion(version1,version2) >= 0 ? version1 : version2;
    String min = VersionCompareUtils.compareVersion(version1,version2) <= 0 ? version1 : version2;
    List<IosVersion> versionList = iosVersions.stream().filter(o -> VersionCompareUtils.compareVersion(o.getAppVersion(), min) >= 0 && VersionCompareUtils.compareVersion(max, o.getAppVersion()) >= 0)
            .sorted((o1, o2) -> VersionCompareUtils.compareVersion(o2.getAppVersion(), o1.getAppVersion())).collect(Collectors.toList());
    return ServiceResult.ok(versionList);
}
 
Example #27
Source File: MenuServiceImpl.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Override
public List<ZtreeVO> showTreeMenus() {
    EntityWrapper<Menu> wrapper = new EntityWrapper<>();
    wrapper.eq("del_flag",false);
    wrapper.eq("is_show",true);
    wrapper.orderBy("sort",false);
    List<Menu> totalMenus = baseMapper.selectList(wrapper);
    List<ZtreeVO> ztreeVOs = Lists.newArrayList();
    return getZTree(null,totalMenus,ztreeVOs);
}
 
Example #28
Source File: QiniuFileUtil.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
/***
 * 普通上传图片
 * @param file
 * @return
 * @throws QiniuException
 * @throws IOException
 */
public static String upload(MultipartFile file) throws IOException, NoSuchAlgorithmException {
	Zone z = Zone.zone0();
	Configuration config = new Configuration(z);
	String fileName = "", extName = "", filePath = "";
	if (null != file && !file.isEmpty()) {
		extName = file.getOriginalFilename().substring(
				file.getOriginalFilename().lastIndexOf("."));
		fileName = UUID.randomUUID() + extName;
		UploadManager uploadManager = new UploadManager(config);
		Auth auth = Auth.create(qiniuAccess, qiniuKey);
		String token = auth.uploadToken(bucketName);
		byte[] data = file.getBytes();
		QETag tag = new QETag();
		String hash = tag.calcETag(file);
		Rescource rescource = new Rescource();
		EntityWrapper<RestResponse> wrapper = new EntityWrapper<>();
		wrapper.eq("hash",hash);
		rescource = rescource.selectOne(wrapper);
		if( rescource!= null){
			return rescource.getWebUrl();
		}
		Response r = uploadManager.put(data, fileName, token);
		if (r.isOK()) {
			filePath = path + fileName;
			rescource = new Rescource();
			rescource.setFileName(fileName);
			rescource.setFileSize(new java.text.DecimalFormat("#.##").format(file.getSize()/1024)+"kb");
			rescource.setHash(hash);
			rescource.setFileType(StringUtils.isBlank(extName)?"unknown":extName);
			rescource.setWebUrl(filePath);
			rescource.setSource("qiniu");
			rescource.insert();
		}
	}
	return filePath;
}
 
Example #29
Source File: BasicServiceImpl.java    From app-version with Apache License 2.0 5 votes vote down vote up
@Override
public void formatCreatedBy(BasicEntity basicEntity) {
    String createdBy = basicEntity.getCreatedBy();
    if (StringUtils.isNotBlank(createdBy)) {
        User user = new User();
        user.setUserId(createdBy);
        List<User> users = userMapper.selectList(new EntityWrapper<>(user));
        if (!users.isEmpty()) {
            basicEntity.setCreatedBy(users.get(0).getPhone());
        }
    }
}
 
Example #30
Source File: SysImageServiceImpl.java    From paas with Apache License 2.0 5 votes vote down vote up
@Override
public Page<SysImageDTO> listLocalUserImage(String name, boolean filterOpen, String userId, Page<SysImageDTO> page) {
    List<SysImageDTO> images;
    if(filterOpen) {
        List<SysImage> imageList = imageMapper.selectList(new EntityWrapper<SysImage>()
                .eq("type", 2)
                .and().eq("user_id", userId).or().eq("has_open", true));
        images = sysImage2DTO(imageList);

    } else {
        images = imageMapper.listLocalUserImage(page, name);
    }

    return page.setRecords(images);
}