Java Code Examples for org.apache.commons.lang3.StringUtils#isAnyEmpty()

The following examples show how to use org.apache.commons.lang3.StringUtils#isAnyEmpty() . 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: AbstractU2Handler.java    From openzaly with Apache License 2.0 6 votes vote down vote up
protected void msgStatusResponse(Command command, String msgId, long msgTime, int statusValue) {
	if (command == null || StringUtils.isAnyEmpty(command.getDeviceId(), msgId)) {
		return;
	}
	CoreProto.MsgStatus status = CoreProto.MsgStatus.newBuilder().setMsgId(msgId).setMsgStatus(statusValue)
			.setMsgServerTime(msgTime).build();

	ImStcMessageProto.MsgWithPointer statusMsg = ImStcMessageProto.MsgWithPointer.newBuilder()
			.setType(MsgType.MSG_STATUS).setStatus(status).build();

	ImStcMessageProto.ImStcMessageRequest request = ImStcMessageProto.ImStcMessageRequest.newBuilder()
			.addList(statusMsg).build();

	CoreProto.TransportPackageData data = CoreProto.TransportPackageData.newBuilder()
			.setData(request.toByteString()).build();

	ChannelWriter.writeByDeviceId(command.getDeviceId(), new RedisCommand().add(CommandConst.PROTOCOL_VERSION)
			.add(CommandConst.IM_MSG_TOCLIENT).add(data.toByteArray()));
}
 
Example 2
Source File: AbstractPoolManager.java    From openzaly with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化连接池主库
 * 
 * @param pro
 * @return
 * @throws Exception
 */
public static String getJdbcUrl(Properties pro) throws Exception {
	String host = trimToNull(pro, JdbcConst.MYSQL_HOST);
	String port = trimToNull(pro, JdbcConst.MYSQL_PORT);
	String dbName = trimToNull(pro, JdbcConst.MYSQL_DB);

	// "jdbc:mysql://localhost:3306/mysql?";
	String url = "jdbc:mysql://" + host + ":" + port + "/" + dbName;

	if (StringUtils.isAnyEmpty(host, port, dbName)) {
		throw new Exception("jdbc url=" + url + " is invalid");
	}

	String useUnicode = trimToNull(pro, JdbcConst.MYSQL_USE_UNICODE, "true");
	String characterEncoding = trimToNull(pro, JdbcConst.MYSQL_CHARACTER_ENCODING, "utf-8");
	String verifyServerCertificate = trimToNull(pro, JdbcConst.MYSQL_VERIFY_SERVER_CERTIFICATE, "false");
	String useSSL = trimToNull(pro, JdbcConst.MYSQL_USE_SSL, "true");

	StringBuilder sb = buildJdbcUrlWithParameters(url, useUnicode, characterEncoding, verifyServerCertificate,
			useSSL);

	return sb.toString();
}
 
Example 3
Source File: HttpUtils.java    From azeroth with Apache License 2.0 6 votes vote down vote up
public static String buildQuery(Map<String, String> params, String charset) throws IOException {
    if (params == null || params.isEmpty()) {
        return null;
    }

    StringBuilder query = new StringBuilder();
    Set<Entry<String, String>> entries = params.entrySet();
    boolean hasParam = false;

    for (Entry<String, String> entry : entries) {
        String name = entry.getKey();
        String value = entry.getValue();
        // 忽略参数名或参数值为空的参数
        if (StringUtils.isAnyEmpty(name, value)) {
            if (hasParam) {
                query.append("&");
            } else {
                hasParam = true;
            }

            query.append(name).append("=").append(URLEncoder.encode(value, charset));
        }
    }

    return query.toString();
}
 
Example 4
Source File: AbstractU2Handler.java    From wind-im with Apache License 2.0 6 votes vote down vote up
protected void msgStatusResponse(Command command, String msgId, long msgTime, int statusValue) {
	if (command == null || StringUtils.isAnyEmpty(command.getDeviceId(), msgId)) {
		return;
	}
	CoreProto.MsgStatus status = CoreProto.MsgStatus.newBuilder().setMsgId(msgId).setMsgStatus(statusValue)
			.setMsgServerTime(msgTime).build();

	ImStcMessageProto.MsgWithPointer statusMsg = ImStcMessageProto.MsgWithPointer.newBuilder()
			.setType(MsgType.MSG_STATUS).setStatus(status).build();

	ImStcMessageProto.ImStcMessageRequest request = ImStcMessageProto.ImStcMessageRequest.newBuilder()
			.addList(statusMsg).build();

	CoreProto.TransportPackageData data = CoreProto.TransportPackageData.newBuilder()
			.setData(request.toByteString()).build();

	ChannelWriter.writeByDeviceId(command.getDeviceId(), new RedisCommand().add(CommandConst.PROTOCOL_VERSION)
			.add(CommandConst.IM_MSG_TOCLIENT).add(data.toByteArray()));
}
 
