cn.hutool.core.lang.Assert Java Examples

The following examples show how to use cn.hutool.core.lang.Assert. 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: ApiDocProjectUserController.java    From feiqu-opensource with Apache License 2.0 6 votes vote down vote up
@PostMapping("dealInvite")
@ResponseBody
public Object list(Long id,Integer status) {
    BaseResult result = new BaseResult();
    try {
        ApiDocProjectUser apiDocProjectUser = apiDocProjectUserService.selectByPrimaryKey(id);
        Assert.notNull(apiDocProjectUser,"邀请不存在");
        //此条邀请已经被处理过了
        if(apiDocProjectUser.getStatus() != 0){
            result.setCode("1");
            result.setMessage("该条邀请已经被处理了!");
            return result;
        }
        if(apiDocProjectUser.getStatus().equals(status)){
           return result;
        }
        ApiDocProjectUser toUpdate = new ApiDocProjectUser();
        toUpdate.setId(id);
        toUpdate.setStatus(status);
        apiDocProjectUserService.updateByPrimaryKeySelective(toUpdate);
    } catch (Exception e) {
        logger.error("error", e);
        result.setCode("1");
    }
    return result;
}
 
Example #2
Source File: ClassUtil.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null.
 */
public static Field getAccessibleField(final Class<?> cls, final String fieldName) {
	Assert.notNull(cls, "cls can't be null");
	Assert.notEmpty(fieldName, "fieldName can't be blank");
	for (Class<?> superClass = cls; superClass != Object.class; superClass = superClass
		.getSuperclass()) {
		try {
			Field field = superClass.getDeclaredField(fieldName);
			makeAccessible(field);
			return field;
		} catch (NoSuchFieldException e) {// NOSONAR
			// Field不在当前类定义,继续向上转型
			continue;// new add
		}
	}
	return null;
}
 
Example #3
Source File: ValidateCodeController.java    From Taroco with Apache License 2.0 6 votes vote down vote up
/**
 * 创建验证码
 *
 * @throws Exception
 */
@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{randomStr}")
public void createCode(@PathVariable String randomStr, HttpServletResponse response)
        throws Exception {
    Assert.notEmpty(randomStr, "机器码不能为空");
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.setContentType("image/jpeg");
    //生成文字验证码
    String text = producer.createText();
    //生成图片验证码
    BufferedImage image = producer.createImage(text);
    userService.saveImageCode(randomStr, text);
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(image, "JPEG", out);
    IOUtils.closeQuietly(out);
}
 
Example #4
Source File: Db.java    From Aooms with Apache License 2.0 6 votes vote down vote up
/**
 * 注意:开启	@Transactional 时无法使用该方法
 */
public void useOn(String name) {
    Assert.notNull(name,"datasource name is not allow null !");
    // 如果包含在当前spring事务中,拒绝操作
    if(TransactionSynchronizationManager.isActualTransactionActive()){
        throw new UnsupportedOperationException("Cannot be used in spring transactions !");
    }

    if (!DynamicDataSourceHolder.containsDataSource(name)) {
        logger.error("datasource [{}] not found !",name);
    } else {
        logger.info("on datasource [{}]",name);
        // 设置动态数据源上下文
        DynamicDataSourceHolder.setDataSource(name);
    }
}
 
Example #5
Source File: Db.java    From Aooms with Apache License 2.0 6 votes vote down vote up
/**
 * 注意:开启	@Transactional 时无法使用该方法
 */
public Db use(String name) {
    Assert.notNull(name,"datasource name is not allow null !");
    // 如果包含在当前spring事务中,拒绝操作
    if(TransactionSynchronizationManager.isActualTransactionActive()){
        throw new UnsupportedOperationException("Cannot be used in spring transactions !");
    }

    if (!DynamicDataSourceHolder.containsDataSource(name)) {
        logger.error("datasource [{}] not found !",name);
    } else {
        logger.info("use datasource [{}]",name);
        // 设置动态数据源上下文
        DynamicDataSourceHolder.setDataSource(name);
    }

    return this;
}
 
Example #6
Source File: AbstractSessionManager.java    From bitchat with Apache License 2.0 6 votes vote down vote up
@Override
public void removeSession(ChannelId channelId) {
    Assert.notNull(channelId, "channelId can not be null");
    Collection<Session> sessions = allSession();
    if (CollectionUtil.isEmpty(sessions)) {
        return;
    }
    Iterator<Session> iterator = sessions.iterator();
    while (iterator.hasNext()) {
        Session session = iterator.next();
        if (session.channelId() == channelId) {
            iterator.remove();
            log.info("remove a session, session={}, channelId={}", session, channelId);
            break;
        }
    }
}
 
