Example usage for org.apache.commons.lang ArrayUtils isEmpty

List of usage examples for org.apache.commons.lang ArrayUtils isEmpty

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils isEmpty.

Prototype

public static boolean isEmpty(boolean[] array) 

Source Link

Document

Checks if an array of primitive booleans is empty or null.

Usage

From source file:org.apache.directory.studio.ldapbrowser.core.utils.CompoundModification.java

/**
 * Rename the values by removing the old attribute from the entry and adding 
 * a new attribute to the entry. Only one event (an {@link ValueRenamedEvent}) is fired.
 * //from  ww  w  .  j  av a  2s.  co  m
 * @param oldValues the old values
 * @param newAttributeDescription the new attribute description
 */
public void renameValues(IValue[] oldValues, String newAttributeDescription) {
    if (ArrayUtils.isEmpty(oldValues)) {
        throw new IllegalArgumentException("Expected non-null and non-empty values array."); //$NON-NLS-1$
    }
    if (StringUtils.isEmpty(newAttributeDescription)) {
        throw new IllegalArgumentException("Expected non-null and non-empty attribute description."); //$NON-NLS-1$
    }

    if (newAttributeDescription != null && !"".equals(newAttributeDescription) //$NON-NLS-1$
            && !newAttributeDescription.equals(oldValues[0].getAttribute().getDescription())) {
        ValueRenamedEvent event = null;
        try {
            EventRegistry.suspendEventFiringInCurrentThread();
            for (IValue oldValue : oldValues) {
                if (!newAttributeDescription.equals(oldValue.getAttribute().getDescription())) {
                    IAttribute oldAttribute = oldValue.getAttribute();
                    IEntry entry = oldAttribute.getEntry();
                    IValue newValue = null;

                    // delete old value
                    oldAttribute.deleteValue(oldValue);
                    if (oldAttribute.getValueSize() == 0) {
                        entry.deleteAttribute(oldAttribute);
                    }

                    // add new value
                    IAttribute attribute = entry.getAttribute(newAttributeDescription);
                    if (attribute == null) {
                        attribute = new Attribute(entry, newAttributeDescription);
                        entry.addAttribute(attribute);
                    }
                    newValue = new Value(attribute, oldValue.getRawValue());
                    attribute.addValue(newValue);

                    // prepare event
                    if (event == null) {
                        event = new ValueRenamedEvent(entry.getBrowserConnection(), entry, oldValue, newValue);
                    }
                }
            }
        } finally {
            EventRegistry.resumeEventFiringInCurrentThread();
        }

        // fire events
        EventRegistry.fireEntryUpdated(event, this);
    }
}

From source file:org.apache.directory.studio.ldapbrowser.core.utils.CompoundModification.java

/**
 * Creates the attribute with the given value in the entry.
 * Only one event (an {@link ValueAddedEvent}) is fired.
 * //from  w w  w . j  av  a 2s  .c o m
 * @param entry the entry
 * @param values the values
 * 
 * @throws ModelModificationException the model modification exception
 */
public void createValues(IEntry entry, IValue... values) {
    if (entry == null) {
        throw new IllegalArgumentException("Expected non-null entry."); //$NON-NLS-1$
    }
    if (ArrayUtils.isEmpty(values)) {
        throw new IllegalArgumentException("Expected non-null and non-empty values array."); //$NON-NLS-1$
    }

    ValueAddedEvent event = null;
    EventRegistry.suspendEventFiringInCurrentThread();
    for (IValue value : values) {
        String attributeDescription = value.getAttribute().getDescription();
        IAttribute attribute = entry.getAttribute(attributeDescription);
        if (attribute == null) {
            attribute = new Attribute(entry, attributeDescription);
            entry.addAttribute(attribute);
        }
        Value newValue = new Value(attribute, value.getRawValue());
        attribute.addValue(newValue);
        if (event == null) {
            event = new ValueAddedEvent(entry.getBrowserConnection(), entry, attribute, newValue);
        }
    }
    EventRegistry.resumeEventFiringInCurrentThread();

    // fire event
    EventRegistry.fireEntryUpdated(event, this);
}

From source file:org.apache.falcon.regression.core.util.MathUtil.java

public static Object[][] append(Object[][] arr1, Object[][] arr2) {
    Assert.assertFalse(ArrayUtils.isEmpty(arr1), "arr1 can't be empty:" + Arrays.deepToString(arr1));
    Assert.assertFalse(ArrayUtils.isEmpty(arr2), "arr2 can't be empty:" + Arrays.deepToString(arr2));
    Assert.assertEquals(arr1[0].length, arr2[0].length,
            "Array rows are not compatible. " + "row of first array: " + Arrays.deepToString(arr1[0])
                    + "row of second array: " + Arrays.deepToString(arr2[0]));
    return (Object[][]) ArrayUtils.addAll(arr1, arr2);
}