Example 5
Source File: C3P0PoolSlaveManager.java    From openzaly with Apache License 2.0 5 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	List<String> jdbcUrlList = getSlaveDBUrl(pro);

	String userName = trimToNull(pro, JdbcConst.MYSQL_SLAVE_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_SLAVE_PASSWORD);

	if (jdbcUrlList == null || jdbcUrlList.size() == 0 || StringUtils.isAnyEmpty(userName, password)) {
		SqlLog.warn(
				"load database slave for mysql fail, system will user mysql master connection pool.urls={} user={} passwd={}",
				jdbcUrlList, userName, password);
		return;
	}

	cpdsList = new ArrayList<ComboPooledDataSource>();

	for (String jdbcUrl : jdbcUrlList) {
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
		cpds.setJdbcUrl(jdbcUrl);
		cpds.setUser(userName);
		cpds.setPassword(password);
		int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_INITIAL_SIZE, "10"));
		int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_SIZE, "100"));
		cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
		cpds.setMaxPoolSize(maxSize);// 最大默认100个
		int inc = (maxSize - inititalSize) / 5;
		cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建个数

		int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_IDLE, "60"));
		cpds.setMaxIdleTime(maxIdle);// 最大空闲时间

		cpdsList.add(cpds);

		SqlLog.info("openzaly init mysql slave connection pool cpds={}", cpds.toString());
	}
}
 
Example 6
Source File: AbstractPoolManager.java    From openzaly with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化从库连接池
 * 
 * @param pro
 * @return
 * @throws Exception
 */
public static List<String> getSlaveJdbcUrl(Properties pro) throws Exception {
	String slaveHosts = trimToNull(pro, JdbcConst.MYSQL_SLAVE_HOST);// 192.168.3.4,192.168.3.5,192.168.3.6

	if (StringUtils.isEmpty(slaveHosts)) {
		return null;
	}

	List<String> urlList = new ArrayList<String>();
	String[] hosts = slaveHosts.split(",");

	for (String host : hosts) {
		host = StringUtils.trimToNull(host);
		String port = trimToNull(pro, JdbcConst.MYSQL_PORT);
		String dbName = trimToNull(pro, JdbcConst.MYSQL_DB);

		// "jdbc:mysql://localhost:3306/mysql?";
		String url = "jdbc:mysql://" + host + ":" + port + "/" + dbName;

		if (StringUtils.isAnyEmpty(host, port, dbName)) {
			throw new Exception("mysql slave jdbc url=" + url + " is invalid");
		}

		String useUnicode = pro.getProperty(JdbcConst.MYSQL_SLAVE_USE_UNICODE, "true");
		String characterEncoding = pro.getProperty(JdbcConst.MYSQL_SLAVE_CHARACTER_ENCODING, "utf-8");
		String verifyServerCertificate = pro.getProperty(JdbcConst.MYSQL_SLAVE_VERIFY_SERVER_CERTIFICATE, "false");
		String useSSL = pro.getProperty(JdbcConst.MYSQL_SLAVE_USE_SSL, "true");

		StringBuilder sb = buildJdbcUrlWithParameters(url, useUnicode, characterEncoding, verifyServerCertificate,
				useSSL);

		urlList.add(sb.toString());
	}
	return urlList;
}
 
Example 7
Source File: C3P0PoolSlaveManager.java    From openzaly with Apache License 2.0 5 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	List<String> jdbcUrlList = getSlaveJdbcUrl(pro);

	String userName = trimToNull(pro, JdbcConst.MYSQL_SLAVE_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_SLAVE_PASSWORD);

	if (jdbcUrlList == null || jdbcUrlList.size() == 0 || StringUtils.isAnyEmpty(userName, password)) {
		SqlLog.warn(
				"load database slave for mysql fail, system will user mysql master connection pool.urls={} user={} passwd={}",
				jdbcUrlList, userName, password);
		return;
	}

	cpdsList = new ArrayList<ComboPooledDataSource>();

	for (String jdbcUrl : jdbcUrlList) {
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
		cpds.setJdbcUrl(jdbcUrl);
		cpds.setUser(userName);
		cpds.setPassword(password);
		int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_INITIAL_SIZE, "10"));
		int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_SIZE, "100"));
		cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
		cpds.setMaxPoolSize(maxSize);// 最大默认100个
		int inc = (maxSize - inititalSize) / 5;
		cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建个数

		int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_IDLE, "60"));
		cpds.setMaxIdleTime(maxIdle);// 最大空闲时间

		cpdsList.add(cpds);

		SqlLog.info("openzaly init mysql slave connection pool cpds={}", cpds.toString());
	}
}
 
Example 8
Source File: StackService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void storeTelemetryForStack(Stack stack) {
    if (stack.getCluster() == null || StringUtils.isAnyEmpty(stack.getType().name(), stack.getResourceCrn(), stack.getCluster().getName())) {
        return;
    }
    List<Component> enrichedComponents = stack.getComponents().stream()
            .filter(component -> ComponentType.TELEMETRY.equals(component.getComponentType()))
            .map(component -> {
                LOGGER.debug("Found TELEMETRY component for stack, will enrich that with cluster data before saving it.");
                FluentClusterType fluentClusterType = StackType.DATALAKE.equals(stack.getType())
                        ? FluentClusterType.DATALAKE : FluentClusterType.DATAHUB;
                try {
                    Telemetry telemetry = component.getAttributes().get(Telemetry.class);
                    if (telemetry != null) {
                        telemetry.setRules(accountTelemetryClientService.getAnonymizationRules());
                    }
                    cloudStorageFolderResolverService.updateStorageLocation(telemetry,
                            fluentClusterType.value(),
                            stack.getCluster().getName(), stack.getResourceCrn());
                    component.setAttributes(Json.silent(telemetry));
                } catch (IOException e) {
                    LOGGER.info("Could not create Cloudbreak telemetry component.", e);
                }
                return component;
            })
            .collect(Collectors.toList());
    componentConfigProviderService.store(enrichedComponents);
}
 
