Example usage for java.util Collection getClass

List of usage examples for java.util Collection getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.oltpbenchmark.util.TestCollectionUtil.java

/**
 * testPop/*from  ww  w. j av a 2s.  c om*/
 */
@SuppressWarnings("unchecked")
public void testPop() {
    String expected[] = new String[11];
    RandomGenerator rng = new RandomGenerator(0);
    for (int i = 0; i < expected.length; i++) {
        expected[i] = rng.astring(1, 32);
    } // FOR

    Collection<String> collections[] = new Collection[] {
            CollectionUtil.addAll(new ListOrderedSet<String>(), expected),
            CollectionUtil.addAll(new HashSet<String>(), expected),
            CollectionUtil.addAll(new ArrayList<String>(), expected), };
    for (Collection<String> c : collections) {
        assertNotNull(c);
        assertEquals(c.getClass().getSimpleName(), expected.length, c.size());
        String pop = CollectionUtil.pop(c);
        assertNotNull(c.getClass().getSimpleName(), pop);
        assertEquals(c.getClass().getSimpleName(), expected.length - 1, c.size());
        assertFalse(c.getClass().getSimpleName(), c.contains(pop));

        if (c instanceof List || c instanceof ListOrderedSet) {
            assertEquals(c.getClass().getSimpleName(), expected[0], pop);
        }
    } // FOR
}

From source file:edu.brown.utils.TestCollectionUtil.java

/**
 * testPop/* w  w  w.j av  a2 s  . c  om*/
 */
@SuppressWarnings("unchecked")
public void testPop() {
    String expected[] = new String[11];
    DefaultRandomGenerator rng = new DefaultRandomGenerator();
    for (int i = 0; i < expected.length; i++) {
        expected[i] = rng.astring(1, 32);
    } // FOR

    Collection<String> collections[] = new Collection[] {
            CollectionUtil.addAll(new ListOrderedSet<String>(), expected),
            CollectionUtil.addAll(new HashSet<String>(), expected),
            CollectionUtil.addAll(new ArrayList<String>(), expected), };
    for (Collection<String> c : collections) {
        assertNotNull(c);
        assertEquals(c.getClass().getSimpleName(), expected.length, c.size());
        String pop = CollectionUtil.pop(c);
        assertNotNull(c.getClass().getSimpleName(), pop);
        assertEquals(c.getClass().getSimpleName(), expected.length - 1, c.size());
        assertFalse(c.getClass().getSimpleName(), c.contains(pop));

        if (c instanceof List || c instanceof ListOrderedSet) {
            assertEquals(c.getClass().getSimpleName(), expected[0], pop);
        }
    } // FOR
}

From source file:eu.java.pg.jsonb.types.JSONBUserType.java

@SuppressWarnings("unchecked")
@Override//from w  ww.j  a v  a2s .c  om
public Object deepCopy(Object value) throws HibernateException {

    if (!(value instanceof Collection)) {
        return value;
    }

    Collection<?> collection = (Collection) value;
    Collection collectionClone = CollectionFactory.newInstance(collection.getClass());

    collectionClone.addAll(collection.stream().map(this::deepCopy).collect(Collectors.toList()));

    return collectionClone;
}

From source file:org.projectforge.core.AbstractBaseDO.java

/**
 * /*ww  w . j a va 2s  .  com*/
 * @param srcClazz
 * @param src
 * @param dest
 * @param ignoreFields
 * @return true, if any modifications are detected, otherwise false;
 */
