Example usage for java.util Collection clear

List of usage examples for java.util Collection clear

Introduction

In this page you can find the example usage for java.util Collection clear.

Prototype

void clear();

Source Link

Document

Removes all of the elements from this collection (optional operation).

Usage

From source file:jp.ac.tokushima_u.is.ll.common.orm.hibernate.HibernateWebUtils.java

/**
 * ?ID?,???./*  w w  w .  j av a2 s.c  o  m*/
 * 
 * ??????id,??????id?????.
 * ???id??,??id??.
 * ?ID, ??cascade-save-or-update.
 * 
 * @param srcObjects ??,.
 * @param checkedIds  ?,ID.
 * @param clazz  ?
 * @param idName ??
 */
public static <T, ID> void mergeByCheckedIds(final Collection<T> srcObjects, final Collection<ID> checkedIds,
        final Class<T> clazz, final String idName) {

    //?
    Assert.notNull(srcObjects, "scrObjects?");
    Assert.hasText(idName, "idName?");
    Assert.notNull(clazz, "clazz?");

    //?,???.
    if (checkedIds == null) {
        srcObjects.clear();
        return;
    }

    //????,id?ID?,.
    //?,???id,?id???ID.
    Iterator<T> srcIterator = srcObjects.iterator();
    try {

        while (srcIterator.hasNext()) {
            T element = srcIterator.next();
            Object id;
            id = PropertyUtils.getProperty(element, idName);

            if (!checkedIds.contains(id)) {
                srcIterator.remove();
            } else {
                checkedIds.remove(id);
            }
        }

        //ID??id????,,id??.
        for (ID id : checkedIds) {
            T obj = clazz.newInstance();
            PropertyUtils.setProperty(obj, idName, id);
            srcObjects.add(obj);
        }
    } catch (Exception e) {
        throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
    }
}

From source file:gov.nih.nci.caintegrator.common.PermissibleValueUtil.java

/**
 * Add new values to the permissibleValue collection.
 *
 * @param type the type of the abstractPermissibleValue
 * @param abstractPermissibleValues the PermissibleValue collection
 * @param addList the list of DisplayString to add
 *//*from ww w . j  av a2  s.  c o m*/
public static void addNewValue(String type, Collection<PermissibleValue> abstractPermissibleValues,
        List<String> addList) {
    if (addList == null) {
        return;
    }
    for (String displayString : addList) {
        try {
            addNewValue(type, abstractPermissibleValues, displayString);
        } catch (NumberFormatException e) {
            abstractPermissibleValues.clear();
            return;
        } catch (ParseException e) {
            abstractPermissibleValues.clear();
            return;
        }
    }
}

From source file:com.afeng.common.dao.orm.HibernateWebUtils.java

/**
 * ?ID?,???.//from www.j ava  2  s .c  o m
 * <p/>
 * ??????id,??????id?????.
 * ???id??,??id??.
 * ?ID, ??cascade-save-or-update.
 *
 * @param srcObjects ??,.
 * @param checkedIds ?,ID.
 * @param clazz      ?
 * @param idName     ??
 */
public static <T, ID> void mergeByCheckedIds(final Collection<T> srcObjects, final Collection<ID> checkedIds,
        final Class<T> clazz, final String idName) {

    //?
    Assert.notNull(srcObjects, "scrObjects?");
    Assert.hasText(idName, "idName?");
    Assert.notNull(clazz, "clazz?");

    //?,???.
    if (checkedIds == null) {
        srcObjects.clear();
        return;
    }

    //????,id?ID?,.
    //?,???id,?id???id.
    Iterator<T> srcIterator = srcObjects.iterator();
    try {

        while (srcIterator.hasNext()) {
            T element = srcIterator.next();
            Object id;
            id = PropertyUtils.getProperty(element, idName);

            if (!checkedIds.contains(id)) {
                srcIterator.remove();
            } else {
                checkedIds.remove(id);
            }
        }

        //ID??id????,,id??.
        for (ID id : checkedIds) {
            T obj = clazz.newInstance();
            PropertyUtils.setProperty(obj, idName, id);
            srcObjects.add(obj);
        }
    } catch (Exception e) {
        throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
    }
}

From source file:mitm.common.mail.BodyPartUtils.java

/**
 * Returns the plain text body of the message and it's attachments. The attachments collection is cleared before use.
 *///w  w w .ja  v a  2s  .  c o m