Example 9
Source File: PurgeApiAuthorizationFilter.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
protected CloudTarget extractTarget(HttpServletRequest request) {
    String organizationName = request.getParameter(ConfigurationEntriesResource.REQUEST_PARAM_ORGANIZATION);
    String spaceName = request.getParameter(ConfigurationEntriesResource.REQUEST_PARAM_SPACE);
    if (StringUtils.isAnyEmpty(organizationName, spaceName)) {
        throw new SLException(Messages.ORG_AND_SPACE_MUST_BE_SPECIFIED);
    }
    return new CloudTarget(organizationName, spaceName);
}
 
Example 10
Source File: C3P0PoolSlaveManager.java    From wind-im with Apache License 2.0 5 votes vote down vote up
public static void initPool(Properties pro) throws Exception {
	List<String> jdbcUrlList = getSlaveJdbcUrl(pro);

	String userName = trimToNull(pro, JdbcConst.MYSQL_SLAVE_USER_NAME);
	String password = trimToNull(pro, JdbcConst.MYSQL_SLAVE_PASSWORD);

	if (jdbcUrlList == null || jdbcUrlList.size() == 0 || StringUtils.isAnyEmpty(userName, password)) {
		SqlLog.warn(
				"load database slave for mysql fail, system will user mysql master connection pool.urls={} user={} passwd={}",
				jdbcUrlList, userName, password);
		return;
	}

	cpdsList = new ArrayList<ComboPooledDataSource>();

	for (String jdbcUrl : jdbcUrlList) {
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass(MYSQL_JDBC_DRIVER); // loads the jdbc driver
		cpds.setJdbcUrl(jdbcUrl);
		cpds.setUser(userName);
		cpds.setPassword(password);
		int inititalSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_INITIAL_SIZE, "10"));
		int maxSize = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_SIZE, "100"));
		cpds.setInitialPoolSize(inititalSize);// 初始创建默认10个连接
		cpds.setMaxPoolSize(maxSize);// 最大默认100个
		int inc = (maxSize - inititalSize) / 5;
		cpds.setAcquireIncrement(Integer.max(1, inc));// 每次创建个数

		int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_SLAVE_MAX_IDLE, "60"));
		cpds.setMaxIdleTime(maxIdle);// 最大空闲时间

		cpdsList.add(cpds);

		SqlLog.info("windchat init mysql slave connection pool cpds={}", cpds.toString());
	}
}
 
Example 11
Source File: ApiGroupService.java    From wind-im with Apache License 2.0 4 votes vote down vote up
/**
 * 用户更新群资料<br>
 * 群主/管理员权限限制
 *
 * @param command
 * @return
 */
public CommandResponse updateProfile(Command command) {
	CommandResponse commandResponse = new CommandResponse().setAction(CommandConst.ACTION_RES);
	IErrorCode errCode = ErrorCode2.ERROR;
	try {
		ApiGroupUpdateProfileProto.ApiGroupUpdateProfileRequest request = ApiGroupUpdateProfileProto.ApiGroupUpdateProfileRequest
				.parseFrom(command.getParams());
		String siteUserId = command.getSiteUserId();
		String groupId = request.getProfile().getId();
		String photoId = request.getProfile().getIcon();
		String groupName = request.getProfile().getName();
		String groupNotice = request.getProfile().getGroupNotice();
		// 新的群群主
		String newGroupOwner = request.getNewGroupOwner();
		// 是否可以邀请群聊(除了群主以外的其他群成员)
		boolean closeInviteGroupChat = request.getCloseInviteGroupChat();
		LogUtils.requestDebugLog(logger, command, request.toString());

		if (StringUtils.isAnyEmpty(siteUserId, groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_PARAMETER);
		}

		if (!checkGroupStatus(groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_GROUP_DELETED);
		}

		// 判断是否具有权限,群主拥有权限
		String groupMasterId = UserGroupDao.getInstance().getGroupMaster(groupId);
		if (siteUserId.equals(groupMasterId)) {
			GroupProfileBean gprofileBean = new GroupProfileBean();
			gprofileBean.setGroupId(groupId);
			gprofileBean.setGroupName(groupName);
			gprofileBean.setGroupPhoto(photoId);
			gprofileBean.setGroupNotice(groupNotice);
			gprofileBean.setCreateUserId(newGroupOwner);
			gprofileBean.setCloseInviteGroupChat(closeInviteGroupChat);

			if (StringUtils.isNotEmpty(groupName)) {
				if (UserGroupDao.getInstance().updateGroupProfile(gprofileBean)) {
					errCode = ErrorCode2.SUCCESS;
				}
			} else {
				if (UserGroupDao.getInstance().updateGroupIGC(gprofileBean)) {
					errCode = ErrorCode2.SUCCESS;
				}
			}
		} else {
			errCode = ErrorCode2.ERROR_NOPERMISSION;
		}

	} catch (Exception e) {
		if (e instanceof ZalyException) {
			errCode = ((ZalyException) e).getErrCode();
		} else {
			errCode = ErrorCode2.ERROR_SYSTEMERROR;
		}
		LogUtils.requestErrorLog(logger, command, e);
	}
	return commandResponse.setErrCode(errCode);
}
 