@SuppressWarnings("unchecked")
private static ModificationStatus copyDeclaredFields(final Class<?> srcClazz, final BaseDO<?> src,
        final BaseDO<?> dest, final String... ignoreFields) {
    final Field[] fields = srcClazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    ModificationStatus modificationStatus = null;
    for (final Field field : fields) {
        final String fieldName = field.getName();
        if ((ignoreFields != null && ArrayUtils.contains(ignoreFields, fieldName) == true)
                || accept(field) == false) {
            continue;
        }
        try {
            final Object srcFieldValue = field.get(src);
            final Object destFieldValue = field.get(dest);
            if (field.getType().isPrimitive() == true) {
                if (ObjectUtils.equals(destFieldValue, srcFieldValue) == false) {
                    field.set(dest, srcFieldValue);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                }
                continue;
            } else if (srcFieldValue == null) {
                if (field.getType() == String.class) {
                    if (StringUtils.isNotEmpty((String) destFieldValue) == true) {
                        field.set(dest, null);
                        modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                    }
                } else if (destFieldValue != null) {
                    field.set(dest, null);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                } else {
                    // dest was already null
                }
            } else if (srcFieldValue instanceof Collection) {
                Collection<Object> destColl = (Collection<Object>) destFieldValue;
                final Collection<Object> srcColl = (Collection<Object>) srcFieldValue;
                final Collection<Object> toRemove = new ArrayList<Object>();
                if (srcColl != null && destColl == null) {
                    if (srcColl instanceof TreeSet) {
                        destColl = new TreeSet<Object>();
                    } else if (srcColl instanceof HashSet) {
                        destColl = new HashSet<Object>();
                    } else if (srcColl instanceof List) {
                        destColl = new ArrayList<Object>();
                    } else if (srcColl instanceof PersistentSet) {
                        destColl = new HashSet<Object>();
                    } else {
                        log.error("Unsupported collection type: " + srcColl.getClass().getName());
                    }
                    field.set(dest, destColl);
                }
                for (final Object o : destColl) {
                    if (srcColl.contains(o) == false) {
                        toRemove.add(o);
                    }
                }
                for (final Object o : toRemove) {
                    if (log.isDebugEnabled() == true) {
                        log.debug("Removing collection entry: " + o);
                    }
                    destColl.remove(o);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                }
                for (final Object srcEntry : srcColl) {
                    if (destColl.contains(srcEntry) == false) {
                        if (log.isDebugEnabled() == true) {
                            log.debug("Adding new collection entry: " + srcEntry);
                        }
                        destColl.add(srcEntry);
                        modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                    } else if (srcEntry instanceof BaseDO) {
                        final PFPersistancyBehavior behavior = field.getAnnotation(PFPersistancyBehavior.class);
                        if (behavior != null && behavior.autoUpdateCollectionEntries() == true) {
                            BaseDO<?> destEntry = null;
                            for (final Object entry : destColl) {
                                if (entry.equals(srcEntry) == true) {
                                    destEntry = (BaseDO<?>) entry;
                                    break;
                                }
                            }
                            Validate.notNull(destEntry);
                            final ModificationStatus st = destEntry.copyValuesFrom((BaseDO<?>) srcEntry);
                            modificationStatus = getModificationStatus(modificationStatus, st);
                        }
                    }
                }
            } else if (srcFieldValue instanceof BaseDO) {
                final Serializable srcFieldValueId = HibernateUtils.getIdentifier((BaseDO<?>) srcFieldValue);
                if (srcFieldValueId != null) {
                    if (destFieldValue == null || ObjectUtils.equals(srcFieldValueId,
                            ((BaseDO<?>) destFieldValue).getId()) == false) {
                        field.set(dest, srcFieldValue);
                        modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                    }
                } else {
                    log.error(
                            "Can't get id though can't copy the BaseDO (see error message above about HHH-3502).");
                }
            } else if (srcFieldValue instanceof java.sql.Date) {
                if (destFieldValue == null) {
                    field.set(dest, srcFieldValue);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                } else {
                    final DayHolder srcDay = new DayHolder((Date) srcFieldValue);
                    final DayHolder destDay = new DayHolder((Date) destFieldValue);
                    if (srcDay.isSameDay(destDay) == false) {
                        field.set(dest, srcDay.getSQLDate());
                        modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                    }
                }
            } else if (srcFieldValue instanceof Date) {
                if (destFieldValue == null
                        || ((Date) srcFieldValue).getTime() != ((Date) destFieldValue).getTime()) {
                    field.set(dest, srcFieldValue);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                }
            } else if (srcFieldValue instanceof BigDecimal) {
                if (destFieldValue == null
                        || ((BigDecimal) srcFieldValue).compareTo((BigDecimal) destFieldValue) != 0) {
                    field.set(dest, srcFieldValue);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                }
            } else if (ObjectUtils.equals(destFieldValue, srcFieldValue) == false) {
                field.set(dest, srcFieldValue);
                modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
            }
        } catch (final IllegalAccessException ex) {
            throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
        }
    }
    final Class<?> superClazz = srcClazz.getSuperclass();
    if (superClazz != null) {
        final ModificationStatus st = copyDeclaredFields(superClazz, src, dest, ignoreFields);
        modificationStatus = getModificationStatus(modificationStatus, st);
    }
    return modificationStatus;
}

From source file:org.bbreak.excella.core.SheetParser.java

/**
 * ??// w ww. j a va 2  s .  c  o m
 * 
 * @param sheet ?
 * @param data ?
 * @param sheetData ?
 * @param cell ?
 * @param row ?
 * @param columnIdx ??
 * @return ??????
 * @throws ParseException ??????Throw?
 */
