Java Code Examples for org.apache.commons.lang.ArrayUtils#isNotEmpty()

The following examples show how to use org.apache.commons.lang.ArrayUtils#isNotEmpty() . 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: FullTextMapperV2.java    From atlas with Apache License 2.0 6 votes vote down vote up
private Set<String> getExcludeAttributesForIndexText(String typeName) {
    final Set<String> ret;

    if (excludeAttributesCache.containsKey(typeName)) {
        ret = excludeAttributesCache.get(typeName);

    } else if (configuration != null) {
        String[] excludeAttributes = configuration.getStringArray(FULL_TEXT_EXCLUDE_ATTRIBUTE_PROPERTY + "." +
                                                                          typeName + "." + "attributes.exclude");

        if (ArrayUtils.isNotEmpty(excludeAttributes)) {
            ret = new HashSet<>(Arrays.asList(excludeAttributes));
        } else {
            ret = Collections.emptySet();
        }

        excludeAttributesCache.put(typeName, ret);
    } else {
        ret = Collections.emptySet();
    }

    return ret;
}
 
Example 2
Source File: IdentityApplicationManagementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Generate CertData array
 *
 * @param certificateInfo array of certificate info
 * @return CertData array
 * @throws CertificateException
 */
public static List<CertData> getCertDataArray(CertificateInfo[] certificateInfo) throws CertificateException {

    if (ArrayUtils.isNotEmpty(certificateInfo)) {
        List<CertData> certDataList = new ArrayList<>();
        HashMap<CertData, String> certDataMap = new HashMap<>();
        int i = 0;
        for (CertificateInfo certificateInfoVal : certificateInfo) {
            String certVal = certificateInfoVal.getCertValue();
            CertData certData = createCertData(certVal);
            certDataList.add(certData);
            certDataMap.put(certData, certVal);
            i++;
        }
        setCertDataMap(certDataMap);
        return certDataList;
    } else {
        String errorMsg = "Certificate info array is empty";
        if (log.isDebugEnabled()) {
            log.debug(errorMsg);
        }
        throw new IllegalArgumentException(errorMsg);
    }
}
 
Example 3
Source File: CourseController.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
 * 批量删除
 *
 * @param ids ids
 * @return ResponseBean
 * @author tangyi
 * @date 2018/12/4 11:26
 */
@PostMapping("deleteAll")
@AdminTenantTeacherAuthorization
@ApiOperation(value = "批量删除课程", notes = "根据课程id批量删除课程")
@ApiImplicitParam(name = "ids", value = "课程ID", dataType = "Long")
@Log("批量删除课程")
public ResponseBean<Boolean> deleteAllCourses(@RequestBody Long[] ids) {
    boolean success = false;
    try {
        if (ArrayUtils.isNotEmpty(ids))
            success = courseService.deleteAll(ids) > 0;
    } catch (Exception e) {
        log.error("Delete course failed", e);
    }
    return new ResponseBean<>(success);
}
 
Example 4
Source File: ServerIdentityGovernanceService.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
private String buildErrorDescription(GovernanceConstants.ErrorMessage errorEnum, String... data) {

        String errorDescription;

        if (ArrayUtils.isNotEmpty(data)) {
            if (data.length == 1) {
                errorDescription = String.format(errorEnum.getDescription(), (Object) data);
            } else {
                errorDescription = String.format(errorEnum.getDescription(), (Object[]) data);
            }
        } else {
            errorDescription = errorEnum.getDescription();
        }

        return errorDescription;
    }
 
Example 5
Source File: DefaultCallbackHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    if (ArrayUtils.isNotEmpty(callbacks)) {
        OAuthCallback oauthCallback = (OAuthCallback) callbacks[0];
        // TODO : This needs to be implemented in XACML.
        // TODO : For the moment, let's approve everything.
        if (OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_AUTHZ.equals(
                oauthCallback.getCallbackType())) {
            oauthCallback.setAuthorized(true);
        }
        if (OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_TOKEN.equals(
                oauthCallback.getCallbackType())) {
            oauthCallback.setAuthorized(true);
        }
        if (OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_AUTHZ.equals(
                oauthCallback.getCallbackType())) {
            oauthCallback.setApprovedScope(oauthCallback.getRequestedScope());
            oauthCallback.setValidScope(true);
        }
        if (OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_TOKEN.equals(
                oauthCallback.getCallbackType())) {
            oauthCallback.setApprovedScope(oauthCallback.getRequestedScope());
            oauthCallback.setValidScope(true);
        }
    }
}
 