public static String getPlainBodyAndAttachments(final MimeMessage message, Collection<Part> attachments)
        throws MessagingException, IOException {
    String body = null;

    for (int maxLevel = 1; maxLevel <= 2; maxLevel++) {
        if (attachments != null) {
            attachments.clear();
        }

        body = getPlainBodyAndAttachments(message, attachments, 0, maxLevel);

        if (body != null) {
            break;
        }
    }

    return body;
}

From source file:de.xwic.appkit.core.util.CollectionUtil.java

/**
 * @param where collection to clear and add to
 * @param fromWhere what to add//from   w  w  w. j  a  v a2 s .c  o  m
 * @throws NullPointerException if <code>where</code> is empty
 */
public static <E> void clearAndAddAll(final Collection<? super E> where,
        final Collection<? extends E> fromWhere) throws NullPointerException {
    if (where == fromWhere) {
        return;
    }
    where.clear();
    if (!isEmpty(fromWhere)) {
        where.addAll(fromWhere);
    }
}

From source file:org.apache.openejb.util.classloader.URLClassLoaderFirst.java

private static void list(final Collection<String> list, final String key) {
    list.clear();

    final String s = SystemInstance.get().getOptions().get(key, (String) null);
    if (s != null && !s.trim().isEmpty()) {
        list.addAll(Arrays.asList(s.trim().split(",")));
    }/*from   w  ww. ja va  2  s.  com*/
}

From source file:org.rhq.core.pc.drift.DriftDetector.java

static private void safeClear(Collection<?>... collections) {
    if (null == collections) {
        return;/*from   www . jav  a 2s .co m*/
    }
    for (Collection<?> c : collections) {
        if (null != c) {
            c.clear();
        }
    }
}

From source file:fr.gouv.culture.vitam.digest.DigestCompute.java

public static int createDigest(File src, File dst, File ftar, File fglobal, boolean oneDigestPerFile,
        String[] extensions, String mask, boolean prefix) {
    if (mask == null) {
        return createDigest(src, dst, ftar, fglobal, oneDigestPerFile, extensions);
    }/*from   w  w w. j  a va2s. c o  m*/
    try {
        if (prefix) {
            // fix mask
            List<File> filesToScan = new ArrayList<File>();
            File dirToSearch = src;
            if (!dirToSearch.isDirectory()) {
                if (dirToSearch.canRead() && dirToSearch.getName().startsWith(mask)) {
                    filesToScan.add(dirToSearch);
                } else {
                    throw new CommandExecutionException("Resources not found");
                }
            } else {
                Collection<File> temp = FileUtils.listFiles(dirToSearch, extensions,
                        StaticValues.config.argument.recursive);
                for (File file : temp) {
                    if (file.getName().startsWith(mask)) {
                        filesToScan.add(file);
                    }
                }
                temp.clear();
            }
            return createDigest(src, dst, ftar, fglobal, oneDigestPerFile, filesToScan);
        } else {
            // RegEx mask
            File dirToSearch = src;
            if (!dirToSearch.isDirectory()) {
                List<File> filesToScan = new ArrayList<File>();
                if (dirToSearch.canRead() && dirToSearch.getName().matches(mask + ".*")) {
                    filesToScan.add(dirToSearch);
                    String global = dirToSearch.getName().replaceAll("[^" + mask + "].*", "")
                            + "_all_digests.xml";
                    fglobal = new File(fglobal, global);
                } else {
                    throw new CommandExecutionException("Resources not found");
                }
                return createDigest(src, dst, ftar, fglobal, oneDigestPerFile, filesToScan);
            } else {
                HashMap<String, List<File>> hashmap = new HashMap<String, List<File>>();
                Collection<File> temp = FileUtils.listFiles(dirToSearch, extensions,
                        StaticValues.config.argument.recursive);
                List<File> filesToScan = null;
                Pattern pattern = Pattern.compile(mask + ".*");
                Pattern pattern2 = Pattern.compile(mask);
                for (File file : temp) {
                    String filename = file.getName();
                    Matcher matcher = pattern.matcher(filename);
                    if (matcher.matches()) {
                        String end = pattern2.matcher(filename).replaceFirst("");
                        int pos = filename.indexOf(end);
                        if (pos <= 0) {
                            System.err.println("Cannot find : " + end + " in " + filename);
                            continue;
                        }
                        String global = filename.substring(0, pos);
                        if (global.charAt(global.length() - 1) != '_') {
                            global += "_";
                        }
                        global += "all_digests.xml";
                        filesToScan = hashmap.get(global);
                        if (filesToScan == null) {
                            filesToScan = new ArrayList<File>();
                            hashmap.put(global, filesToScan);
                        }
                        filesToScan.add(file);
                    }
                }
                temp.clear();
                int res = 0;
                for (String global : hashmap.keySet()) {
                    File fglobalnew = new File(fglobal, global);
                    res += createDigest(src, dst, ftar, fglobalnew, oneDigestPerFile, hashmap.get(global));
                }
                hashmap.clear();
                return res;
            }
        }
    } catch (CommandExecutionException e1) {
        System.err.println(StaticValues.LBL.error_error.get() + " " + e1.toString());
        return -1;
    }
}