Example #7
Source File: FqWebsiteDirController.java    From feiqu-opensource with Apache License 2.0 6 votes vote down vote up
/**
 * ajax删除FqWebsiteDir
 */
@ResponseBody
@RequestMapping("/delete")
public Object delete(@RequestParam Integer id) {
    BaseResult result = new BaseResult();
    try {
        FqUserCache fqUserCache = getCurrentUser();
        if(fqUserCache == null){
            result.setResult(ResultEnum.USER_NOT_LOGIN);
            return result;
        }
        logger.info("删除网址:用户id:{},图片id:{}",fqUserCache.getId(),id);
        FqWebsiteDir fqWebsiteDir = fqWebsiteDirService.selectByPrimaryKey(id);
        Assert.notNull(fqWebsiteDir,"网址不能为空");
        fqWebsiteDir.setDelFlag(YesNoEnum.YES.getValue());
        fqWebsiteDirService.updateByPrimaryKey(fqWebsiteDir);
        CacheManager.refreshWebsiteCache();
    } catch (Exception e) {
        logger.error("删除网址报错",e);
        result.setResult(ResultEnum.SYSTEM_ERROR);
        return result;
    }
    return result;
}
 
Example #8
Source File: FqFriendLinkController.java    From feiqu-opensource with Apache License 2.0 6 votes vote down vote up
/**
 * ajax删除
 */
@ResponseBody
@PostMapping("/manage/delete")
public Object delete(@RequestParam Integer id) {
    BaseResult result = new BaseResult();
    try {
        FqUserCache fqUserCache = getCurrentUser();
        if(fqUserCache == null){
            result.setResult(ResultEnum.USER_NOT_LOGIN);
            return result;
        }
        logger.info("删除友链:用户id:{},友链id:{}",fqUserCache.getId(),id);
        FqFriendLink fqFriendLink = fqFriendLinkService.selectByPrimaryKey(id);
        Assert.notNull(fqFriendLink,"网址不能为空");
        fqFriendLinkService.deleteByPrimaryKey(id);
        CommonConstant.FRIEND_LINK_LIST.remove(fqFriendLink);
    } catch (Exception e) {
        logger.error("删除友链报错",e);
        result.setCode("1");
        result.setMessage(e.getMessage());
        return result;
    }
    return result;
}
 
Example #9
Source File: UserDetailsServiceImpl.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 用户密码登录
 *
 * @param username 用户名
 * @return
 */
@Override
@SneakyThrows
public UserDetails loadUserByUsername(String username) {
	UserVo userVo = userService.findVoByUsername(username);
	if (userVo == null) {
		throw new UsernameNotFoundException("用户不存在");
	}
	Assert.isTrue(userVo.isAvailable(), "用户【" + username + "】已被锁定,无法登录");
	UserDetails userDetails = getUserDetails(userService.getInfo(userVo));
	return userDetails;
}
 
Example #10
Source File: Sequence.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 有参构造器
 * </p>
 *
 * @param workerId     工作机器 ID
 * @param datacenterId 序列号
 */