From source file:org.apache.flink.api.java.ScalaShellRemoteEnvironment.java

/**
 * compiles jars from files in the shell virtual directory on the fly, sends and executes it in the remote environment
 *
 * @param jobName name of the job as string
 * @return Result of the computation//  w w  w .  j  a va  2 s. c  om
 * @throws Exception
 */
@Override
public JobExecutionResult execute(String jobName) throws Exception {
    Plan p = createProgramPlan(jobName);

    String jarFile = flinkILoop.writeFilesToDisk().getAbsolutePath();

    // get "external jars, and add the shell command jar, pass to executor
    List<String> alljars = new ArrayList<String>();
    // get external (library) jars
    String[] extJars = this.flinkILoop.getExternalJars();

    if (!ArrayUtils.isEmpty(extJars)) {
        alljars.addAll(Arrays.asList(extJars));
    }
    // add shell commands
    alljars.add(jarFile);
    String[] alljarsArr = new String[alljars.size()];
    alljarsArr = alljars.toArray(alljarsArr);
    PlanExecutor executor = PlanExecutor.createRemoteExecutor(host, port, new Configuration(), alljarsArr);

    executor.setPrintStatusDuringExecution(p.getExecutionConfig().isSysoutLoggingEnabled());
    return executor.executePlan(p);
}

From source file:org.apache.geode.management.internal.cli.commands.DestroyIndexCommand.java

@CliCommand(value = CliStrings.DESTROY_INDEX, help = CliStrings.DESTROY_INDEX__HELP)
@CliMetaData(relatedTopic = { CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA })
@ResourceOperation(resource = ResourcePermission.Resource.CLUSTER, operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
public Result destroyIndex(
        @CliOption(key = CliStrings.DESTROY_INDEX__NAME, unspecifiedDefaultValue = "", help = CliStrings.DESTROY_INDEX__NAME__HELP) final String indexName,

        @CliOption(key = CliStrings.DESTROY_INDEX__REGION, optionContext = ConverterHint.REGION_PATH, help = CliStrings.DESTROY_INDEX__REGION__HELP) final String regionPath,

        @CliOption(key = { CliStrings.MEMBER,
                CliStrings.MEMBERS }, optionContext = ConverterHint.MEMBERIDNAME, help = CliStrings.DESTROY_INDEX__MEMBER__HELP) final String[] memberNameOrID,

        @CliOption(key = { CliStrings.GROUP,
                CliStrings.GROUPS }, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.DESTROY_INDEX__GROUP__HELP) final String[] group) {

    Result result;//from ww  w .  ja va  2s  .  co m

    if (StringUtils.isBlank(indexName) && StringUtils.isBlank(regionPath) && ArrayUtils.isEmpty(group)
            && ArrayUtils.isEmpty(memberNameOrID)) {
        return ResultBuilder.createUserErrorResult(
                CliStrings.format(CliStrings.PROVIDE_ATLEAST_ONE_OPTION, CliStrings.DESTROY_INDEX));
    }

    final Cache cache = CacheFactory.getAnyInstance();
    String regionName = null;
    if (regionPath != null) {
        regionName = regionPath.startsWith("/") ? regionPath.substring(1) : regionPath;
    }
    IndexInfo indexInfo = new IndexInfo(indexName, regionName);
    Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);

    if (targetMembers.isEmpty()) {
        return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
    }

    ResultCollector rc = CliUtil.executeFunction(destroyIndexFunction, indexInfo, targetMembers);
    List<Object> funcResults = (List<Object>) rc.getResult();

    Set<String> successfulMembers = new TreeSet<>();
    Map<String, Set<String>> indexOpFailMap = new HashMap<>();

    AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
    for (Object funcResult : funcResults) {
        if (!(funcResult instanceof CliFunctionResult)) {
            continue;
        }
        CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;

        if (cliFunctionResult.isSuccessful()) {
            successfulMembers.add(cliFunctionResult.getMemberIdOrName());
            if (xmlEntity.get() == null) {
                xmlEntity.set(cliFunctionResult.getXmlEntity());
            }
        } else {
            String exceptionMessage = cliFunctionResult.getMessage();
            Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);

            if (failedMembers == null) {
                failedMembers = new TreeSet<>();
            }
            failedMembers.add(cliFunctionResult.getMemberIdOrName());
            indexOpFailMap.put(exceptionMessage, failedMembers);
        }
    }
    if (!successfulMembers.isEmpty()) {
        InfoResultData infoResult = ResultBuilder.createInfoResultData();
        if (StringUtils.isNotBlank(indexName)) {
            if (StringUtils.isNotBlank(regionPath)) {
                infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__SUCCESS__MSG,
                        indexName, regionPath));
            } else {
                infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__SUCCESS__MSG, indexName));
            }
        } else {
            if (StringUtils.isNotBlank(regionPath)) {
                infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__ONLY__SUCCESS__MSG,
                        regionPath));
            } else {
                infoResult.addLine(CliStrings.DESTROY_INDEX__ON__MEMBERS__ONLY__SUCCESS__MSG);
            }
        }
        int num = 0;
        for (String memberId : successfulMembers) {
            infoResult.addLine(CliStrings
                    .format(CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
        }
        result = ResultBuilder.buildResult(infoResult);
    } else {
        ErrorResultData erd = ResultBuilder.createErrorResultData();
        if (StringUtils.isNotBlank(indexName)) {
            erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__FAILURE__MSG, indexName));
        } else {
            erd.addLine("Indexes could not be destroyed for following reasons");
        }

        Set<String> exceptionMessages = indexOpFailMap.keySet();

        for (String exceptionMessage : exceptionMessages) {
            erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__REASON_MESSAGE, exceptionMessage));
            erd.addLine(CliStrings.DESTROY_INDEX__EXCEPTION__OCCURRED__ON);

            Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
            int num = 0;

            for (String memberId : memberIds) {
                erd.addLine(CliStrings.format(
                        CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
            }
            erd.addLine("");
        }
        result = ResultBuilder.buildResult(erd);
    }
    if (xmlEntity.get() != null) {
        persistClusterConfiguration(result,
                () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), group));
    }
    return result;
}