Example 6
Source File: EntityMeta.java    From ymate-platform-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * 处理@Indexes和@Index注解
 *
 * @param targetClass 目标类型
 * @param targetMeta  实体元数据
 */
private static void __doParseIndexes(Class<? extends IEntity> targetClass, EntityMeta targetMeta) {
    List<Index> _indexes = new ArrayList<Index>();
    if (ClassUtils.isAnnotationOf(targetClass, Indexes.class)) {
        _indexes.addAll(Arrays.asList(targetClass.getAnnotation(Indexes.class).value()));
    }
    if (ClassUtils.isAnnotationOf(targetClass, Index.class)) {
        _indexes.add(targetClass.getAnnotation(Index.class));
    }
    for (Index _index : _indexes) {
        // 索引名称和索引字段缺一不可
        if (StringUtils.isNotBlank(_index.name()) && ArrayUtils.isNotEmpty(_index.fields())) {
            // 索引名称不允许重复
            if (!targetMeta.containsIndex(_index.name())) {
                // 每个字段名称都必须是有效的
                for (String _field : _index.fields()) {
                    if (!targetMeta.containsProperty(_field)) {
                        throw new IllegalArgumentException("Invalid index field '" + _field + "'");
                    }
                }
                targetMeta.__indexes.put(_index.name(), new IndexMeta(_index.name(), _index.unique(), Arrays.asList(_index.fields())));
            }
        }
    }
}
 
Example 7
Source File: EntitlementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static void addSamplePolicies(Registry registry) {

        File policyFolder = new File(CarbonUtils.getCarbonHome() + File.separator
                + "repository" + File.separator + "resources" + File.separator
                + "identity" + File.separator + "policies" + File.separator + "xacml"
                + File.separator + "default");

        File[] fileList;
        if (policyFolder.exists() && ArrayUtils.isNotEmpty(fileList = policyFolder.listFiles())) {
            for (File policyFile : fileList) {
                if (policyFile.isFile()) {
                    PolicyDTO policyDTO = new PolicyDTO();
                    try {
                        policyDTO.setPolicy(FileUtils.readFileToString(policyFile));
                        EntitlementUtil.addFilesystemPolicy(policyDTO, registry, false);
                    } catch (Exception e) {
                        // log and ignore
                        log.error("Error while adding sample XACML policies", e);
                    }
                }
            }
        }
    }
 
Example 8
Source File: InboundAuthConfigToApiModel.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
@Override
public List<InboundProtocolListItem> apply(ServiceProvider application) {

    String applicationId = application.getApplicationResourceId();
    InboundAuthenticationConfig inboundAuthConfig = application.getInboundAuthenticationConfig();

    if (inboundAuthConfig != null) {
        if (ArrayUtils.isNotEmpty(inboundAuthConfig.getInboundAuthenticationRequestConfigs())) {

            List<InboundProtocolListItem> inboundProtocolListItems = new ArrayList<>();
            Arrays.stream(inboundAuthConfig.getInboundAuthenticationRequestConfigs()).forEach(
                    inbound -> inboundProtocolListItems.add(buildInboundProtocolListItem(applicationId, inbound)));

            return inboundProtocolListItems;
        }
    }

    return Collections.emptyList();
}
 
Example 9
Source File: ServerIdpManagementService.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
/**
 * Get meta information about a specific federated authenticator supported by the IDPs.
 *
 * @param id Federated authenticator ID.
 * @return MetaFederatedAuthenticator.
 */
