Java Code Examples for org.apache.commons.lang3.ObjectUtils#allNotNull()

The following examples show how to use org.apache.commons.lang3.ObjectUtils#allNotNull() . 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: ZkUtils.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 创建节点
 *
 * @param path
 * @param data
 * @param mode
 * @return
 */
public boolean createNode(String path, String data, CreateMode mode) {
    if (!ObjectUtils.allNotNull(zkClient, path)) {
        return Boolean.FALSE;
    }
    try {
        Stat stat = exists(path);
        if (stat == null) {
            mode = mode == null ? CreateMode.PERSISTENT : mode;
            String opResult;
            if (ObjectUtils.allNotNull(data)) {
                opResult = zkClient.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path, data.getBytes(Charsets.UTF_8));
            } else {
                opResult = zkClient.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path);
            }
            return Objects.equal(opResult, path);
        }
        return Boolean.TRUE;
    } catch (Exception e) {
        log.error("create node fail! path: {}, error: {}", path, e);
    }
    return Boolean.FALSE;
}
 
Example 2
Source File: ZkUtils.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 删除节点  递归删除子节点
 *
 * @param path
 * @param version
 * @return
 */
public boolean deleteNode(String path, Integer version) {
    if (!ObjectUtils.allNotNull(zkClient, path)) {
        return Boolean.FALSE;
    }
    try {
        Stat stat = exists(path);
        if (stat != null) {
            if (version == null) {
                zkClient.delete().deletingChildrenIfNeeded().forPath(path);
            } else {
                zkClient.delete().deletingChildrenIfNeeded().withVersion(version).forPath(path);
            }
        }
        return Boolean.TRUE;
    } catch (Exception e) {
        log.error("delete node fail! path: {}, error: {}", path, e);
    }
    return Boolean.FALSE;
}
 
Example 3
Source File: ZkUtils.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 设置节点数据
 *
 * @param path
 * @param data
 * @param version
 * @return
 */
public boolean setNodeData(String path, byte[] data, Integer version) {
    if (!ObjectUtils.allNotNull(zkClient, path)) {
        return Boolean.FALSE;
    }
    try {
        Stat stat = exists(path);
        if (stat != null) {
            if (version == null) {
                zkClient.setData().forPath(path, data);
            } else {
                zkClient.setData().withVersion(version).forPath(path, data);
            }
            return Boolean.TRUE;
        }
    } catch (Exception e) {
        log.error("set node data fail! path: {}, error: {}", path, e);
    }
    return Boolean.FALSE;
}
 
Example 4
Source File: ZkUtils.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
/**
     * 设置子节点更改监听
     *
     * @param path
     * @throws Exception
     */
    public boolean listenerPathChildrenCache(String path, BiConsumer<CuratorFramework, PathChildrenCacheEvent> biConsumer) {

        if (!ObjectUtils.allNotNull(zkClient, path, biConsumer)) {
            return Boolean.FALSE;
        }
        try {
            Stat stat = exists(path);
            if (stat != null) {
                PathChildrenCache watcher = new PathChildrenCache(zkClient, path, true);
                watcher.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
                //该模式下 watcher在重连的时候会自动 rebuild 否则需要重新rebuild
                watcher.getListenable().addListener(biConsumer::accept, pool);
                if (!pathChildrenCaches.contains(watcher)) {
                    pathChildrenCaches.add(watcher);
                }
//                else{
//                    watcher.rebuild();
//                }
                return Boolean.TRUE;
            }
        } catch (Exception e) {
            log.error("listen path children cache fail! path:{} , error:{}", path, e);
        }
        return Boolean.FALSE;
    }
 
Example 5
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private ValueMap checkForNullWithCommonsObjectUtilsAllNotNull(Resource resource) {
  ValueMap result = new ValueMapDecorator(new HashMap<>());
  Page page = resource.adaptTo(Page.class);
  Resource pageResource = page.getContentResource("test");
  if (ObjectUtils.allNotNull(pageResource)) {
    result = pageResource.getValueMap();
  }
  return result;
}
 