public Sequence(long workerId, long datacenterId) {
    Assert.isFalse(workerId > maxWorkerId || workerId < 0,
            String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
    Assert.isFalse(datacenterId > maxDatacenterId || datacenterId < 0,
            String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
    this.workerId = workerId;
    this.datacenterId = datacenterId;
}
 
Example #11
Source File: ServerBootstrap.java    From bitchat with Apache License 2.0 5 votes vote down vote up
public void start(Integer serverPort) {
    ServerFactory factory = SimpleServerFactory.getInstance();
    Server server;
    if (ServerMode.STAND_ALONE == serverMode) {
        server = factory.newServer(serverPort, channelListener);
    } else {
        Assert.notNull(routerServerAttr, "routerServerAttr can not be null cause you are starting the server in cluster mode");
        Assert.isTrue(routerServerAttr.valid(), "routerServerAttr is invalid");
        server = factory.newClusterServer(serverPort, channelListener, routerServerAttr);
    }
    server.start();
}
 
Example #12
Source File: DefaultSession.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public void bound(ChannelId channelId, long userId) {
    if (bounded.compareAndSet(false, true)) {
        ChannelWrapper channelWrapper = ChannelHelper.getChannelWrapper(channelId);
        Assert.notNull(channelWrapper, "channelId does not exists");
        this.channelId = channelId;
        this.userId = userId;
        this.channel = channelWrapper.getChannel();
        this.channelType = channelWrapper.getChannelType();
    }
}
 
Example #13
Source File: MqBaseModel.java    From scaffold-cloud with MIT License 5 votes vote down vote up
/**
 * 获取构造message
 *
 * @return
 */
@JSONField(serialize = false)
public Message getMessage() {
    Assert.notNull(getTag(), "tag cannot be null");
    Assert.notNull(getRequestNo(), "requestNo cannot be null");
    this.key = String.format(MqConstant.ROCKETMQ_MESSAGE_KEY, tag,
            StrUtil.lowerFirst(this.getClass().getSimpleName()), getRequestNo());
    Assert.notNull(getKey(), "key");
    Message message = new Message(TOPIC, getTag(), getKey(), this.toString().getBytes());
    Properties userProperties = new Properties();
    userProperties.setProperty(MqConstant.MODEL_CLASS_NAME, modelClassName);
    message.setUserProperties(userProperties);
    return message;
}
 
Example #14
Source File: AbstractSessionManager.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public void bound(Session session, ChannelId channelId, long userId) {
    Assert.notNull(session, "session can not be null");
    Assert.notNull(channelId, "channelId can not be null");
    session.bound(channelId, userId);
    sessionMap.putIfAbsent(session.sessionId(), session);
    log.info("bound a new session, session={}, channelId={}", session, channelId);
}
 
Example #15
Source File: DefaultChannelManager.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelWrapper getChannelWrapper(String longId) {
    Assert.notNull(longId, "longId can not be null");
    if (channels.isEmpty()) {
        return null;
    }
    Channel channel = channels.stream()
            .filter(item -> item.id().asLongText().equals(longId))
            .findFirst()
            .orElse(null);
    return wrapChannel(channel);
}
 
Example #16
Source File: DefaultChannelManager.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelWrapper getChannelWrapper(ChannelId channelId) {
    Assert.notNull(channelId, "channelId can not be null");
    if (channels.isEmpty()) {
        return null;
    }
    Channel channel = channels.find(channelId);
    return wrapChannel(channel);
}
 
Example #17
Source File: DefaultChannelManager.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public void addChannel(Channel channel, ChannelType channelType) {
    Assert.notNull(channel, "channel can not be null");
    Assert.notNull(channelType, "channelType can not be null");
    channel.attr(CHANNEL_TYPE).set(channelType);
    channels.add(channel);
}
 
Example #18
Source File: GenericClient.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public void connect() {
    Assert.notNull(serverAttr, "serverAttr can not be null");
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group)
            .channel(NioSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new ClientInitializer(GenericClient.this));
                }
            });

    ChannelFuture future = bootstrap.connect(serverAttr.getAddress(), serverAttr.getPort());
    future.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> f) throws Exception {
            channel = future.channel();
            if (f.isSuccess()) {
                connected = true;
                log.info("[{}] Has connected to {} successfully", GenericClient.class.getSimpleName(), serverAttr);
            } else {
                log.warn("[{}] Connect to {} failed, cause={}", GenericClient.class.getSimpleName(), serverAttr, f.cause().getMessage());
                // fire the channelInactive and make sure
                // the {@link HealthyChecker} will reconnect
                channel.pipeline().fireChannelInactive();
            }
        }
    });
}
 
Example #19
Source File: PacketCodec.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
    // leastPacketLen = 1byte(magic) + 1byte(serialize algorithm) + 1byte(packet type) + 4bytes(content length)
    int leastPacketLen = 7;
    // until we can read at least 7 bytes
    if (in.readableBytes() < leastPacketLen) {
        return;
    }
    // mark reader index at here
    // if no enough bytes arrived
    // we should wait and reset the
    // reader index to here
    in.markReaderIndex();
    // do common check before decode
    byte magic = in.readByte();
    Assert.state(magic == Packet.PACKET_MAGIC, "magic number is invalid");

    byte algorithm = in.readByte();
    Serializer serializer = chooser.choose(algorithm);
    Assert.notNull(serializer, "No serializer is chosen cause the algorithm of packet is invalid");
    byte type = in.readByte();
    int len = in.readInt();
    // until we have the entire packet received
    if (in.readableBytes() < len) {
        // after read some bytes: magic/algorithm/type/len
        // the left readable bytes length is less than len
        // so we need to wait until enough bytes received
        // but we must reset the reader index to we marked
        // before we return
        in.resetReaderIndex();
        return;
    }
    // read content
    byte[] content = new byte[len];
    in.readBytes(content);

    Packet packet = serializer.deserialize(content, DefaultPacket.class);
    out.add(packet);
}
 