private boolean parseCell(Sheet sheet, Object data, SheetData sheetData, Cell cell, Row row, int columnIdx)
        throws ParseException {
    for (TagParser<?> parser : tagParsers) {
        // ??
        if (parser.isParse(sheet, cell)) {
            String strCellValue = cell.getStringCellValue();
            Map<String, String> paramDef = TagUtil.getParams(strCellValue);
            // ?
            Object result = parser.parse(sheet, cell, data);

            // ??
            if (result != null) {
                // ?ResultKey?????ResultKey?
                // ???Tag???
                String resultKey = parser.getTag();
                if (paramDef.containsKey(PARAM_RESULT_KEY)) {
                    resultKey = paramDef.get(PARAM_RESULT_KEY);
                }
                sheetData.put(resultKey, result);
            }
            // ??
            if (log.isInfoEnabled()) {
                StringBuilder resultBuf = new StringBuilder(strCellValue + "???:");
                if (result instanceof Map) {
                    Map<?, ?> mapResult = (Map<?, ?>) result;
                    Set<?> keyset = mapResult.keySet();
                    for (Object key : keyset) {
                        resultBuf.append("[" + key + ":" + mapResult.get(key) + "]");
                    }
                } else if (result instanceof Collection) {
                    Collection<?> listResult = (Collection<?>) result;
                    resultBuf.append(listResult.getClass() + " Size=" + listResult.size());
                } else {
                    resultBuf.append(result);
                }
                log.info(resultBuf.toString());
            }

            // ??????????????

            if (paramDef.containsKey(PARAM_LAST_TAG)) {
                String strLastTag = paramDef.get(PARAM_LAST_TAG);
                try {
                    if (Boolean.parseBoolean(strLastTag)) {
                        return true;
                    }
                } catch (Exception e) {
                    throw new ParseException(cell);
                }
            }

            cell = row.getCell(columnIdx);
            if (cell != null && cell.getCellTypeEnum() == CellType.STRING
                    && !strCellValue.equals(cell.getStringCellValue())) {
                // ?????????????
                if (parseCell(sheet, data, sheetData, cell, row, columnIdx)) {
                    // ?
                    return true;
                }
            }
            break;
        }
    }
    return false;
}

From source file:org.duracloud.snapshot.rest.GeneralResourceTest.java

@Test
public void testInit() {
    Capture<DatabaseConfig> dbConfigCapture = new Capture<>();
    initializer.init(EasyMock.capture(dbConfigCapture));
    EasyMock.expectLastCall();/* w w w  .  j av a 2 s. com*/

    Capture<ExecutionListenerConfig> notifyConfigCapture = new Capture<>();
    snapshotJobListener.init(EasyMock.capture(notifyConfigCapture));
    EasyMock.expectLastCall();

    restoreJobListener.init(EasyMock.capture(notifyConfigCapture));
    EasyMock.expectLastCall();

    snapshotFinalizer.initialize(snapshotFinalizerPeriodMs);
    EasyMock.expectLastCall();

    Capture<SnapshotJobManagerConfig> duracloudConfigCapture = new Capture<>();
    manager.init(EasyMock.capture(duracloudConfigCapture));
    EasyMock.expectLastCall();

    Capture<RestoreManagerConfig> restorationConfigCapture = new Capture<>();
    restorationManager.init(EasyMock.capture(restorationConfigCapture), EasyMock.isA(SnapshotJobManager.class));
    EasyMock.expectLastCall();

    Collection<NotificationConfig> collection = new ArrayList<>();
    this.notificationManager.initializeNotifiers(EasyMock.isA(collection.getClass()));
    EasyMock.expectLastCall();

    bridgeConfiguration.setDuracloudUsername(duracloudUsername);
    EasyMock.expectLastCall();
    bridgeConfiguration.setDuracloudPassword(duracloudPassword);
    EasyMock.expectLastCall();
    bridgeConfiguration.setDuracloudEmailAddresses(duracloudEmailAddresses);
    EasyMock.expectLastCall();
    bridgeConfiguration.setContentRootDir(EasyMock.eq(this.contentDirRoot));
    EasyMock.expectLastCall();

    replayAll();

    InitParams initParams = createInitParams();

    resource.init(initParams);

    DatabaseConfig dbConfig = dbConfigCapture.getValue();
    assertEquals(databaseUser, dbConfig.getUsername());
    assertEquals(databasePassword, dbConfig.getPassword());
    assertEquals(databaseURL, dbConfig.getUrl());
    assertEquals(clean, dbConfig.isClean());

    ExecutionListenerConfig notifyConfig = notifyConfigCapture.getValue();
    assertEquals(awsAccessKey, notifyConfig.getSesUsername());
    assertEquals(awsSecretKey, notifyConfig.getSesPassword());
    assertEquals(originatorEmailAddress, notifyConfig.getOriginatorEmailAddress());
    assertEquals(duracloudEmailAddresses[0], notifyConfig.getDuracloudEmailAddresses()[0]);
    assertEquals(dpnEmailAddresses[0], notifyConfig.getDpnEmailAddresses()[0]);

    SnapshotJobManagerConfig jobManagerConfig = duracloudConfigCapture.getValue();

    assertEquals(duracloudUsername, jobManagerConfig.getDuracloudUsername());
    assertEquals(duracloudPassword, jobManagerConfig.getDuracloudPassword());
    assertEquals(contentDirRoot, jobManagerConfig.getContentRootDir());
    assertEquals(workDir, jobManagerConfig.getWorkDir());

    RestoreManagerConfig restorationConfig = restorationConfigCapture.getValue();
    assertEquals(duracloudEmailAddresses[0], restorationConfig.getDuracloudEmailAddresses()[0]);
    assertEquals(dpnEmailAddresses[0], restorationConfig.getDpnEmailAddresses()[0]);

}