Example 6
Source File: PubmaticAdapter.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
private static boolean isValidParams(AdUnitBidWithParams<NormalizedPubmaticParams> adUnitBidWithParams) {
    final NormalizedPubmaticParams params = adUnitBidWithParams.getParams();
    if (params == null) {
        return false;
    }

    // if adUnitBid has banner type, params should contains tagId, width and height fields
    return !adUnitBidWithParams.getAdUnitBid().getMediaTypes().contains(MediaType.banner)
            || ObjectUtils.allNotNull(params.getTagId(), params.getWidth(), params.getHeight());
}
 
Example 7
Source File: WxCollectController.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 用户收藏添加或删除
 * <p>
 * 如果商品没有收藏,则添加收藏;如果商品已经收藏,则删除收藏状态。
 *
 * @param userId 用户ID
 * @param body   请求内容,{ type: xxx, valueId: xxx }
 * @return 操作结果
 */
@PostMapping("addordelete")
public Object addordelete(@LoginUser Integer userId, @RequestBody String body) {
    if (userId == null) {
        return ResponseUtil.unlogin();
    }

    Byte type = JacksonUtil.parseByte(body, "type");
    Integer valueId = JacksonUtil.parseInteger(body, "valueId");
    if (!ObjectUtils.allNotNull(type, valueId)) {
        return ResponseUtil.badArgument();
    }

    LitemallCollect collect = collectService.queryByTypeAndValue(userId, type, valueId);

    if (collect != null) {
        collectService.deleteById(collect.getId());
    } else {
        collect = new LitemallCollect();
        collect.setUserId(userId);
        collect.setValueId(valueId);
        collect.setType(type);
        collectService.add(collect);
    }

    return ResponseUtil.ok();
}
 
Example 8
Source File: WxCollectController.java    From litemall with MIT License 5 votes vote down vote up
/**
 * 用户收藏添加或删除
 * <p>
 * 如果商品没有收藏,则添加收藏;如果商品已经收藏,则删除收藏状态。
 *
 * @param userId 用户ID
 * @param body   请求内容,{ type: xxx, valueId: xxx }
 * @return 操作结果
 */
@PostMapping("addordelete")
public Object addordelete(@LoginUser Integer userId, @RequestBody String body) {
    if (userId == null) {
        return ResponseUtil.unlogin();
    }

    Byte type = JacksonUtil.parseByte(body, "type");
    Integer valueId = JacksonUtil.parseInteger(body, "valueId");
    if (!ObjectUtils.allNotNull(type, valueId)) {
        return ResponseUtil.badArgument();
    }

    LitemallCollect collect = collectService.queryByTypeAndValue(userId, type, valueId);

    if (collect != null) {
        collectService.deleteById(collect.getId());
    } else {
        collect = new LitemallCollect();
        collect.setUserId(userId);
        collect.setValueId(valueId);
        collect.setType(type);
        collectService.add(collect);
    }

    return ResponseUtil.ok();
}
 
Example 9
Source File: ZkUtils.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 检查节点是否存在
 *
 * @param path
 * @return
 */
public Stat exists(String path) {
    if (!ObjectUtils.allNotNull(zkClient, path)) {
        return null;
    }
    try {
        return zkClient.checkExists().forPath(path);
    } catch (Exception e) {
        log.error("check node exists fail! path: {}, error: {}", path, e);
    }
    return null;
}
 
Example 10
Source File: ZkUtils.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取指定节点的值
 *
 * @param path
 * @return
 */
public byte[] getNodeData(String path) {
    if (!ObjectUtils.allNotNull(zkClient, path)) {
        return null;
    }
    try {
        Stat stat = exists(path);
        if (stat != null) {
            return zkClient.getData().forPath(path);
        }
    } catch (Exception e) {
        log.error("get node data fail! path: {}, error: {}", path, e);
    }
    return null;
}
 