Example 12
Source File: ApiGroupService.java    From openzaly with Apache License 2.0 4 votes vote down vote up
/**
 * 获取用户群组中,不存在的好友用户
 *
 * @param command
 * @return
 */
public CommandResponse nonMembers(Command command) {
	CommandResponse commandResponse = new CommandResponse().setAction(CommandConst.ACTION_RES);
	IErrorCode errCode = ErrorCode2.ERROR;
	try {
		ApiGroupNonMembersProto.ApiGroupNonMembersRequest request = ApiGroupNonMembersProto.ApiGroupNonMembersRequest
				.parseFrom(command.getParams());
		String siteUserId = command.getSiteUserId();
		String groupId = request.getGroupId();
		int pageNum = request.getPageNumber();
		int pageSize = request.getPageSize();
		if (pageNum == 0 && pageSize == 0) {
			pageNum = 1;
			pageSize = 100;
		}
		LogUtils.requestDebugLog(logger, command, request.toString());

		if (StringUtils.isAnyEmpty(siteUserId, groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_PARAMETER);
		}

		if (!checkGroupStatus(groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_GROUP_DELETED);
		}

		List<SimpleUserBean> userFriendList = UserGroupDao.getInstance().getUserFriendNonGroupMemberList(siteUserId,
				groupId, pageNum, pageSize);
		ApiGroupNonMembersProto.ApiGroupNonMembersResponse.Builder responseBuilder = ApiGroupNonMembersProto.ApiGroupNonMembersResponse
				.newBuilder();
		for (SimpleUserBean friendBean : userFriendList) {
			UserProto.SimpleUserProfile friendProfile = UserProto.SimpleUserProfile.newBuilder()
					.setSiteUserId(friendBean.getUserId()).setUserName(String.valueOf(friendBean.getUserName()))
					.setUserPhoto(String.valueOf(friendBean.getUserPhoto())).build();
			responseBuilder.addProfile(friendProfile);
		}
		commandResponse.setParams(responseBuilder.build().toByteArray());
		errCode = ErrorCode2.SUCCESS;

	} catch (Exception e) {
		if (e instanceof ZalyException) {
			errCode = ((ZalyException) e).getErrCode();
		} else {
			errCode = ErrorCode2.ERROR_SYSTEMERROR;
		}
		LogUtils.requestErrorLog(logger, command, e);
	}
	return commandResponse.setErrCode(errCode);
}
 
Example 13
Source File: ApiGroupService.java    From openzaly with Apache License 2.0 4 votes vote down vote up
/**
 * 获取群成员 <br>
 * 无权限控制
 *
 * @param command
 * @return
 */
public CommandResponse members(Command command) {
	CommandResponse commandResponse = new CommandResponse().setAction(CommandConst.ACTION_RES);
	IErrorCode errCode = ErrorCode2.ERROR;
	try {
		ApiGroupMembersProto.ApiGroupMembersRequest request = ApiGroupMembersProto.ApiGroupMembersRequest
				.parseFrom(command.getParams());
		String siteUserId = command.getSiteUserId();
		String siteGroupId = request.getGroupId();
		int pageNum = 1;
		int pageSize = GroupConfig.GROUP_MAX_MEMBER_COUNT;
		LogUtils.requestDebugLog(logger, command, request.toString());

		if (StringUtils.isAnyEmpty(siteUserId, siteGroupId)) {
			throw new ZalyException(ErrorCode2.ERROR_PARAMETER);
		}

		if (!checkGroupStatus(siteGroupId)) {
			throw new ZalyException(ErrorCode2.ERROR_GROUP_DELETED);
		}

		List<GroupMemberBean> memberList = UserGroupDao.getInstance().getGroupMemberList(siteGroupId, pageNum,
				pageSize);
		ApiGroupMembersProto.ApiGroupMembersResponse.Builder responseBuilder = ApiGroupMembersProto.ApiGroupMembersResponse
				.newBuilder();
		for (GroupMemberBean member : memberList) {
			GroupProto.GroupMemberRole memberRole = GroupProto.GroupMemberRole.forNumber(member.getUserRole());
			UserProto.UserProfile memberProfile = UserProto.UserProfile.newBuilder()
					.setSiteUserId(member.getUserId()).setUserName(String.valueOf(member.getUserName()))
					.setUserPhoto(String.valueOf(member.getUserPhoto())).build();
			GroupProto.GroupMemberProfile groupMember = GroupProto.GroupMemberProfile.newBuilder()
					.setRole(memberRole).setProfile(memberProfile).build();
			responseBuilder.addList(groupMember);
		}
		commandResponse.setParams(responseBuilder.build().toByteArray());
		errCode = ErrorCode2.SUCCESS;

	} catch (Exception e) {
		if (e instanceof ZalyException) {
			errCode = ((ZalyException) e).getErrCode();
		} else {
			errCode = ErrorCode2.ERROR_SYSTEMERROR;
		}
		LogUtils.requestErrorLog(logger, command, e);
	}
	return commandResponse.setErrCode(errCode);
}
 
