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

The following are Jave code examples for showing how to use isEmpty() of the org.apache.commons.lang.ArrayUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: configx   File: ConfigContext.java   View Source Code Vote up 6 votes
/**
 * 判断指定版本的指定的bean是否需要刷新
 *
 * @param versionPropertySource
 * @param beanName
 * @param dependencyFactory
 * @return
 */
private boolean shouldRefresh(VersionPropertySource<?> versionPropertySource, String beanName,
                              RefreshBeanDependencyFactory dependencyFactory) {

    // 这个版本的属性未变化,不用刷新任何Bean
    if (versionPropertySource == null) {
        return false;
    }

    // 这个版本变化的属性名
    String[] changedPropertyNames = versionPropertySource.getPropertyNames();
    if (ArrayUtils.isEmpty(changedPropertyNames)) {
        return false;
    }

    String[] dependentPropertyNames = dependencyFactory.getDependentPropertyNames(beanName);

    for (String propertyName : changedPropertyNames) {
        for (String dependentPropertyName : dependentPropertyNames) {
            if (Pattern.matches(dependentPropertyName, propertyName)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 2
Project: patcher   File: ClassesExportAction.java   View Source Code Vote up 6 votes
private void getVirtualFile(String sourceName, VirtualFile virtualFile[], String compileRoot)
        throws Exception {
    if (!ArrayUtils.isEmpty(virtualFile)) {
        VirtualFile arr$[] = virtualFile;
        int len$ = arr$.length;
        for (int i$ = 0; i$ < len$; i$++) {
            VirtualFile vf = arr$[i$];
            String srcName;
            if (StringUtils.indexOf(vf.toString(), "$") != -1)
                srcName = StringUtils.substring(vf.toString(), StringUtils.lastIndexOf(vf.toString(), "/") + 1, StringUtils.indexOf(vf.toString(), "$"));
            else
                srcName = StringUtils.substring(vf.toString(), StringUtils.lastIndexOf(vf.toString(), "/") + 1, StringUtils.length(vf.toString()) - 6);
            String dstName = StringUtils.substring(sourceName, 0, StringUtils.length(sourceName) - 5);
            if (StringUtils.equals(srcName, dstName)) {
                String outRoot = (new StringBuilder()).append(StringUtils.substring(compileRoot, 0, StringUtils.lastIndexOf(compileRoot, "/"))).append("/out").toString();
                String packagePath = StringUtils.substring(vf.getPath(), StringUtils.length(compileRoot), StringUtils.length(vf.getPath()));
                File s = new File(vf.getPath());
                File t = new File((new StringBuilder()).append(outRoot).append(packagePath).toString());
                FileUtil.copy(s, t);
            }
            if (!ArrayUtils.isEmpty(virtualFile))
                getVirtualFile(sourceName, vf.getChildren(), compileRoot);
        }

    }
}
 
Example 3
Project: coddy   File: JWTService.java   View Source Code Vote up 6 votes
private JWTToken generateToken(Map<String, Object> claims, Date notBefore) {

        byte[] secret = DEFAULT_JWT_SECRET;

        if (!ArrayUtils.isEmpty(this.jwtSecret)) {
            secret = this.jwtSecret;
        }

        int sessionExpireMinutes = DEFAULT_JWT_SESSION_TIMEOUT_MINUTE;

        if (NumberUtils.isDigits(this.jwtTimeOut)) {
            sessionExpireMinutes = Integer.parseInt(this.jwtTimeOut);
        }

        LocalDateTime expiration = LocalDateTime.now().plusMinutes(sessionExpireMinutes);

        return new JWTToken(Jwts.builder()
                .setClaims(claims)
                .setNotBefore(notBefore)
                .setExpiration(Date.from(expiration.atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact());
    }
 
Example 4
Project: configx   File: DependencyConfigUtils.java   View Source Code Vote up 5 votes
public static void registerDependency(BeanDefinitionRegistry registry, String beanName, String[] propertyNames) {
    if (ArrayUtils.isEmpty(propertyNames)) {
        return;
    }
    String dependencyBeanName = beanName + ".dependency";
    BeanDefinitionBuilder meta = BeanDefinitionBuilder.genericBeanDefinition(RefreshBeanDependencyFactoryBean.class);
    meta.addPropertyValue("beanName", beanName);
    meta.addPropertyValue("propertyNames", propertyNames);
    registry.registerBeanDefinition(dependencyBeanName, meta.getBeanDefinition());
}
 
Example 5
Project: xm-ms-entity   File: TargetProceedingLep.java   View Source Code Vote up 5 votes
@Override
public Object proceed() throws Exception {
    Class<?>[] parameterTypes = getMethodSignature().getParameterTypes();
    if (!ArrayUtils.isEmpty(parameterTypes)) {
        throw new IllegalStateException("Call proceed without parameters on method '"
                                            + getMethodSignature().getName()
                                            + "' with arguments for LEP resource key:"
                                            + compositeResourceKey);
    }

    return invoke();
}
 
Example 6
Project: xm-ms-entity   File: TargetProceedingLep.java   View Source Code Vote up 5 votes
@Override
public Object proceed(Object[] args) throws Exception {
    Class<?>[] parameterTypes = getMethodSignature().getParameterTypes();
    if (ArrayUtils.isEmpty(parameterTypes)) {
        throw new IllegalStateException("Call proceed with parameters on method '"
                                            + getMethodSignature().getName()
                                            + "' without arguments for LEP resource key: "
                                            + compositeResourceKey);
    }

    return invoke(args);
}
 
Example 7
Project: osc-core   File: KeyStoreProvider.java   View Source Code Vote up 5 votes
/**
 * Gets the secret password stored in keystore under given alias.
 * @param alias
 * @param entryPassword entry password to access the secret password stored in keystore
 * @return the secret password or null if secret password does not exists in keystore
 * @throws KeyStoreProviderException
 */
public String getPassword(String alias, String entryPassword) throws KeyStoreProviderException {
    try {
        LOG.info(String.format("Getting password with alias %s from keystore ...", alias));

        SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_PASSWORD_ALGORITHM);

        Optional<KeyStore.SecretKeyEntry> ske = Optional.fromNullable((KeyStore.SecretKeyEntry) this.keystore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword.toCharArray())));

        if(!ske.isPresent()) {
            return null;
        }

        PBEKeySpec keySpec = (PBEKeySpec)factory.getKeySpec(ske.get().getSecretKey(),PBEKeySpec.class);
        char[] password = keySpec.getPassword();

        if(ArrayUtils.isEmpty(password)) {
            throw new KeyStoreProviderException("Recovered password is blank.");
        }

        return new String(password);
    } catch (NoSuchAlgorithmException nsae) {
        throw new KeyStoreProviderException("Algorithm used to create PBE secret cannot be found.", nsae);
    } catch (UnrecoverableEntryException uee) {
        throw new KeyStoreProviderException("Invalid entry password to recover secret.", uee);
    } catch (KeyStoreException kse) {
        throw new KeyStoreProviderException("Failed to get PBE secret to keystore.", kse);
    } catch (InvalidKeySpecException ikse) {
        throw new KeyStoreProviderException("Failed to get key spec from PBE secret.", ikse);
    } catch (Exception e) {
        throw new KeyStoreProviderException("Failed to get PBE secret.", e);
    }
}
 
Example 8
Project: kaltura-ce-sakai-extension   File: KalturaAPIService.java   View Source Code Vote up 5 votes
/**
 * removes a KalturaMetadata object for a Kaltura object id
 * 
 * @param metadatProfileName METADATA_PROFILE_NAME_ENTRY or METADATA_PROFILE_NAME_PLAYLIST 
 *          depending on the type of objects the ids are for, Defaults to Entry
 * @param objectId the id of the Kaltura object
 * @return true if deletion successful, false if not
 * @throws IllegalArgumentException if object id is invalid
 * @throws RuntimeException if error getting metadata
 */
private boolean deleteMetadataObjectsForKalturaObjectIds(String metadatProfileName, String... objectIds) {
    if (ArrayUtils.isEmpty(objectIds)) {
        throw new IllegalArgumentException("object ids must be set");
    }
    if (log.isDebugEnabled()) log.debug("deleteMetadataObjectForKalturaObjectId(objectIds="+StringUtils.join(objectIds, ",")+")");
    boolean deleted = false;
    KalturaClient kc = getKalturaClient(KS_PERM_ADMIN);
    KalturaMetadataService kms = new KalturaMetadataService(kc);
    KalturaMetadataFilter filter = new KalturaMetadataFilter();
    int metadataProfileId = entryMetadataProfile != null ? entryMetadataProfile.id : -1;
    if (METADATA_PROFILE_NAME_PLAYLIST.equals(metadatProfileName) || metadataProfileId < 0) {
        metadataProfileId = playlistMetadataProfile != null ? playlistMetadataProfile.id : -1;
    }
    if (metadataProfileId < 0) {
        log.warn("getMetadataObjectsForKalturaObjectIds Unable to filter metadata by the metadata profile ("+metadatProfileName+"), no ids can be found because the metadataProfile objects are null");
    } else {
        filter.metadataProfileIdEqual = metadataProfileId;
    }
    //filter.objectIdEqual = StringUtils.join(objectIds, ",");
    filter.objectIdIn = StringUtils.join(objectIds, ",");
    // NOTE: max of 500 so you may have to loop this
    if (objectIds.length > 500) {
        log.warn("Maximum metadata entries delete filter is 500 items, this filter is asking for "+objectIds.length+" items so only the first 500 will be returned");
    }
    KalturaFilterPager pager = new KalturaFilterPager();
    pager.pageSize = MAX_ENTRIES_PER_REQUEST; // max items returned is 30 without a pager
    try {
        ArrayList<KalturaMetadata> response = kms.list(filter, pager).objects;
        if (!response.isEmpty()) {
            for (KalturaMetadata r : response) {
                kms.delete(r.id);
            }
            deleted = true;
        }
    } catch (KalturaApiException e) {
        throw new RuntimeException("Error getting metadata object for kaltura objects (" + StringUtils.join(objectIds, ",") + ") :: " + e);
    }
    return deleted;
}
 
Example 9
Project: coddy   File: AdminCreationOnStartup.java   View Source Code Vote up 5 votes
private void createAdmin() {
    if (StringUtils.isEmpty(adminUsername) && ArrayUtils.isEmpty(adminPassword) && StringUtils.isEmpty(adminEmail)) {
        return;
    }

    LOGGER.info("create admin user if exists");
    if (!service.exists(adminUsername)) {
        List<String> permissions = new ArrayList<>();
        permissions.add(Permission.PERSO_ACCOUNT);
        permissions.add(Permission.PERSO_SNIPPET);
        permissions.add(Permission.ADMIN);
        service.create(new UpdateUser(adminUsername, adminPassword, adminEmail), permissions);
    }
}
 
Example 10
Project: FCat   File: ReqtoBeanUtil.java   View Source Code Vote up 4 votes
/**
* 自动匹配参数赋值到实体bean中
  */
 public static void toBean(Object bean, HttpServletRequest req){
     Class<?> clazz = bean.getClass();
     Method ms[] = clazz.getDeclaredMethods();
     String mname;
     String field;
     String fieldType;
     String value;
     for(Method m : ms){
         mname = m.getName();
         if(!mname.startsWith("set")
                 || ArrayUtils.isEmpty(m.getParameterTypes())){
             continue;
         }
         try{
             field = mname.toLowerCase().charAt(3) + mname.substring(4, mname.length());
             value = req.getParameter(field);
             if(LOG.isDebugEnabled()){
             	LOG.debug(field + " = " + value);
             }
             if(StringUtils.isEmpty(value)){
                 continue;
             }
             fieldType = m.getParameterTypes()[0].getName();
             //以下可以确认value为String类型
             if(String.class.getName().equals(fieldType)){
                 m.invoke(bean, (String)value);
             }else if((Byte.class.getName().equals(fieldType)||byte.class.getName().equals(fieldType)) && NumberUtils.isDigits((String)value)){
                 m.invoke(bean, Byte.valueOf((String)value));
             }else if((Integer.class.getName().equals(fieldType)||int.class.getName().equals(fieldType)) && NumberUtils.isDigits((String)value)){
                 m.invoke(bean, Integer.valueOf((String)value));
             }else if((Short.class.getName().equals(fieldType)||short.class.getName().equals(fieldType)) && NumberUtils.isDigits((String)value)){
                 m.invoke(bean, Short.valueOf((String)value));
             }else if((Long.class.getName().equals(fieldType)||long.class.getName().equals(fieldType)) && NumberUtils.isDigits((String)value)){
                 m.invoke(bean, Long.valueOf((String)value));
             }else if((Float.class.getName().equals(fieldType)||float.class.getName().equals(fieldType)) && NumberUtils.isNumber((String)value)){
                 m.invoke(bean, Float.valueOf((String)value));
             }else if((Double.class.getName().equals(fieldType)||double.class.getName().equals(fieldType)) && NumberUtils.isNumber((String)value)){
                 m.invoke(bean, Double.valueOf((String)value));
             }else if(BigDecimal.class.getName().equals(fieldType) && NumberUtils.isNumber((String)value)){
                 m.invoke(bean, new BigDecimal(value));
             }else if(Date.class.getName().equals(fieldType)){
             	String attach0 = "";
             	value = value.replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "");
             	for(int i =0; i < (17 - value.length()); i++) {
             		attach0 += "0";
             	}
                 m.invoke(bean, DateUtil.toDate(value + attach0));
             }else{
                 m.invoke(bean, value);
             }
         }catch(Exception e){
             e.printStackTrace();
             continue;
         }
     }
 }
 
Example 11
Project: marathon-auth-plugin   File: HTTPAuthFilter.java   View Source Code Vote up 4 votes
public byte[] filterGroups(HttpServletRequest request, byte[] content) {
	byte[] newContent = content;
	if (ArrayUtils.isEmpty(newContent)) {
		return newContent;
	}
	try {
		String method = request.getMethod();
		String uri = request.getRequestURI();
		String queryString = request.getQueryString();
		String path = uri + "?" + queryString;
		String url = AuthUtil.QUERY_GROUP_URI;
		if (AuthUtil.HTTP_GET.equalsIgnoreCase(method) && path.equalsIgnoreCase(url)) {
			String umContent = MessageGZIP.uncompressToString(newContent);
			

			User user = AuthUtil.THREAD_LOCAL_USER.get();
			if (user == null) {
				log.warn("AuthUtil.THREAD_LOCAL_USER.get()");
				return null;
			}

			JsonObject jsonObject = new JsonParser().parse(umContent)
					.getAsJsonObject();

			// 新的jsonArrayGroups
			JsonArray newJsonArrayGroups = new JsonArray();

			JsonArray jsonArrayGroups = jsonObject.getAsJsonArray("groups");
			
			log.info("jsonArrayGroups.size >>>>>{}", jsonArrayGroups.size());

			if (!jsonArrayGroups.isJsonNull()) {
				for (JsonElement jsonElement : jsonArrayGroups) {
					JsonObject jsonObjectGroup = jsonElement
							.getAsJsonObject();
					String id = jsonObjectGroup.get("id").getAsString();
					Permission permission = AuthUtil
							.getQueryPermission(user);
					log.info(" path >>>>>>  {} permission >>>> {}", id,permission);
					if (permission != null) {
						String queryPath = permission.getOn();
						// 判断分组查询权限
						if ("/".equals(queryPath) || queryPath.contains(id)) {
							newJsonArrayGroups.add(jsonElement);
						}
					}
				}
			}

			jsonObject.remove("groups");
			jsonObject.add("groups", newJsonArrayGroups);

			String newContentStr = jsonObject.toString();

			newContent = MessageGZIP.compressToByte(newContentStr);

			log.info("newJsonArrayGroups.size >>>>>{}", newJsonArrayGroups.size());

		}
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	}

	return newContent;
}