Example 11
Source File: AbstractMantaTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    final Profile profile = new ProfilePlistReader(new ProtocolFactory(Collections.singleton(new MantaProtocol()))).read(
        new Local("../profiles/Joyent Triton Object Storage (us-east).cyberduckprofile"));

    final String hostname;
    final Local file;
    if(ObjectUtils.allNotNull(System.getProperty("manta.key_path"), System.getProperty("manta.url"))) {
        file = new Local(System.getProperty("manta.key_path"));
        hostname = new URL(System.getProperty("manta.url")).getHost();
    }
    else {
        final String key = System.getProperty("manta.key");
        file = TemporaryFileServiceFactory.get().create(new AlphanumericRandomStringService().random());
        LocalTouchFactory.get().touch(file);
        IOUtils.write(key, file.getOutputStream(false), Charset.defaultCharset());
        hostname = profile.getDefaultHostname();
    }

    final String user = System.getProperty("manta.user");
    final Host host = new Host(profile, hostname, new Credentials(user).withIdentity(file));
    session = new MantaSession(host, new DisabledX509TrustManager(), new DefaultX509KeyManager());
    session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback());
    final String testRoot = "cyberduck-test-" + new AlphanumericRandomStringService().random();
    testPathPrefix = new Path(new MantaAccountHomeInfo(host.getCredentials().getUsername(), host.getDefaultPath()).getAccountPrivateRoot(), testRoot, EnumSet.of(Type.directory));
    session.getClient().putDirectory(testPathPrefix.getAbsolute());
}
 
Example 12
Source File: WxCollectController.java    From mall with MIT License 5 votes vote down vote up
/**
 * 用户收藏添加或删除
 * <p>
 * 如果商品没有收藏,则添加收藏;如果商品已经收藏,则删除收藏状态。
 *
 * @param userId 用户ID
 * @param body   请求内容,{ type: xxx, valueId: xxx }
 * @return 操作结果
 */
@PostMapping("addordelete")
public Object addordelete(@LoginUser Integer userId, @RequestBody String body) {
    if (userId == null) {
        return ResponseUtil.unlogin();
    }

    Byte type = JacksonUtil.parseByte(body, "type");
    Integer valueId = JacksonUtil.parseInteger(body, "valueId");
    if (!ObjectUtils.allNotNull(type, valueId)) {
        return ResponseUtil.badArgument();
    }

    LitemallCollect collect = collectService.queryByTypeAndValue(userId, type, valueId);

    String handleType = null;
    if (collect != null) {
        handleType = "delete";
        collectService.deleteById(collect.getId());
    } else {
        handleType = "add";
        collect = new LitemallCollect();
        collect.setUserId(userId);
        collect.setValueId(valueId);
        collect.setType(type);
        collectService.add(collect);
    }

    Map<String, Object> data = new HashMap<String, Object>();
    data.put("type", handleType);
    return ResponseUtil.ok(data);
}
 
Example 13
Source File: OptionObjectBundleHook.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Check for duplication of Option's name OR code within given OptionSet
 *
 * @param listOptions
 * @param checkOption
 * @return
 */
private List<ErrorReport> checkDuplicateOption( OptionSet optionSet, Option checkOption )
{
    List<ErrorReport> errors = new ArrayList<>();

    if ( optionSet == null || optionSet.getOptions().isEmpty() || checkOption == null )
    {
        return errors;
    }

    for ( Option option : optionSet.getOptions() )
    {
        if ( option == null || option.getName() == null || option.getCode() == null )
        {
            continue;
        }

        if ( ObjectUtils.allNotNull( option.getUid(), checkOption.getUid() ) && option.getUid().equals( checkOption.getUid() ) )
        {
            continue;
        }

        if ( option.getName().equals( checkOption.getName() ) || option.getCode().equals( checkOption.getCode() ) )
        {
            errors.add( new ErrorReport( OptionSet.class, ErrorCode.E4028, optionSet.getUid(), option.getUid() ) );
        }
    }

    return errors;
}
 
Example 14
Source File: WxCartController.java    From mall with MIT License 4 votes vote down vote up
/**
 * 立即购买
 * <p>
 * 和add方法的区别在于:
 * 1. 如果购物车内已经存在购物车货品,前者的逻辑是数量添加,这里的逻辑是数量覆盖
 * 2. 添加成功以后,前者的逻辑是返回当前购物车商品数量,这里的逻辑是返回对应购物车项的ID
 *
 * @param userId 用户ID
 * @param cart   购物车商品信息, { goodsId: xxx, productId: xxx, number: xxx }
 * @return 立即购买操作结果
 */