From source file:org.apache.geode.management.internal.cli.functions.UndeployFunction.java

@Override
public void execute(FunctionContext context) {
    // Declared here so that it's available when returning a Throwable
    String memberId = "";

    try {/*from w ww. j  a  va2s . co m*/
        final Object[] args = (Object[]) context.getArguments();
        final String[] jarFilenameList = (String[]) args[0]; // Comma separated
        InternalCache cache = (InternalCache) context.getCache();

        final JarDeployer jarDeployer = ClassPathLoader.getLatest().getJarDeployer();

        DistributedMember member = cache.getDistributedSystem().getDistributedMember();

        memberId = member.getId();
        // If they set a name use it instead
        if (!member.getName().equals("")) {
            memberId = member.getName();
        }

        String[] undeployedJars = new String[0];
        if (ArrayUtils.isEmpty(jarFilenameList)) {
            final List<DeployedJar> jarClassLoaders = jarDeployer.findDeployedJars();
            undeployedJars = new String[jarClassLoaders.size() * 2];
            int index = 0;
            for (DeployedJar jarClassLoader : jarClassLoaders) {
                undeployedJars[index++] = jarClassLoader.getJarName();
                try {
                    undeployedJars[index++] = ClassPathLoader.getLatest().getJarDeployer()
                            .undeploy(jarClassLoader.getJarName());
                } catch (IllegalArgumentException iaex) {
                    // It's okay for it to have have been uneployed from this server
                    undeployedJars[index++] = iaex.getMessage();
                }
            }
        } else {
            List<String> undeployedList = new ArrayList<String>();
            for (String jarFilename : jarFilenameList) {
                try {
                    undeployedList.add(jarFilename);
                    undeployedList.add(ClassPathLoader.getLatest().getJarDeployer().undeploy(jarFilename));
                } catch (IllegalArgumentException iaex) {
                    // It's okay for it to not have been deployed to this server
                    undeployedList.add(iaex.getMessage());
                }
            }
            undeployedJars = undeployedList.toArray(undeployedJars);
        }

        CliFunctionResult result = new CliFunctionResult(memberId, undeployedJars);
        context.getResultSender().lastResult(result);

    } catch (CacheClosedException cce) {
        CliFunctionResult result = new CliFunctionResult(memberId, false, null);
        context.getResultSender().lastResult(result);

    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;

    } catch (Throwable th) {
        SystemFailure.checkFailure();
        logger.error("Could not undeploy JAR file: {}", th.getMessage(), th);
        CliFunctionResult result = new CliFunctionResult(memberId, th, null);
        context.getResultSender().lastResult(result);
    }
}

From source file:org.apache.hadoop.hdfs.TestBalancer.java