From source file:org.toobsframework.data.beanutil.BeanMonkey.java

private static Object evaluatePropertyValue(String name, String className, String namespace, Object value,
        Map properties, Object bean)
        throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, PermissionException {
    // Perform the assignment for this property
    if (className.startsWith(configuration.getProperty("toobs.beanmonkey.dataPackage"))) {
        className = className.substring(className.lastIndexOf(".") + 1);

        IObjectLoader odao = null;/*  www.  j av  a2s  .c o m*/
        ICollectionLoader cdao = null;
        Object daoObject = beanFactory.getBean(Introspector.decapitalize(className) + "Dao");
        if (daoObject == null) {
            throw new InvocationTargetException(new Exception(
                    "DAO class " + Introspector.decapitalize(className) + "Dao could not be loaded"));
        }
        if (daoObject instanceof IObjectLoader) {
            odao = (IObjectLoader) daoObject;
        } else {
            cdao = (ICollectionLoader) daoObject;
        }

        String guid = null;
        if (value != null && value.getClass().isArray()) {
            if (properties.containsKey(PlatformConstants.MULTI_ACTION_INSTANCE)) {
                Object[] oldValue = (Object[]) value;
                Integer instance = (Integer) properties.get(PlatformConstants.MULTI_ACTION_INSTANCE);
                if (oldValue.length >= instance + 1) {
                    guid = ((String[]) oldValue)[instance];
                } else {
                    throw new RuntimeException("Instance " + instance + " not found in " + oldValue + " for: "
                            + name + " class: " + className + " in: " + bean);
                }
            } else {
                guid = ((String[]) value)[0];
            }
        } else {
            guid = (String) value;
        }
        if (guid != null && guid.length() > 0) {
            String personId = (String) properties.get("personId");
            try {
                if (odao != null) {
                    value = odao.load(guid);
                } else {
                    value = cdao.load(Integer.parseInt(guid));
                }
            } catch (PermissionException pe) {
                log.error("PermissionException loading object " + className + "." + name + " with guid " + guid
                        + " by person " + personId);
                throw pe;
            } finally {
            }
        } else {
            value = null;
        }
    } else if ((className.equals("java.util.ArrayList") || className.equals("java.util.List"))
            && !(value instanceof java.util.List)) {
        Object[] values = null;
        if (value != null && value.getClass().isArray()) {
            values = ((Object[]) value);
        } else {
            values = new Object[1];
            values[0] = (Object) value;
        }
        value = new ArrayList();
        for (int aa = 0; aa < values.length; aa++) {
            if (!"".equals(values[aa]))
                ((ArrayList) value).add(values[aa]);
        }
        if (((ArrayList) value).size() == 0)
            value = null;
    } else if (className.equals("java.util.Collection")) {
        className = null;
        String typeProp = (namespace != null ? namespace : "") + name + "-Type";
        if (properties.get(typeProp) != null && properties.get(typeProp).getClass().isArray()) {
            className = ((String[]) properties.get(typeProp))[0];
        } else {
            className = (String) properties.get(typeProp);
        }

        if (className == null) {
            throw new InvocationTargetException(new Exception("Missing collection type for " + name));
        }

        IObjectLoader odao = null;
        ICollectionLoader cdao = null;
        Object daoObject = beanFactory.getBean(Introspector.decapitalize(className) + "Dao");
        if (daoObject == null) {
            throw new InvocationTargetException(new Exception(
                    "DAO class " + Introspector.decapitalize(className) + "Dao could not be loaded"));
        }
        if (daoObject instanceof IObjectLoader) {
            odao = (IObjectLoader) daoObject;
        } else {
            cdao = (ICollectionLoader) daoObject;
        }

        Object[] guids = null;
        if (value != null && value.getClass().isArray()) {
            guids = ((Object[]) value);
        } else if (value != null && value instanceof ArrayList) {
            guids = new Object[((ArrayList) value).size()];
            for (int i = 0; i < guids.length; i++) {
                guids[i] = (Object) ((ArrayList) value).get(i);
            }
        } else {
            guids = new Object[1];
            guids[0] = (Object) value;
        }

        String personId = (String) properties.get("personId");

        java.util.Collection valueList = (java.util.Collection) PropertyUtils.getProperty(bean, name);
        valueList.clear();

        for (int i = 0; i < guids.length; i++) {
            if (odao != null) {
                if (((String) guids[i]).length() == 0)
                    continue;
                value = odao.load((String) guids[i]);
            } else if (cdao != null) {
                value = cdao.load((Integer) guids[i]);
            }
            if (value != null) {
                valueList.add(value);
            } else {
                if (beanFactory.containsBean(className + "CollectionCreator")) {
                    ICollectionCreator collectionCreator = (ICollectionCreator) beanFactory
                            .getBean(className + "CollectionCreator");
                    try {
                        collectionCreator.addCollectionElements(guids[i], valueList, properties, personId,
                                namespace);
                    } catch (Exception e) {
                        throw new InvocationTargetException(e);
                    }
                }
            }
        }
        value = valueList;
    } else if (className.equals("java.lang.String") && value != null && value.getClass().isArray()
            && ((Object[]) value).length > 1
            && properties.containsKey(PlatformConstants.MULTI_ACTION_INSTANCE)) {
        Object[] oldValue = (Object[]) value;
        Integer instance = (Integer) properties.get(PlatformConstants.MULTI_ACTION_INSTANCE);
        if (oldValue.length >= instance + 1) {
            value = oldValue[instance];
        } else {
            throw new RuntimeException("Instance " + instance + " not found in " + oldValue + " for: " + name
                    + " class: " + className + " in: " + bean);
        }
    } else if (className.equals("java.lang.String") && value != null && value.getClass().isArray()
            && ((Object[]) value).length > 1) {
        Object[] oldValue = (Object[]) value;
        String newValue = new String();
        for (int i = 0; i < oldValue.length; i++) {
            if (i > 0) {
                newValue = newValue + ";";
            }
            newValue = newValue + oldValue[i];
        }
        value = newValue;
    } else if ((className.equals("java.lang.Integer") || className.equals("java.lang.Boolean"))
            && value != null) {
        if (value.getClass().isArray() && ((Object[]) value).length == 1 && ((Object[]) value)[0].equals("")) {
            value = null;
        } else if (!value.getClass().isArray() && String.valueOf(value).equals("")) {
            value = null;
        }
    } else if (className.equals("java.util.Date") && value != null) {
        if (value.getClass().isArray()) {
            value = StringToDateConverter.convert(value);
        }
    }

    return value;
}