@PostMapping("fastadd")
public Object fastadd(@LoginUser Integer userId, @RequestBody LitemallCart cart) {
    if (userId == null) {
        return ResponseUtil.unlogin();
    }
    if (cart == null) {
        return ResponseUtil.badArgument();
    }

    Integer productId = cart.getProductId();
    Integer number = cart.getNumber().intValue();
    Integer goodsId = cart.getGoodsId();
    if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
        return ResponseUtil.badArgument();
    }

    //判断商品是否可以购买
    LitemallGoods goods = goodsService.findById(goodsId);
    if (goods == null || !goods.getIsOnSale()) {
        return ResponseUtil.fail(GOODS_UNSHELVE, "商品已下架");
    }

    LitemallGoodsProduct product = productService.findById(productId);
    //判断购物车中是否存在此规格商品
    LitemallCart existCart = cartService.queryExist(goodsId, productId, userId);
    if (existCart == null) {
        //取得规格的信息,判断规格库存
        if (product == null || number > product.getNumber()) {
            return ResponseUtil.fail(GOODS_NO_STOCK, "库存不足");
        }

        cart.setId(null);
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName((goods.getName()));
        cart.setPicUrl(goods.getPicUrl());
        cart.setPrice(product.getPrice());
        cart.setSpecifications(product.getSpecifications());
        cart.setUserId(userId);
        cart.setChecked(true);
        cartService.add(cart);
    } else {
        //取得规格的信息,判断规格库存
        int num = number;
        if (num > product.getNumber()) {
            return ResponseUtil.fail(GOODS_NO_STOCK, "库存不足");
        }
        existCart.setNumber((short) num);
        if (cartService.updateById(existCart) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
    }

    return ResponseUtil.ok(existCart != null ? existCart.getId() : cart.getId());
}
 
Example 15
Source File: WxCartController.java    From litemall with MIT License 4 votes vote down vote up
/**
 * 立即购买
 * <p>
 * 和add方法的区别在于:
 * 1. 如果购物车内已经存在购物车货品,前者的逻辑是数量添加,这里的逻辑是数量覆盖
 * 2. 添加成功以后,前者的逻辑是返回当前购物车商品数量,这里的逻辑是返回对应购物车项的ID
 *
 * @param userId 用户ID
 * @param cart   购物车商品信息, { goodsId: xxx, productId: xxx, number: xxx }
 * @return 立即购买操作结果
 */
@PostMapping("fastadd")
public Object fastadd(@LoginUser Integer userId, @RequestBody LitemallCart cart) {
    if (userId == null) {
        return ResponseUtil.unlogin();
    }
    if (cart == null) {
        return ResponseUtil.badArgument();
    }

    Integer productId = cart.getProductId();
    Integer number = cart.getNumber().intValue();
    Integer goodsId = cart.getGoodsId();
    if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
        return ResponseUtil.badArgument();
    }
    if(number <= 0){
        return ResponseUtil.badArgument();
    }

    //判断商品是否可以购买
    LitemallGoods goods = goodsService.findById(goodsId);
    if (goods == null || !goods.getIsOnSale()) {
        return ResponseUtil.fail(GOODS_UNSHELVE, "商品已下架");
    }

    LitemallGoodsProduct product = productService.findById(productId);
    //判断购物车中是否存在此规格商品
    LitemallCart existCart = cartService.queryExist(goodsId, productId, userId);
    if (existCart == null) {
        //取得规格的信息,判断规格库存
        if (product == null || number > product.getNumber()) {
            return ResponseUtil.fail(GOODS_NO_STOCK, "库存不足");
        }

        cart.setId(null);
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName((goods.getName()));
        if(StringUtils.isEmpty(product.getUrl())){
            cart.setPicUrl(goods.getPicUrl());
        }
        else{
            cart.setPicUrl(product.getUrl());
        }
        cart.setPrice(product.getPrice());
        cart.setSpecifications(product.getSpecifications());
        cart.setUserId(userId);
        cart.setChecked(true);
        cartService.add(cart);
    } else {
        //取得规格的信息,判断规格库存
        int num = number;
        if (num > product.getNumber()) {
            return ResponseUtil.fail(GOODS_NO_STOCK, "库存不足");
        }
        existCart.setNumber((short) num);
        if (cartService.updateById(existCart) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
    }

    return ResponseUtil.ok(existCart != null ? existCart.getId() : cart.getId());
}
 
Example 16
Source File: AnalyticsUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Returns a mapping between identifiers and meta data items for the given query.
 *
 * @param params the data query parameters.
 * @return a mapping between identifiers and meta data items.
 */