From source file:org.ldaptive.beans.spring.SpelAttributeValueMutator.java

/**
 * Uses the configured expression and evaluation context to set values on the
 * supplied object. If a custom transcoder has been configured it is executed
 * on the values before they are passed to the expression.
 *
 * @param  <T>  either String or byte[]
 * @param  object  to set values on/*w w w . j a va2s . co  m*/
 * @param  values  to set
 * @param  type  of objects in the collection
 */
protected <T> void setValues(final Object object, final Collection<T> values, final Class<T> type) {
    if (transcoder != null) {
        final Collection<Object> newValues = createCollection(values.getClass(), values.size());
        for (T t : values) {
            if (byte[].class == type) {
                newValues.add(transcoder.decodeBinaryValue((byte[]) t));
            } else if (String.class == type) {
                newValues.add(transcoder.decodeStringValue((String) t));
            } else {
                throw new IllegalArgumentException("type must be either String.class or byte[].class");
            }
        }
        expression.setValue(evaluationContext, object, newValues);
    } else {
        if (values != null && values.size() == 1) {
            expression.setValue(evaluationContext, object, values.iterator().next());
        } else {
            expression.setValue(evaluationContext, object, values);
        }
    }
}

From source file:org.springframework.data.neo4j.support.NodeEntityRelationshipTest.java

@Test
@Transactional/*from  w w  w  .  j  a va  2 s  . c o  m*/
public void testGetOneToManyRelationship() {
    Person michael = persistedPerson("Michael", 35);
    Person david = persistedPerson("David", 25);
    Group group = new Group().persist();
    Set<Person> persons = new HashSet<Person>(Arrays.asList(michael, david));
    group.setPersons(persons);
    Collection<Person> personsFromGet = group.getPersons();
    assertEquals(persons, personsFromGet);
    Assert.assertTrue(Set.class.isAssignableFrom(personsFromGet.getClass()));
}

From source file:org.springframework.data.neo4j.aspects.support.NodeEntityRelationshipTest.java

@Test
@Transactional/*from ww w. ja  va2 s  .co m*/
public void testGetOneToManyRelationship() {
    Person michael = persistedPerson("Michael", 35);
    Person david = persistedPerson("David", 25);
    Group group = new Group().persist();
    Set<Person> persons = new HashSet<Person>(Arrays.asList(michael, david));
    group.setPersons(persons);
    Collection<Person> personsFromGet = group.getPersons();
    assertEquals(persons, personsFromGet);
    assertTrue(Set.class.isAssignableFrom(personsFromGet.getClass()));
}

From source file:org.jdto.mergers.PropertyCollectionMerger.java

private Collection getCollectionToReturn(Collection value) {
    try {//from   ww w  .j a  v a 2  s . com
        Collection ret = null;

        if (value instanceof Cloneable) {
            ret = (Collection) ObjectUtils.clone(value);
            ret.clear();
        } else {
            //try to create a new instance of the collection
            ret = BeanClassUtils.createInstance(value.getClass());
        }
        return ret;
    } catch (Exception ex) {
        logger.error("Exception while trying to instantiate collection", ex);
        throw new RuntimeException(ex);
    }
}