Example 14
Source File: AwsMediaConvertController.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Uploads a file to S3 and triggers a MediaConvert job
 *
 * @param request the request
 * @return the result of triggering the job
 * @throws IOException if there is any error reading the content of the file
 * @throws AwsException if there is any error uploading the file or triggering the job
 * @throws InvalidParametersException if there is any error parsing the request
 */
@PostMapping("/upload")
public ResultOne<MediaConvertResult> uploadVideo(HttpServletRequest request)
    throws IOException, AwsException, InvalidParametersException {
    if (ServletFileUpload.isMultipartContent(request)) {
        ResultOne<MediaConvertResult> result = new ResultOne<>();
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iterator = upload.getItemIterator(request);
            String siteId = null;
            String inputProfileId = null;
            String outputProfileId = null;
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                try (InputStream stream = item.openStream()) {
                    if (item.isFormField()) {
                        switch (name) {
                            case REQUEST_PARAM_SITEID:
                                siteId = Streams.asString(stream);
                                break;
                            case INPUT_PROFILE_PARAM:
                                inputProfileId = Streams.asString(stream);
                                break;
                            case OUTPUT_PROFILE_PARAM:
                                outputProfileId = Streams.asString(stream);
                                break;
                            default:
                                // Unknown parameter, just skip it...
                        }
                    } else {
                        if (StringUtils.isAnyEmpty(siteId, inputProfileId, outputProfileId)) {
                            throw new InvalidParametersException("Missing one or more required parameters: "
                                + "siteId, inputProfileId or outputProfileId");
                        }
                        String filename = item.getName();
                        if (StringUtils.isNotEmpty(filename)) {
                            filename = FilenameUtils.getName(filename);
                        }
                        result.setEntity(RESULT_KEY_ITEM,
                            mediaConvertService
                                .uploadVideo(siteId, inputProfileId, outputProfileId, filename, stream));
                        result.setResponse(ApiResponse.OK);
                    }
                }
            }
            return result;
        } catch (FileUploadException e) {
            throw new InvalidParametersException("The request body is invalid");
        }
    } else {
        throw new InvalidParametersException("The request is not multipart");
    }
}
 
Example 15
Source File: ApiRequestHandler.java    From wind-im with Apache License 2.0 4 votes vote down vote up
public CommandResponse handle(Command command) {
	try {
		ChannelSession channelSession = command.getChannelSession();
		if (channelSession == null || channelSession.getChannel() == null) {
			logger.error("{} client={} api request handler error.channelSession={}", AkxProject.PLN,
					command.getClientIp(), channelSession);
			// NULL,则不需要再次关闭channel
			return null;
		}

		switch (RequestAction.getAction(command.getAction())) {
		case API_SITE_CONFIG:
		case API_SITE_REGISTER:
		case API_SITE_LOGIN:
			break;
		default: {
			Map<Integer, String> header = command.getHeader();
			String sessionId = header.get(CoreProto.HeaderKey.CLIENT_SOCKET_SITE_SESSION_ID_VALUE);
			// logger.debug("{} client={} api request sessionId={}", AkxProject.PLN,
			// command.getClientIp(), sessionId);

			if (!StringUtils.isNotEmpty(sessionId)) {
				this.tellClientSessionError(channelSession.getChannel());
				logger.error("{} client={} api request with sessionId is NULL", AkxProject.PLN,
						command.getClientIp());
				return customResponse(ErrorCode2.ERROR_SESSION);
			}

			IUserSessionDao sessionDao = new UserSessionDaoService();
			SimpleAuthBean authBean = sessionDao.getUserSession(sessionId);
			// logger.debug("{} client={} api session auth result {}", authBean.toString());

			if (authBean == null || StringUtils.isAnyEmpty(authBean.getSiteUserId(), authBean.getDeviceId())) {
				this.tellClientSessionError(channelSession.getChannel());
				logger.error("{} client={} api session auth fail.authBean={}", AkxProject.PLN,
						command.getClientIp(), authBean);
				return customResponse(ErrorCode2.ERROR_SESSION);
			}

			command.setSiteUserId(authBean.getSiteUserId());
			command.setDeviceId(authBean.getDeviceId());
		}
		}
		// 执行业务操作
		return this.doApiRequest(channelSession.getChannel(), command);
	} catch (Exception e) {
		logger.error(StringHelper.format("{} client={} api request error.", AkxProject.PLN, command.getClientIp()),
				e);
	}

	return customResponse(ErrorCode2.ERROR);
}
 