public static Map<String, MetadataItem> getDimensionMetadataItemMap( DataQueryParams params )
{
    List<DimensionalObject> dimensions = params.getDimensionsAndFilters();

    Map<String, MetadataItem> map = new HashMap<>();

    Calendar calendar = PeriodType.getCalendar();

    boolean includeMetadataDetails = params.isIncludeMetadataDetails();

    for ( DimensionalObject dimension : dimensions )
    {
        for ( DimensionalItemObject item : dimension.getItems() )
        {
            if ( DimensionType.PERIOD == dimension.getDimensionType() && !calendar.isIso8601() )
            {
                Period period = (Period) item;
                DateTimeUnit dateTimeUnit = calendar.fromIso( period.getStartDate() );
                String isoDate = period.getPeriodType().getIsoDate( dateTimeUnit );
                map.put( isoDate, new MetadataItem( period.getDisplayName(), includeMetadataDetails ? period : null ) );
            }
            else
            {
                map.put( item.getDimensionItem(), new MetadataItem( item.getDisplayProperty( params.getDisplayProperty() ), includeMetadataDetails ? item : null ) );
            }

            if ( DimensionType.ORGANISATION_UNIT == dimension.getDimensionType() && params.isHierarchyMeta() )
            {
                OrganisationUnit unit = (OrganisationUnit) item;

                for ( OrganisationUnit ancestor : unit.getAncestors() )
                {
                    map.put( ancestor.getUid(), new MetadataItem( ancestor.getDisplayProperty( params.getDisplayProperty() ), includeMetadataDetails ? ancestor : null ) );
                }
            }

            if ( DimensionItemType.DATA_ELEMENT == item.getDimensionItemType() )
            {
                DataElement dataElement = (DataElement) item;

                for ( CategoryOptionCombo coc : dataElement.getCategoryOptionCombos() )
                {
                    map.put( coc.getUid(), new MetadataItem( coc.getDisplayProperty( params.getDisplayProperty() ), includeMetadataDetails ? coc : null ) );
                }
            }
        }

        map.put( dimension.getDimension(), new MetadataItem( dimension.getDisplayProperty( params.getDisplayProperty() ), includeMetadataDetails ? dimension : null ) );

        if ( dimension.getDimensionalKeywords() != null )
        {
            dimension.getDimensionalKeywords().getGroupBy()
                .forEach( b -> map.put( b.getKey(), new MetadataItem( b.getName(), b.getUid(), b.getCode() ) ) );
        }

    }

    Program program = params.getProgram();
    ProgramStage stage = params.getProgramStage();

    if ( ObjectUtils.allNotNull( program ) )
    {
        map.put( program.getUid(), new MetadataItem( program.getDisplayProperty( params.getDisplayProperty() ), includeMetadataDetails ? program : null ) );

        if ( stage != null )
        {
            map.put( stage.getUid(), new MetadataItem( stage.getDisplayName(), includeMetadataDetails ? stage : null ) );
        }
        else
        {
            for ( ProgramStage ps : program.getProgramStages() )
            {
                map.put( ps.getUid(), new MetadataItem( ps.getDisplayName(), includeMetadataDetails ? ps : null ) );
            }
        }
    }

    return map;
}
 
Example 17
Source File: WxCartController.java    From dts-shop with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 加入商品到购物车
 * <p>
 * 如果已经存在购物车货品,则增加数量; 否则添加新的购物车货品项。
 *
 * @param userId
 *            用户ID
 * @param cart
 *            购物车商品信息, { goodsId: xxx, productId: xxx, number: xxx }
 * @return 加入购物车操作结果
 */