Example #20
Source File: SchemeResource.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Log(value = "方案生成代码")
@PutMapping(value = "/gen-code")
@PreAuthorize("@pms.hasPermission('gen_scheme_code')")
public Result genCode(@Valid @RequestBody GenCodeDto genCodeDto) {
	SchemeDto genSchemeDto = schemeService.getOneDto(genCodeDto.getId());
	Assert.isTrue(genSchemeDto != null, "无法获取代码生成方案信息");
	genSchemeDto.setReplaceFile(genCodeDto.getReplaceFile());
	schemeService.generateCode(genSchemeDto);
	return Result.buildOk("生成", genSchemeDto.getName(), "代码成功");
}
 
Example #21
Source File: Db.java    From Aooms with Apache License 2.0 4 votes vote down vote up
/**
 * 删除对象
 * @return
 * @
 */
public int delete(String tableName, Record record)  {
    Assert.notNull(record,"record must not be null");
    record.setGeneral(MyBatisConst.TABLE_NAME_PLACEHOLDER,tableName);
    return getSqlSession().delete(MyBatisConst.MS_RECORD_DELETE, record);
}
 
Example #22
Source File: ID.java    From Aooms with Apache License 2.0 4 votes vote down vote up
public String stringValue(){
    Assert.notNull(value,"ID Value cannot be null");
    return value.toString();
}
 
Example #23
Source File: Db.java    From Aooms with Apache License 2.0 4 votes vote down vote up
/**
 * 更新对象
 * @return
 * @
 */
public int update(String tableName, Record record){
    Assert.notNull(record,"record must not be null");
    record.setGeneral(MyBatisConst.TABLE_NAME_PLACEHOLDER,tableName);
    return getSqlSession().update(MyBatisConst.MS_RECORD_UPDATE, record);
}
 
Example #24
Source File: RedisConfig.java    From eladmin with Apache License 2.0 4 votes vote down vote up
private StringRedisSerializer(Charset charset) {
    Assert.notNull(charset, "Charset must not be null!");
    this.charset = charset;
}
 
Example #25
Source File: Db.java    From Aooms with Apache License 2.0 4 votes vote down vote up
/**
 * 保存对象
 * @return 
 * @ 
 */
public int insert(String tableName, Record record) {
    Assert.notNull(record,"record must not be null");
    record.setGeneral(MyBatisConst.TABLE_NAME_PLACEHOLDER,tableName);
    return getSqlSession().insert(MyBatisConst.MS_RECORD_INSERT, record);
}
 
Example #26
Source File: RedisConfig.java    From sk-admin with Apache License 2.0 4 votes vote down vote up
private StringRedisSerializer(Charset charset) {
    Assert.notNull(charset, "Charset must not be null!");
    this.charset = charset;
}
 
Example #27
Source File: FrameHandler.java    From bitchat with Apache License 2.0 4 votes vote down vote up
private FrameHandler(ChannelListener channelListener) {
    Assert.notNull(channelListener, "channelListener can not be null");
    this.executor = FrameExecutor.getInstance();
    this.channelListener = channelListener;
}
 
Example #28
Source File: PacketHandler.java    From bitchat with Apache License 2.0 4 votes vote down vote up
private PacketHandler(ChannelListener channelListener) {
    Assert.notNull(channelListener, "channelListener can not be null");
    this.executor = PacketExecutor.getInstance();
    this.channelListener = channelListener;
}
 
Example #29
Source File: ClusterServer.java    From bitchat with Apache License 2.0 4 votes vote down vote up
public ClusterServer(Integer serverPort, ChannelListener channelListener, RouterServerAttr routerServerAttr) {
    super(serverPort, channelListener);
    Assert.notNull(routerServerAttr, "routerServerAttr can not be null");
    this.routerServerAttr = routerServerAttr;
}
 
Example #30
Source File: HttpHandler.java    From bitchat with Apache License 2.0 4 votes vote down vote up
private HttpHandler(ChannelListener channelListener) {
    Assert.notNull(channelListener, "channelListener can not be null");
    this.executor = HttpExecutor.getInstance();
    this.channelListener = channelListener;
}