public MetaFederatedAuthenticator getMetaFederatedAuthenticator(String id) {

    String authenticatorName = base64URLDecode(id);
    MetaFederatedAuthenticator authenticator = null;
    try {
        FederatedAuthenticatorConfig[] authenticatorConfigs =
                IdentityProviderServiceHolder.getIdentityProviderManager()
                        .getAllFederatedAuthenticators();
        if (ArrayUtils.isNotEmpty(authenticatorConfigs)) {
            for (FederatedAuthenticatorConfig authenticatorConfig : authenticatorConfigs) {
                if (StringUtils.equals(authenticatorConfig.getName(), authenticatorName)) {
                    authenticator = createMetaFederatedAuthenticator(authenticatorConfig);
                    break;
                }
            }
        }
        return authenticator;
    } catch (IdentityProviderManagementException e) {
        throw handleIdPException(e, Constants.ErrorMessage.ERROR_CODE_ERROR_RETRIEVING_META_AUTHENTICATOR, id);
    }
}
 
Example 10
Source File: UserManagementAuditLogger.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPostUpdatePermissionsOfRole(String roleName, Permission[] permissions, UserStoreManager
        userStoreManager) {

    if (isEnable()) {
        JSONObject dataObject = new JSONObject();
        if (ArrayUtils.isNotEmpty(permissions)) {
            JSONArray permissionsArray = new JSONArray(permissions);
            dataObject.put(ListenerUtils.PERMISSIONS_FIELD, permissionsArray);
        }

        audit.warn(createAuditMessage(ListenerUtils.UPDATE_PERMISSIONS_OF_ROLE_ACTION,
                ListenerUtils.getEntityWithUserStoreDomain(roleName, userStoreManager), dataObject, SUCCESS));
    }
    return true;
}
 
Example 11
Source File: UserController.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
  * 导出
  *
  * @param ids ids
  * @author tangyi
  * @date 2018/11/26 22:11
  */
 @PostMapping("export")
 @AdminTenantTeacherAuthorization
 @ApiOperation(value = "导出用户", notes = "根据用户id导出用户")
 @ApiImplicitParam(name = "userVo", value = "用户信息", required = true, dataType = "UserVo")
 @Log("导出用户")
 public void exportUser(@RequestBody Long[] ids, HttpServletRequest request, HttpServletResponse response) {
     try {
         List<User> users;
         if (ArrayUtils.isNotEmpty(ids)) {
             users = userService.findListById(ids);
         } else {
             // 导出本租户下的全部用户
             User user = new User();
             user.setTenantCode(SysUtil.getTenantCode());
             users = userService.findList(user);
         }
         if (CollectionUtils.isEmpty(users))
             throw new CommonException("无用户数据.");
         // 查询用户授权信息
         List<UserAuths> userAuths = userAuthsService.getListByUsers(users);
         // 组装数据,转成dto
         List<UserInfoDto> userInfoDtos = users.stream().map(tempUser -> {
             UserInfoDto userDto = new UserInfoDto();
             userAuths.stream()
                     .filter(userAuth -> userAuth.getUserId().equals(tempUser.getId()))
                     .findFirst()
                     .ifPresent(userAuth -> UserUtils.toUserInfoDto(userDto, tempUser, userAuth));
             return userDto;
         }).collect(Collectors.toList());
String fileName = "用户信息" + DateUtils.localDateMillisToString(LocalDateTime.now());
ExcelToolUtil.writeExcel(request, response, UserUtils.convertToExcelModel(userInfoDtos), fileName,"sheet1", UserExcelModel.class);
     } catch (Exception e) {
         log.error("Export user data failed", e);
         throw new CommonException("Export user data failed");
     }
 }
 
Example 12
Source File: CarreraProducerBase.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private DelayMessage buildDelayMessage4Cancel(String topic, String uniqDelayMsgId, String... tags) {
    DelayMessage delayMessage = new DelayMessage();
    delayMessage.setTopic(topic);
    delayMessage.setUniqDelayMsgId(uniqDelayMsgId);
    delayMessage.setAction(DELAY_ACTIONS_CANCEL);
    delayMessage.setVersion(VersionUtils.getVersion());
    delayMessage.setBody("c".getBytes()); // if body is null, new String(message.getBody()) will throw NullPointerException

    if (ArrayUtils.isNotEmpty(tags)) {
        delayMessage.setTags(StringUtils.join(tags, TAGS_SEPARATOR));
    }

    return delayMessage;
}
 