@PostMapping("add")
public Object add(@LoginUser Integer userId, @RequestBody DtsCart cart) {
	logger.info("【请求开始】加入商品到购物车,请求参数,userId:{},cart:{}", userId, JSONObject.toJSONString(cart));

	if (userId == null) {
		logger.error("加入商品到购物车失败:用户未登录!!!");
		return ResponseUtil.unlogin();
	}
	if (cart == null) {
		return ResponseUtil.badArgument();
	}

	Integer productId = cart.getProductId();
	Integer number = cart.getNumber().intValue();
	Integer goodsId = cart.getGoodsId();
	if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
		return ResponseUtil.badArgument();
	}

	// 判断商品是否可以购买
	DtsGoods goods = goodsService.findById(goodsId);
	if (goods == null || !goods.getIsOnSale()) {
		logger.error("加入商品到购物车失败:{}", GOODS_UNSHELVE.desc());
		return WxResponseUtil.fail(GOODS_UNSHELVE);
	}

	DtsGoodsProduct product = productService.findById(productId);
	// 判断购物车中是否存在此规格商品
	DtsCart existCart = cartService.queryExist(goodsId, productId, userId);
	if (existCart == null) {
		// 取得规格的信息,判断规格库存
		if (product == null || number > product.getNumber()) {
			logger.error("加入商品到购物车失败:{}", GOODS_NO_STOCK.desc());
			return WxResponseUtil.fail(GOODS_NO_STOCK);
		}

		cart.setId(null);
		cart.setGoodsSn(goods.getGoodsSn());
		cart.setBrandId(goods.getBrandId());// 新增入驻商户
		cart.setGoodsName((goods.getName()));
		cart.setPicUrl(goods.getPicUrl());
		cart.setPrice(product.getPrice());
		cart.setSpecifications(product.getSpecifications());
		cart.setUserId(userId);
		cart.setChecked(true);
		cartService.add(cart);
	} else {
		// 取得规格的信息,判断规格库存
		int num = existCart.getNumber() + number;
		if (num > product.getNumber()) {
			logger.error("加入商品到购物车失败:{}", GOODS_NO_STOCK.desc());
			return WxResponseUtil.fail(GOODS_NO_STOCK);
		}
		existCart.setNumber((short) num);
		if (cartService.updateById(existCart) == 0) {
			logger.error("加入商品到购物车失败:更新购物车信息失败!");
			return ResponseUtil.updatedDataFailed();
		}
	}
	logger.info("【请求结束】加入商品到购物车成功!");
	return goodscount(userId);
}
 
Example 18
Source File: WxCartController.java    From BigDataPlatform with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 修改购物车商品货品数量
 *
 * @param userId 用户ID
 * @param cart   购物车商品信息, { id: xxx, goodsId: xxx, productId: xxx, number: xxx }
 * @return 修改结果
 */
@PostMapping("update")
public Object update(@LoginUser Integer userId, @RequestBody LitemallCart cart) {
    if (userId == null) {
        return ResponseUtil.unlogin();
    }
    if (cart == null) {
        return ResponseUtil.badArgument();
    }
    Integer productId = cart.getProductId();
    Integer number = cart.getNumber().intValue();
    Integer goodsId = cart.getGoodsId();
    Integer id = cart.getId();
    if (!ObjectUtils.allNotNull(id, productId, number, goodsId)) {
        return ResponseUtil.badArgument();
    }
    if(number <= 0){
        return ResponseUtil.badArgument();
    }

    //判断是否存在该订单
    // 如果不存在,直接返回错误
    LitemallCart existCart = cartService.findById(id);
    if (existCart == null) {
        return ResponseUtil.badArgumentValue();
    }

    // 判断goodsId和productId是否与当前cart里的值一致
    if (!existCart.getGoodsId().equals(goodsId)) {
        return ResponseUtil.badArgumentValue();
    }
    if (!existCart.getProductId().equals(productId)) {
        return ResponseUtil.badArgumentValue();
    }

    //判断商品是否可以购买
    LitemallGoods goods = goodsService.findById(goodsId);
    if (goods == null || !goods.getIsOnSale()) {
        return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE, "商品已下架");
    }

    //取得规格的信息,判断规格库存
    LitemallGoodsProduct product = productService.findById(productId);
    if (product == null || product.getNumber() < number) {
        return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE, "库存不足");
    }

    existCart.setNumber(number.shortValue());
    if (cartService.updateById(existCart) == 0) {
        return ResponseUtil.updatedDataFailed();
    }
    return ResponseUtil.ok();
}
 
Example 19
Source File: WxCartController.java    From BigDataPlatform with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 立即购买
 * <p>
 * 和add方法的区别在于:
 * 1. 如果购物车内已经存在购物车货品,前者的逻辑是数量添加,这里的逻辑是数量覆盖
 * 2. 添加成功以后,前者的逻辑是返回当前购物车商品数量,这里的逻辑是返回对应购物车项的ID
 *
 * @param userId 用户ID
 * @param cart   购物车商品信息, { goodsId: xxx, productId: xxx, number: xxx }
 * @return 立即购买操作结果
 */