From source file:org.deri.iris.queryrewriting.RewritingUtils.java

public static Collection<IRule> unfold(final IRule reconciliationQuery,
        final Map<String, Set<IRule>> rewritingMap, final Set<IRule> cns) {

    final Collection<IRule> unfolded = new ArrayList<IRule>();
    unfolded.add(RenamingUtils.canonicalRenaming(reconciliationQuery, "U"));

    List<IRule> temp;/*from w  w  w .  j a v a 2s  .  c o  m*/
    for (final String key : rewritingMap.keySet()) {

        temp = ImmutableList.copyOf(unfolded);
        unfolded.clear();
        // get the corresponding expansions
        final Set<IRule> rewritings = rewritingMap.get(key);
        for (final IRule r : temp) {
            for (final ILiteral t : r.getBody()) {
                if (t.getAtom().getPredicate().getPredicateSymbol().equals(key)) {
                    // possible expansion
                    final Map<IVariable, ITerm> gamma = new LinkedHashMap<IVariable, ITerm>();
                    for (IRule exp : rewritings) {
                        exp = RenamingUtils.canonicalRenaming(exp, "V");
                        if (TermMatchingAndSubstitution.unify(t.getAtom(),
                                exp.getHead().iterator().next().getAtom(), gamma)) {
                            final IRule qPrime = RenamingUtils.canonicalRenaming(
                                    RewritingUtils.rewrite(r, t.getAtom(), exp.getBody(), gamma), "U");
                            unfolded.add(qPrime);
                        }
                    }
                }
            }
        }

    }
    return unfolded;
}