Example 13
Source File: LogController.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 批量删除
 *
 * @param ids ids
 * @return ResponseBean
 * @author tangyi
 * @date 2018/12/4 10:12
 */
@PostMapping("deleteAll")
@AdminAuthorization
@ApiOperation(value = "批量删除日志", notes = "根据日志ids批量删除日志")
@ApiImplicitParam(name = "ids", value = "日志ID", dataType = "Long")
public ResponseBean<Boolean> deleteAllLog(@RequestBody Long[] ids) {
    boolean success = false;
    try {
        if (ArrayUtils.isNotEmpty(ids))
            success = logService.deleteAll(ids) > 0;
    } catch (Exception e) {
        log.error("Delete attachment failed", e);
    }
    return new ResponseBean<>(success);
}
 
Example 14
Source File: IdPManagementDAO.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * To get the combined list of identity properties with IDP meta data properties as well as Just in time configs.
 *
 * @param justInTimeProvisioningConfig JustInTimeProvisioningConfig.
 * @param idpProperties                IDP Properties.
 * @return combined list of identity properties.
 */
private List<IdentityProviderProperty> getCombinedProperties(JustInTimeProvisioningConfig
                                                                     justInTimeProvisioningConfig,
                                                             IdentityProviderProperty[] idpProperties) {

    List<IdentityProviderProperty> identityProviderProperties = new ArrayList<>();
    if (ArrayUtils.isNotEmpty(idpProperties)) {
        identityProviderProperties = new ArrayList<>(Arrays.asList(idpProperties));
    }
    IdentityProviderProperty passwordProvisioningProperty = new IdentityProviderProperty();
    passwordProvisioningProperty.setName(IdPManagementConstants.PASSWORD_PROVISIONING_ENABLED);
    passwordProvisioningProperty.setValue("false");

    IdentityProviderProperty modifyUserNameProperty = new IdentityProviderProperty();
    modifyUserNameProperty.setName(IdPManagementConstants.MODIFY_USERNAME_ENABLED);
    modifyUserNameProperty.setValue("false");

    IdentityProviderProperty promptConsentProperty = new IdentityProviderProperty();
    promptConsentProperty.setName(IdPManagementConstants.PROMPT_CONSENT_ENABLED);
    promptConsentProperty.setValue("false");

    if (justInTimeProvisioningConfig != null && justInTimeProvisioningConfig.isProvisioningEnabled()) {
        passwordProvisioningProperty
                .setValue(String.valueOf(justInTimeProvisioningConfig.isPasswordProvisioningEnabled()));
        modifyUserNameProperty.setValue(String.valueOf(justInTimeProvisioningConfig.isModifyUserNameAllowed()));
        promptConsentProperty.setValue(String.valueOf(justInTimeProvisioningConfig.isPromptConsent()));
    }
    identityProviderProperties.add(passwordProvisioningProperty);
    identityProviderProperties.add(modifyUserNameProperty);
    identityProviderProperties.add(promptConsentProperty);
    return identityProviderProperties;
}
 
Example 15
Source File: ApplicationMgtValidator.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @param inboundAuthenticationConfig Inbound authentication configuration.
 * @param tenantDomain                Tenant domain of application.
 * @param appId                       Application ID.
 * @throws IdentityApplicationManagementException IdentityApplicationManagementException.
 */