Example 16
Source File: GroupDetectionHandler.java    From openzaly with Apache License 2.0 4 votes vote down vote up
public Boolean handle(Command command) {
	try {
		ImCtsMessageProto.ImCtsMessageRequest request = ImCtsMessageProto.ImCtsMessageRequest
				.parseFrom(command.getParams());
		int type = request.getType().getNumber();
		command.setMsgType(type);

		String siteUserId = command.getSiteUserId();
		String siteGroupId = null;
		String gmsgId = null;

		switch (type) {
		case CoreProto.MsgType.GROUP_TEXT_VALUE:
			if (command.isProxy()) {
				siteUserId = request.getGroupText().getSiteUserId();
			}
			gmsgId = request.getGroupText().getMsgId();
			siteGroupId = request.getGroupText().getSiteGroupId();
		case CoreProto.MsgType.GROUP_SECRET_TEXT_VALUE:
			break;
		case CoreProto.MsgType.GROUP_IMAGE_VALUE:
			if (command.isProxy()) {
				siteUserId = request.getGroupImage().getSiteUserId();
			}
			gmsgId = request.getGroupImage().getMsgId();
			siteGroupId = request.getGroupImage().getSiteGroupId();
			break;
		case CoreProto.MsgType.GROUP_SECRET_IMAGE_VALUE:
			break;
		case CoreProto.MsgType.GROUP_VOICE_VALUE:
			if (command.isProxy()) {
				siteUserId = request.getGroupVoice().getSiteUserId();
			}
			gmsgId = request.getGroupVoice().getMsgId();
			siteGroupId = request.getGroupVoice().getSiteGroupId();
			break;
		case CoreProto.MsgType.GROUP_SECRET_VOICE_VALUE:
			break;
		case CoreProto.MsgType.GROUP_NOTICE_VALUE:
			if (command.isProxy()) {
				siteUserId = request.getGroupMsgNotice().getSiteUserId();
			}
			siteGroupId = request.getGroupMsgNotice().getSiteGroupId();
			command.setSiteGroupId(siteGroupId);
			// 系统下发的消息,直接return true;
			return true;
		case CoreProto.MsgType.GROUP_WEB_VALUE:
			if (command.isProxy()) {
				siteUserId = request.getGroupWeb().getSiteUserId();
			}
			siteGroupId = request.getGroupWeb().getSiteGroupId();
			command.setProxySiteUserId(siteUserId);
			command.setSiteGroupId(siteGroupId);
			// 系统下发的消息,直接return true;
			return true;
		case CoreProto.MsgType.GROUP_WEB_NOTICE_VALUE:
			if (command.isProxy()) {
				siteUserId = request.getGroupWebNotice().getSiteUserId();
			}
			siteGroupId = request.getGroupWebNotice().getSiteGroupId();
			command.setProxySiteUserId(siteUserId);
			command.setSiteGroupId(siteGroupId);
			// 系统下发的消息,直接return true;
			return true;
		default:
			break;
		}

		command.setProxySiteUserId(siteUserId);
		// 群消息设置siteGroupId
		command.setSiteGroupId(siteGroupId);

		// check parameters
		if (StringUtils.isAnyEmpty(siteUserId, siteGroupId)) {
			return false;
		}

		// check is member of group
		if (check(siteUserId, siteGroupId)) {
			return true;
		} else {
			logger.warn("client={} siteUserId={} is not group={} member", command.getClientIp(), siteUserId,
					siteGroupId);
			int statusValue = -2;
			msgStatusResponse(command, gmsgId, System.currentTimeMillis(), statusValue);
		}

	} catch (Exception e) {
		LogUtils.requestErrorLog(logger, command, GroupDetectionHandler.class, e);
	}

	return false;
}
 
Example 17
Source File: ApiGroupService.java    From openzaly with Apache License 2.0 4 votes vote down vote up
/**
 * 获取用户群组中,不存在的好友用户
 *
 * @param command
 * @return
 */
public CommandResponse nonMembers(Command command) {
	CommandResponse commandResponse = new CommandResponse().setAction(CommandConst.ACTION_RES);
	IErrorCode errCode = ErrorCode2.ERROR;
	try {
		ApiGroupNonMembersProto.ApiGroupNonMembersRequest request = ApiGroupNonMembersProto.ApiGroupNonMembersRequest
				.parseFrom(command.getParams());
		String siteUserId = command.getSiteUserId();
		String groupId = request.getGroupId();
		int pageNum = request.getPageNumber();
		int pageSize = request.getPageSize();
		if (pageNum == 0 && pageSize == 0) {
			pageSize = 100;
		}
		LogUtils.requestDebugLog(logger, command, request.toString());

		if (StringUtils.isAnyEmpty(siteUserId, groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_PARAMETER);
		}

		if (!checkGroupStatus(groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_GROUP_DELETED);
		}

		List<SimpleUserBean> userFriendList = UserGroupDao.getInstance().getUserFriendNonGroupMemberList(siteUserId,
				groupId, pageNum, pageSize);
		ApiGroupNonMembersProto.ApiGroupNonMembersResponse.Builder responseBuilder = ApiGroupNonMembersProto.ApiGroupNonMembersResponse
				.newBuilder();
		for (SimpleUserBean friendBean : userFriendList) {
			UserProto.SimpleUserProfile friendProfile = UserProto.SimpleUserProfile.newBuilder()
					.setSiteUserId(friendBean.getUserId()).setUserName(String.valueOf(friendBean.getUserName()))
					.setUserPhoto(String.valueOf(friendBean.getUserPhoto())).build();
			responseBuilder.addProfile(friendProfile);
		}
		commandResponse.setParams(responseBuilder.build().toByteArray());
		errCode = ErrorCode2.SUCCESS;

	} catch (Exception e) {
		if (e instanceof ZalyException) {
			errCode = ((ZalyException) e).getErrCode();
		} else {
			errCode = ErrorCode2.ERROR_SYSTEMERROR;
		}
		LogUtils.requestErrorLog(logger, command, e);
	}
	return commandResponse.setErrCode(errCode);
}
 