@PostMapping("fastadd")
public Object fastadd(@LoginUser Integer userId, @RequestBody LitemallCart cart) {
    if (userId == null) {
        return ResponseUtil.unlogin();
    }
    if (cart == null) {
        return ResponseUtil.badArgument();
    }

    Integer productId = cart.getProductId();
    Integer number = cart.getNumber().intValue();
    Integer goodsId = cart.getGoodsId();
    if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
        return ResponseUtil.badArgument();
    }
    if(number <= 0){
        return ResponseUtil.badArgument();
    }

    //判断商品是否可以购买
    LitemallGoods goods = goodsService.findById(goodsId);
    if (goods == null || !goods.getIsOnSale()) {
        return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE, "商品已下架");
    }

    LitemallGoodsProduct product = productService.findById(productId);
    //判断购物车中是否存在此规格商品
    LitemallCart existCart = cartService.queryExist(goodsId, productId, userId);
    if (existCart == null) {
        //取得规格的信息,判断规格库存
        if (product == null || number > product.getNumber()) {
            return ResponseUtil.fail(WxResponseCode.GOODS_NO_STOCK, "库存不足");
        }

        cart.setId(null);
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName((goods.getName()));
        cart.setPicUrl(goods.getPicUrl());
        cart.setPrice(product.getPrice());
        cart.setSpecifications(product.getSpecifications());
        cart.setUserId(userId);
        cart.setChecked(true);
        cartService.add(cart);
    } else {
        //取得规格的信息,判断规格库存
        int num = number;
        if (num > product.getNumber()) {
            return ResponseUtil.fail(WxResponseCode.GOODS_NO_STOCK, "库存不足");
        }
        existCart.setNumber((short) num);
        if (cartService.updateById(existCart) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
    }

    return ResponseUtil.ok(existCart != null ? existCart.getId() : cart.getId());
}
 
Example 20
Source File: WxCartController.java    From BigDataPlatform with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 加入商品到购物车
 * <p>
 * 如果已经存在购物车货品,则增加数量;
 * 否则添加新的购物车货品项。
 *
 * @param userId 用户ID
 * @param cart   购物车商品信息, { goodsId: xxx, productId: xxx, number: xxx }
 * @return 加入购物车操作结果
 */
@PostMapping("add")
public Object add(@LoginUser Integer userId, @RequestBody LitemallCart cart) {
    if (userId == null) {
        return ResponseUtil.unlogin();
    }
    if (cart == null) {
        return ResponseUtil.badArgument();
    }

    Integer productId = cart.getProductId();
    Integer number = cart.getNumber().intValue();
    Integer goodsId = cart.getGoodsId();
    if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
        return ResponseUtil.badArgument();
    }
    if(number <= 0){
        return ResponseUtil.badArgument();
    }

    //判断商品是否可以购买
    LitemallGoods goods = goodsService.findById(goodsId);
    if (goods == null || !goods.getIsOnSale()) {
        return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE, "商品已下架");
    }

    LitemallGoodsProduct product = productService.findById(productId);
    //判断购物车中是否存在此规格商品
    LitemallCart existCart = cartService.queryExist(goodsId, productId, userId);
    if (existCart == null) {
        //取得规格的信息,判断规格库存
        if (product == null || number > product.getNumber()) {
            return ResponseUtil.fail(WxResponseCode.GOODS_NO_STOCK, "库存不足");
        }

        cart.setId(null);
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName((goods.getName()));
        cart.setPicUrl(goods.getPicUrl());
        cart.setPrice(product.getPrice());
        cart.setSpecifications(product.getSpecifications());
        cart.setUserId(userId);
        cart.setChecked(true);
        cartService.add(cart);
    } else {
        //取得规格的信息,判断规格库存
        int num = existCart.getNumber() + number;
        if (num > product.getNumber()) {
            return ResponseUtil.fail(WxResponseCode.GOODS_NO_STOCK, "库存不足");
        }
        existCart.setNumber((short) num);
        if (cartService.updateById(existCart) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
    }

    return goodscount(userId);
}