protected boolean isClusterBalanced(DNClient[] datanodes, int tolerance) throws IOException {

    Assert.assertFalse("empty datanode array specified", ArrayUtils.isEmpty(datanodes));
    boolean result = true;
    double[] utilizationByNode = new double[datanodes.length];
    double totalUsedSpace = 0L;
    double totalCapacity = 0L;
    Map datanodeVolumeMap = new HashMap();
    // accumulate space stored on each node
    for (int i = 0; i < datanodes.length; i++) {
        DNClient datanode = datanodes[i];
        Map volumeInfoMap = getDatanodeVolumeAttributes(datanode);
        long usedSpace = (Long) volumeInfoMap.get(ATTRNAME_USED_SPACE);
        long capacity = (Long) volumeInfoMap.get(ATTRNAME_CAPACITY);
        utilizationByNode[i] = (((double) usedSpace) / capacity) * 100;
        totalUsedSpace += usedSpace;/*  www  .j a  va  2 s. c  o m*/
        totalCapacity += capacity;
    }
    // here we are reusing previously fetched volume-info, for speed
    // an alternative is to get fresh values from the cluster here instead
    double avgUtilization = (totalUsedSpace / totalCapacity) * 100;
    for (int i = 0; i < datanodes.length; i++) {
        double varUtilization = Math.abs(avgUtilization - utilizationByNode[i]);
        if (varUtilization > tolerance) {
            result = false;
            break;
        }
    }

    return result;
}

From source file:org.apache.hive.http.JdbcJarDownloadServlet.java

private void handleError(File[] files) {
    if (ArrayUtils.isEmpty(files)) {
        LOG.error("No jdbc standalone jar found in the directory " + JDBC_JAR_DIR);
    } else {/*  w  w  w.j av a 2 s  . co  m*/
        StringBuilder fileNames = new StringBuilder();
        for (File file : files) {
            fileNames.append("\t" + file.getAbsolutePath() + "\n");
        }
        LOG.error("Multiple jdbc standalone jars exist in the directory " + JDBC_JAR_DIR + ":\n" + fileNames);
    }
}

From source file:org.apache.jetspeed.portlets.custom.CustomConfigModePortlet.java

private void addSecurityConstraint(ActionRequest request, ActionResponse response)
        throws PortletException, IOException {
    try {// w  w  w  .j  a  v  a 2 s.c  om
        RequestContext requestContext = (RequestContext) request.getAttribute(RequestContext.REQUEST_PORTALENV);
        ContentPage page = requestContext.getPage();
        String fragmentId = request.getParameter("fragment");

        ContentFragment fragment = page.getFragmentById(fragmentId);

        if (fragment == null) {
            throw new PortletException("Cannot find fragment: " + fragmentId);
        }

        SecurityConstraints constraints = new TransientSecurityConstraints(fragment.getSecurityConstraints());
        SecurityConstraint constraint = new TransientSecurityConstraint(fragment.newSecurityConstraint());
        String[] rolesArray = StringUtils.split(request.getParameter("roles"), DELIMITERS);
        String[] groupsArray = StringUtils.split(request.getParameter("groups"), DELIMITERS);
        String[] usersArray = StringUtils.split(request.getParameter("users"), DELIMITERS);

        if (!ArrayUtils.isEmpty(rolesArray)) {
            constraint.setRoles(Arrays.asList(rolesArray));
        }

        if (!ArrayUtils.isEmpty(groupsArray)) {
            constraint.setGroups(Arrays.asList(groupsArray));
        }

        if (!ArrayUtils.isEmpty(usersArray)) {
            constraint.setUsers(Arrays.asList(usersArray));
        }

        String[] permissionArray = StringUtils
                .split(StringUtils.defaultString(request.getParameter("permissions")), DELIMITERS);

        if (!ArrayUtils.isEmpty(permissionArray)) {
            constraint.setPermissions(Arrays.asList(permissionArray));
        }

        List<SecurityConstraint> constraintList = constraints.getSecurityConstraints();

        if (constraintList == null) {
            constraintList = new ArrayList<SecurityConstraint>();
        }

        constraintList.add(constraint);
        constraints.setSecurityConstraints(constraintList);

        pageLayoutComponent.updateSecurityConstraints(fragment, constraints);
    } catch (Exception e) {
        throw new PortletException("Failed to add security constraint.", e);
    }
}

From source file:org.apache.jetspeed.portlets.custom.CustomConfigModePortlet.java

private boolean hasEqualItems(String[] array, List<String> list) {
    if (ArrayUtils.isEmpty(array)) {
        return (list == null || list.isEmpty());
    } else if (list == null) {
        return ArrayUtils.isEmpty(array);
    } else if (ArrayUtils.getLength(array) == list.size()) {
        for (String item : array) {
            if (!list.contains(item)) {
                return false;
            }/*from  w  w w .  j a  v  a 2 s  . co  m*/
        }

        return true;
    }

    return false;
}