Example 18
Source File: ApiGroupService.java    From openzaly with Apache License 2.0 4 votes vote down vote up
/**
 * 用户更新群资料<br>
 * 群主/管理员权限限制
 *
 * @param command
 * @return
 */
public CommandResponse updateProfile(Command command) {
	CommandResponse commandResponse = new CommandResponse().setAction(CommandConst.ACTION_RES);
	IErrorCode errCode = ErrorCode2.ERROR;
	try {
		ApiGroupUpdateProfileProto.ApiGroupUpdateProfileRequest request = ApiGroupUpdateProfileProto.ApiGroupUpdateProfileRequest
				.parseFrom(command.getParams());
		String siteUserId = command.getSiteUserId();
		String groupId = request.getProfile().getId();
		String photoId = request.getProfile().getIcon();
		String groupName = request.getProfile().getName();
		String groupNotice = request.getProfile().getGroupNotice();
		// 新的群群主
		String newGroupOwner = request.getNewGroupOwner();
		// 是否可以邀请群聊(除了群主以外的其他群成员)
		boolean closeInviteGroupChat = request.getCloseInviteGroupChat();
		LogUtils.requestDebugLog(logger, command, request.toString());

		if (StringUtils.isAnyEmpty(siteUserId, groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_PARAMETER);
		}

		if (!checkGroupStatus(groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_GROUP_DELETED);
		}

		// 判断是否具有权限,群主拥有权限
		String groupMasterId = UserGroupDao.getInstance().getGroupMaster(groupId);
		if (siteUserId.equals(groupMasterId)) {
			GroupProfileBean gprofileBean = new GroupProfileBean();
			gprofileBean.setGroupId(groupId);
			gprofileBean.setGroupName(groupName);
			gprofileBean.setGroupPhoto(photoId);
			gprofileBean.setGroupNotice(groupNotice);
			gprofileBean.setCreateUserId(newGroupOwner);
			gprofileBean.setCloseInviteGroupChat(closeInviteGroupChat);

			if (StringUtils.isNotEmpty(groupName)) {
				if (UserGroupDao.getInstance().updateGroupProfile(gprofileBean)) {
					errCode = ErrorCode2.SUCCESS;
				}
			} else {
				if (UserGroupDao.getInstance().updateGroupIGC(gprofileBean)) {
					errCode = ErrorCode2.SUCCESS;
				}
			}
		} else {
			errCode = ErrorCode2.ERROR_NOPERMISSION;
		}

	} catch (Exception e) {
		if (e instanceof ZalyException) {
			errCode = ((ZalyException) e).getErrCode();
		} else {
			errCode = ErrorCode2.ERROR_SYSTEMERROR;
		}
		LogUtils.requestErrorLog(logger, command, e);
	}
	return commandResponse.setErrCode(errCode);
}
 
Example 19
Source File: ApiGroupService.java    From openzaly with Apache License 2.0 4 votes vote down vote up
/**
 * 用户创建群,并添加初始群成员 <br>
 * 无权限限制
 *
 * @param command
 * @return
 */
public CommandResponse create(Command command) {
	CommandResponse commandResponse = new CommandResponse().setAction(CommandConst.ACTION_RES);
	IErrorCode errCode = ErrorCode2.ERROR;
	try {
		ApiGroupCreateProto.ApiGroupCreateRequest request = ApiGroupCreateProto.ApiGroupCreateRequest
				.parseFrom(command.getParams());
		String siteUserId = command.getSiteUserId();// group owner
		String groupName = request.getGroupName();
		ProtocolStringList groupMembers = request.getSiteUserIdsList();
		List<String> groupMemberIds = Lists.newArrayList(groupMembers);// copy a new list
		LogUtils.requestDebugLog(logger, command, request.toString());

		if (StringUtils.isAnyEmpty(siteUserId, groupName) || groupMemberIds == null) {
			throw new ZalyException(ErrorCode2.ERROR_PARAMETER);
		}

		if (!SiteConfig.allowCreateGroups(siteUserId)) {
			throw new ZalyException(ErrorCode2.ERROR2_GROUP_NOTALLOW);
		}
		// 检查用户是否被封禁,或者不存在
		for (String groupMemberId : groupMemberIds) {
			SimpleUserBean bean = UserProfileDao.getInstance().getSimpleProfileById(groupMemberId);
			if (bean == null || bean.getUserStatus() == 1) {
				groupMemberIds.remove(groupMemberId);
			}
		}

		if (!groupMemberIds.contains(siteUserId)) {
			groupMemberIds.add(siteUserId);
		}

		if (groupMemberIds.size() < 3) {
			throw new ZalyException(ErrorCode2.ERROR_GROUP_MEMBERLESS3);
		}

		GroupProfileBean groupBean = UserGroupDao.getInstance().createGroup(siteUserId, groupName, groupMemberIds);
		if (groupBean != null && StringUtils.isNotEmpty(groupBean.getGroupId())) {
			GroupProto.GroupProfile.Builder groupProfileBuilder = GroupProto.GroupProfile.newBuilder();
			groupProfileBuilder.setId(groupBean.getGroupId());
			if (StringUtils.isNotEmpty(groupBean.getGroupName())) {
				groupProfileBuilder.setName(groupBean.getGroupName());
			}
			if (StringUtils.isNotEmpty(groupBean.getGroupPhoto())) {
				groupProfileBuilder.setIcon(String.valueOf(groupBean.getGroupPhoto()));
			}

			ApiGroupCreateProto.ApiGroupCreateResponse response = ApiGroupCreateProto.ApiGroupCreateResponse
					.newBuilder().setProfile(groupProfileBuilder.build()).build();
			commandResponse.setParams(response.toByteArray());
			errCode = ErrorCode2.SUCCESS;
		} else {
			errCode = ErrorCode2.ERROR_GROUP_WHEN_CREATE;
		}

	} catch (Exception e) {
		if (e instanceof ZalyException) {
			errCode = ((ZalyException) e).getErrCode();
		} else {
			errCode = ErrorCode2.ERROR_SYSTEMERROR;
		}
		LogUtils.requestErrorLog(logger, command, e);
	}
	return commandResponse.setErrCode(errCode);
}
 