private void validateInboundAuthenticationConfig(InboundAuthenticationConfig inboundAuthenticationConfig, String
        tenantDomain, int appId) throws IdentityApplicationManagementException {

    if (inboundAuthenticationConfig == null) {
        return;
    }
    InboundAuthenticationRequestConfig[] inboundAuthRequestConfigs = inboundAuthenticationConfig
            .getInboundAuthenticationRequestConfigs();
    if (ArrayUtils.isNotEmpty(inboundAuthRequestConfigs)) {
        for (InboundAuthenticationRequestConfig inboundAuthRequestConfig : inboundAuthRequestConfigs) {
            validateInboundAuthKey(inboundAuthRequestConfig, appId, tenantDomain);
        }
    }
}
 
Example 16
Source File: ByteBufferSupport.java    From incubator-myriad with Apache License 2.0 5 votes vote down vote up
public static void putBytes(ByteBuffer bb, byte bytes[]) {
  if (ArrayUtils.isNotEmpty(bytes)) {
    bb.putInt(bytes.length);
    bb.put(bytes);
  } else {
    bb.putInt(0);
  }
}
 
Example 17
Source File: TaildirMatcher.java    From ns4_gear_watchdog with Apache License 2.0 5 votes vote down vote up
/**
 * Package accessible constructor. From configuration context it represents a single
 * <code>filegroup</code> and encapsulates the corresponding <code>filePattern</code>.
 * <code>filePattern</code> consists of two parts: first part has to be a valid path to an
 * existing parent directory, second part has to be a valid regex
 * {@link java.util.regex.Pattern} that match any non-hidden file names within parent directory
 * . A valid example for filePattern is <code>/dir0/dir1/.*</code> given
 * <code>/dir0/dir1</code> is an existing directory structure readable by the running user.
 * <p></p>
 * An instance of this class is created for each fileGroup
 *
 * @param fileGroup            arbitrary name of the group given by the config
 * @param filePattern          parent directory plus regex pattern. No wildcards are allowed in directory
 *                             name
 * @param cachePatternMatching default true, recommended in every setup especially with huge
 *                             parent directories. Don't set when local system clock is not used
 *                             for stamping mtime (eg: remote filesystems)
 * @see TaildirSourceConfigurationConstants
 */
TaildirMatcher(String fileGroup, String filePattern, final String[] exclusivePattern, final long fileExpiredTime, boolean cachePatternMatching) {
    // store whatever came from configuration
    this.fileGroup = fileGroup;
    this.filePattern = filePattern;
    this.cachePatternMatching = cachePatternMatching;

    // calculate final members
    File f = new File(filePattern);
    this.parentDir = f.getParentFile();
    String regex = f.getName();
    final PathMatcher matcher = FS.getPathMatcher("regex:" + regex);
    this.fileFilter = new DirectoryStream.Filter<Path>() {
        @Override
        public boolean accept(Path entry) throws IOException {
            if (!matcher.matches(entry.getFileName()) || Files.isDirectory(entry) || ((System.currentTimeMillis() - entry.toFile().lastModified()) > fileExpiredTime)) {
                return false;
            }

            if (ArrayUtils.isNotEmpty(exclusivePattern)) {
                for (String exclusiveFile : exclusivePattern) {
                    if (entry.getFileName().endsWith(exclusiveFile)) {
                        return false;
                    }
                }
            }

            return true;
        }
    };

    // sanity check
    Preconditions.checkState(parentDir.exists(),
            "Directory does not exist: " + parentDir.getAbsolutePath());
}
 
Example 18
Source File: SAMLAttribute.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
/** @deprecated */
@Deprecated
public String getValue() {
   return ArrayUtils.isNotEmpty(this.value) ? this.value[0] : null;
}
 
Example 19
Source File: SAMLAttribute.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
/** @deprecated */
@Deprecated
public String getValue() {
   return ArrayUtils.isNotEmpty(this.value) ? this.value[0] : null;
}
 
Example 20
Source File: FreemarkerConfigBuilder.java    From ymate-platform-v2 with Apache License 2.0 4 votes vote down vote up
public FreemarkerConfigBuilder addTemplateFileDir(File... fileBaseDirs) {
    if (ArrayUtils.isNotEmpty(fileBaseDirs)) {
        this.templateFiles.addAll(Arrays.asList(fileBaseDirs));
    }
    return this;
}