Example 20
Source File: ApiGroupService.java    From openzaly with Apache License 2.0 4 votes vote down vote up
/**
 * 获取群资料信息,一般由以下几部分组成 <br>
 * 1.群资料GroupProfile <br>
 * 2.群主基本资料GroupMaster,群主通过GroupProfile获取 <br>
 * 3.群成员人数以及排在最前列的四位用户 <br>
 * 4.无权限限制
 *
 * @param command
 * @return
 */
public CommandResponse profile(Command command) {
	CommandResponse commandResponse = new CommandResponse().setAction(CommandConst.ACTION_RES);
	IErrorCode errCode = ErrorCode2.ERROR;
	try {
		ApiGroupProfileProto.ApiGroupProfileRequest request = ApiGroupProfileProto.ApiGroupProfileRequest
				.parseFrom(command.getParams());
		String siteUserId = command.getSiteUserId();
		String groupId = request.getGroupId();
		int pageNum = 1;
		int pageSize = GroupConfig.GROUP_MIN_MEMBER_COUNT;
		LogUtils.requestDebugLog(logger, command, request.toString());

		if (StringUtils.isAnyEmpty(siteUserId, groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_PARAMETER);
		}

		if (!checkGroupStatus(groupId)) {
			throw new ZalyException(ErrorCode2.ERROR_GROUP_DELETED);
		}

		GroupProfileBean groupBean = UserGroupDao.getInstance().getGroupProfile(groupId);
		if (groupBean == null || StringUtils.isEmpty(groupBean.getGroupId())) {
			throw new ZalyException(ErrorCode2.ERROR_GROUP_QUERY_PROFILE);
		}

		SimpleUserBean ownerProfileBean = UserProfileDao.getInstance()
				.getSimpleProfileById(groupBean.getCreateUserId());
		logger.debug("get groupId={},groupOwner={}", groupId, ownerProfileBean.toString());

		int groupMembersCount = UserGroupDao.getInstance().getGroupMemberCount(groupId);
		logger.debug("get groupId={},groupMembers={}", groupId, groupMembersCount);

		List<GroupMemberBean> groupMemberList = UserGroupDao.getInstance().getGroupMemberList(groupId, pageNum,
				pageSize);

		UserProto.UserProfile ownerProfile = UserProto.UserProfile.newBuilder()
				.setSiteUserId(String.valueOf(ownerProfileBean.getUserId()))
				.setUserPhoto(String.valueOf(ownerProfileBean.getUserPhoto()))
				.setUserName(String.valueOf(ownerProfileBean.getUserName())).build();
		GroupProto.GroupProfile groupProfile = GroupProto.GroupProfile.newBuilder().setId(groupBean.getGroupId())
				.setName(String.valueOf(groupBean.getGroupName()))
				.setIcon(String.valueOf(groupBean.getGroupPhoto())).build();

		ApiGroupProfileProto.ApiGroupProfileResponse.Builder responseBuilder = ApiGroupProfileProto.ApiGroupProfileResponse
				.newBuilder();
		responseBuilder.setOwner(ownerProfile);
		responseBuilder.setProfile(groupProfile);
		responseBuilder.setGroupMemberCount(groupMembersCount);

		for (GroupMemberBean memberBean : groupMemberList) {
			UserProto.UserProfile memberProfile = UserProto.UserProfile.newBuilder()
					.setSiteUserId(String.valueOf(memberBean.getUserId()))
					.setUserPhoto(String.valueOf(memberBean.getUserPhoto()))
					.setUserName(String.valueOf(memberBean.getUserName())).build();
			GroupProto.GroupMemberProfile groupMemberProfile = GroupProto.GroupMemberProfile.newBuilder()
					.setProfile(memberProfile).build();
			responseBuilder.addGroupLastestMember(groupMemberProfile);
		}
		// 是否可以邀请群聊(除了群主以外)
		responseBuilder.setCloseInviteGroupChat(groupBean.isCloseInviteGroupChat());
		ApiGroupProfileProto.ApiGroupProfileResponse response = responseBuilder.build();

		commandResponse.setParams(response.toByteArray());
		errCode = ErrorCode2.SUCCESS;
	} catch (Exception e) {
		if (e instanceof ZalyException) {
			errCode = ((ZalyException) e).getErrCode();
		} else {
			errCode = ErrorCode2.ERROR_SYSTEMERROR;
		}
		LogUtils.requestErrorLog(logger, command, e);
	}
	return commandResponse.setErrCode(errCode);
}