List of usage examples for java.util Collection getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.openmrs.module.sync.SyncUtil.java
public static String formatObject(Object object) { if (object != null) { try {/*w ww .j a v a 2 s .c om*/ if (object instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) object; Class persistentClass = proxy.getHibernateLazyInitializer().getPersistentClass(); Object identifier = proxy.getHibernateLazyInitializer().getIdentifier(); return persistentClass.getSimpleName() + "#" + identifier; } if (object instanceof OpenmrsObject) { OpenmrsObject o = (OpenmrsObject) object; return object.getClass().getSimpleName() + (o.getId() == null ? "" : "#" + o.getId()); } if (object instanceof Collection) { Collection c = (Collection) object; StringBuilder sb = new StringBuilder(); for (Object o : c) { sb.append(sb.length() == 0 ? "" : ",").append(formatObject(o)); } return c.getClass().getSimpleName() + "[" + sb + "]"; } } catch (Exception e) { } return object.getClass().getSimpleName(); } return ""; }
From source file:jef.database.DbUtils.java
/** * ????/*from ww w .jav a 2 s .c o m*/ * * @param subs * @param container * @return * @throws SQLException */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected static Object toProperContainerType(Collection<? extends IQueryableEntity> subs, Class<?> container, Class<?> bean, AbstractRefField config) throws SQLException { if (container.isAssignableFrom(subs.getClass())) { return subs; } if (container == Set.class) { HashSet set = new HashSet(); set.addAll(subs); return set; } else if (container == List.class) { ArrayList list = new ArrayList(); list.addAll(subs); return list; } else if (container == Array.class) { return subs.toArray(); } else if (container == Map.class) { Cascade cascade = config.getCascadeInfo(); if (cascade == null) { throw new SQLException("@Cascade annotation is required for Map mapping " + config.toString()); } Map map = new HashMap(); String key = cascade.keyOfMap(); BeanAccessor ba = FastBeanWrapperImpl.getAccessorFor(bean); if (StringUtils.isEmpty(cascade.valueOfMap())) { for (IQueryableEntity e : subs) { map.put(ba.getProperty(e, key), e); } } else { String vField = cascade.valueOfMap(); for (IQueryableEntity e : subs) { map.put(ba.getProperty(e, key), ba.getProperty(e, vField)); } } return map; } throw new SQLException("the type " + container.getName() + " is not supported as a collection container."); }
From source file:com.grepcurl.random.BaseGenerator.java
public <T> T choose(Collection<T> elements) { Validate.notNull(elements);/* w w w . j a v a 2 s . c o m*/ Validate.isTrue(elements.size() > 0); if (elements instanceof List) { return choose((List<T>) elements); } else if (elements instanceof Set) { return choose((Set<T>) elements); } else { throw new IllegalArgumentException( "Don't know how to choose from collection of type: " + elements.getClass()); } }
From source file:org.dllearner.core.AbstractAxiomLearningAlgorithm.java
protected <K, J extends Set<V>, V> void addToMap(Map<K, J> map, K key, Collection<V> newValues) { J values = map.get(key);/*from w ww .j ava2 s . c o m*/ if (values == null) { try { values = (J) newValues.getClass().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } map.put(key, values); } values.addAll(newValues); }
From source file:nl.strohalm.cyclos.utils.database.DatabaseQueryHandler.java
@SuppressWarnings("unchecked") public void resolveReferences(final Entity entity) { final EntityType meta = getClassMetaData(entity); Set<Attribute> attrs = meta.getAttributes(); for (Attribute attr : attrs) { final Attribute type = attr; final String name = attr.getName(); if (type instanceof EntityType) { // Properties that are relationships to other entities Entity rel = PropertyHelper.get(entity, name); if (rel instanceof EntityReference) { rel = DatabaseUtil.getCurrentEntityManager().find(EntityHelper.getRealClass(rel), rel.getId()); PropertyHelper.set(entity, name, rel); }/* ww w.j a v a 2 s .c o m*/ } else if (type.isCollection()) { // Properties that are collections of other entities final Collection<?> current = PropertyHelper.get(entity, name); if (current != null /*&& !(current instanceof PersistentCollection)*/) { // We must check that the collection is made of entities, since Hibernate supports collections os values boolean isEntityCollection = true; final Collection<Entity> resolved = ClassHelper.instantiate(current.getClass()); for (final Object object : current) { if (object != null && !(object instanceof Entity)) { isEntityCollection = false; break; } Entity e = (Entity) object; if (object instanceof EntityReference) { e = DatabaseUtil.getCurrentEntityManager().find(EntityHelper.getRealClass(e), e.getId()); } resolved.add(e); } if (isEntityCollection) { PropertyHelper.set(entity, name, resolved); } } } } }
From source file:nl.strohalm.cyclos.utils.hibernate.HibernateQueryHandler.java
@SuppressWarnings("unchecked") public void resolveReferences(final Entity entity) { final ClassMetadata meta = getClassMetaData(entity); final String[] names = meta.getPropertyNames(); final Type[] types = meta.getPropertyTypes(); for (int i = 0; i < types.length; i++) { final Type type = types[i]; final String name = names[i]; if (type instanceof EntityType) { // Properties that are relationships to other entities Entity rel = PropertyHelper.get(entity, name); if (rel instanceof EntityReference) { rel = getHibernateTemplate().load(EntityHelper.getRealClass(rel), rel.getId()); PropertyHelper.set(entity, name, rel); }//from ww w . j av a 2s .c om } else if (type instanceof CollectionType && !(type instanceof MapType)) { // Properties that are collections of other entities final Collection<?> current = PropertyHelper.get(entity, name); if (current != null && !(current instanceof PersistentCollection)) { // We must check that the collection is made of entities, since Hibernate supports collections os values boolean isEntityCollection = true; final Collection<Entity> resolved = ClassHelper.instantiate(current.getClass()); for (final Object object : current) { if (object != null && !(object instanceof Entity)) { isEntityCollection = false; break; } Entity e = (Entity) object; if (object instanceof EntityReference) { e = getHibernateTemplate().load(EntityHelper.getRealClass(e), e.getId()); } resolved.add(e); } if (isEntityCollection) { PropertyHelper.set(entity, name, resolved); } } } } }
From source file:org.vulpe.controller.struts.VulpeStrutsController.java
/** * Method to add detail.// w w w . j a va2 s. com * * @param collection * @since 1.0 * @throws OgnlException */ protected void doAddDetail(final Collection collection) throws OgnlException { final Map context = ActionContext.getContext().getContextMap(); final PropertyAccessor accessor = OgnlRuntime.getPropertyAccessor(collection.getClass()); final Integer index = Integer.valueOf(collection.size()); if (((vulpe.controller().type().equals(ControllerType.TABULAR) && vulpe.controller().config().getTabularConfig().isAddNewDetailsOnTop()) || (vulpe.controller().type().equals(ControllerType.MAIN) && vulpe.controller().detailConfig().isAddNewDetailsOnTop())) && VulpeValidationUtil.isNotEmpty(collection)) { final Object value = accessor.getProperty(context, collection, 0); try { final ENTITY detail = (ENTITY) value.getClass().newInstance(); vulpe.updateAuditInfo(detail); ((ArrayList<ENTITY>) collection).add(0, prepareDetail(detail)); } catch (InstantiationException e) { LOG.error(e.getMessage()); } catch (IllegalAccessException e) { LOG.error(e.getMessage()); } } else { final ENTITY detail = (ENTITY) accessor.getProperty(context, collection, index); vulpe.updateAuditInfo(detail); final ENTITY preparedDetail = prepareDetail(detail); if (!preparedDetail.equals(detail)) { accessor.setProperty(context, collection, index, preparedDetail); } } }
From source file:org.isatools.isatab.export.isatab.ISATABDBExporter.java
/** * You can initialize the class by either a list of accessions or a list of {@link Study} objects. * Here you can pass either a collection of studies or of strings. *//*from ww w. j a v a2 s. c o m*/ @SuppressWarnings("unchecked") public ISATABDBExporter(DaoFactory daoFactory, Collection studies) { // this.daoFactory = daoFactory; studyDAO = daoFactory.getStudyDAO(); entityManager = daoFactory.getEntityManager(); if (studies.isEmpty()) { studies = studyAccs = null; return; } Object first = studies.iterator().next(); if (first instanceof String) { this.studyAccs = studies; this.studies = null; } else if (first instanceof Study) { this.studyAccs = null; this.studies = studies; } else { throw new TabInternalErrorException("Wrong parameter of type" + studies.getClass().getSimpleName() + ", TABDB Exporter must be initialized with" + "either a list of accessions or a list of Study objects"); } }
From source file:com.haulmont.cuba.core.app.importexport.EntityImportExport.java
protected void importOneToManyCollectionAttribute(Entity srcEntity, Entity dstEntity, EntityImportViewProperty importViewProperty, View regularView, CommitContext commitContext, Collection<ReferenceInfo> referenceInfoList) { String propertyName = importViewProperty.getName(); MetaProperty metaProperty = srcEntity.getMetaClass().getPropertyNN(propertyName); MetaProperty inverseMetaProperty = metaProperty.getInverse(); //filteredItems collection will contain entities filtered by the row-level security Multimap<String, Object> filteredItems = ArrayListMultimap.create(); if (srcEntity instanceof BaseGenericIdEntity) { String storeName = metadata.getTools().getStoreName(srcEntity.getMetaClass()); DataStore dataStore = storeFactory.get(storeName); //row-level security works only for entities from RdbmsStore if (dataStore instanceof RdbmsStore) { filteredItems = BaseEntityInternalAccess.getFilteredData(srcEntity); }/*w w w .j a va 2 s .co m*/ } Collection<Entity> srcPropertyValue = srcEntity.getValue(propertyName); Collection<Entity> dstPropertyValue = dstEntity.getValue(propertyName); if (dstPropertyValue == null) dstPropertyValue = new ArrayList<>(); Collection<Entity> collection; try { collection = srcPropertyValue.getClass().newInstance(); } catch (Exception e) { throw new RuntimeException("Error on import entities", e); } if (srcPropertyValue != null) { for (Entity srcChildEntity : srcPropertyValue) { if (importViewProperty.getView() != null) { //create new referenced entity Entity dstChildEntity = null; for (Entity _entity : dstPropertyValue) { if (_entity.equals(srcChildEntity)) { dstChildEntity = _entity; break; } } dstChildEntity = importEntity(srcChildEntity, dstChildEntity, importViewProperty.getView(), regularView, commitContext, referenceInfoList); if (inverseMetaProperty != null) { dstChildEntity.setValue(inverseMetaProperty.getName(), dstEntity); } collection.add(dstChildEntity); } } } if (importViewProperty.getCollectionImportPolicy() == CollectionImportPolicy.REMOVE_ABSENT_ITEMS) { Collection<? extends Entity> dstValue = dstEntity.getValue(propertyName); if (dstValue != null) { Multimap<String, Object> finalFilteredItems = filteredItems; List<? extends Entity> collectionItemsToRemove = dstValue.stream().filter( entity -> !collection.contains(entity) && (finalFilteredItems == null || !finalFilteredItems .containsValue(referenceToEntitySupport.getReferenceId(entity)))) .collect(Collectors.toList()); for (Entity _entity : collectionItemsToRemove) { commitContext.addInstanceToRemove(_entity); } } } dstEntity.setValue(propertyName, collection); }
From source file:com.haulmont.cuba.core.app.importexport.EntityImportExport.java
/** * Method finds and set a reference value to the entity or throws EntityImportException if ERROR_ON_MISSING policy * is violated//w ww. j av a2 s.c o m */ protected void processReferenceInfo(ReferenceInfo referenceInfo, CommitContext commitContext, Set<Entity> loadedEntities) { Entity entity = referenceInfo.getEntity(); String propertyName = referenceInfo.getViewProperty().getName(); MetaProperty metaProperty = entity.getMetaClass().getPropertyNN(propertyName); if (metaProperty.getRange().getCardinality() == Range.Cardinality.MANY_TO_MANY) { Collection<Entity> propertyValue = (Collection<Entity>) referenceInfo.getPropertyValue(); if (propertyValue == null) { entity.setValue(propertyName, null); return; } Collection<Entity> collection; try { collection = propertyValue.getClass().newInstance(); } catch (Exception e) { throw new RuntimeException("Error on import entities", e); } for (Entity childEntity : propertyValue) { Entity entityFromLoadedEntities = findEntityInCollection(loadedEntities, childEntity); if (entityFromLoadedEntities != null) { collection.add(entityFromLoadedEntities); } else { Entity entityFromCommitContext = findEntityInCollection(commitContext.getCommitInstances(), childEntity); if (entityFromCommitContext != null) { collection.add(entityFromCommitContext); } else { LoadContext<? extends Entity> ctx = LoadContext.create(childEntity.getClass()) .setSoftDeletion(false).setView(View.MINIMAL).setId(childEntity.getId()); Entity loadedReference = dataManager.load(ctx); if (loadedReference == null) { if (referenceInfo.getViewProperty() .getReferenceImportBehaviour() == ReferenceImportBehaviour.ERROR_ON_MISSING) { throw new EntityImportException("Referenced entity for property '" + propertyName + "' with id = " + entity.getId() + " is missing"); } } else { collection.add(loadedReference); loadedEntities.add(loadedReference); } } } } //keep absent collection members if we need it if (referenceInfo.getViewProperty() .getCollectionImportPolicy() == CollectionImportPolicy.KEEP_ABSENT_ITEMS) { Collection<Entity> prevCollectionValue = (Collection<Entity>) referenceInfo.getPrevPropertyValue(); if (prevCollectionValue != null) { for (Entity prevCollectionItem : prevCollectionValue) { if (!collection.contains(prevCollectionItem)) { collection.add(prevCollectionItem); } } } } entity.setValue(propertyName, collection); //row-level security works only for entities from RdbmsStore String storeName = metadata.getTools().getStoreName(entity.getMetaClass()); DataStore dataStore = storeFactory.get(storeName); if (dataStore instanceof RdbmsStore && !referenceInfo.isCreateOp()) { //restore filtered data, otherwise they will be lost try (Transaction tx = persistence.getTransaction()) { persistenceSecurity.checkSecurityToken((BaseGenericIdEntity<?>) entity, null); persistenceSecurity.restoreSecurityStateAndFilteredData((BaseGenericIdEntity<?>) entity); tx.commit(); } } //end of many-to-many processing block } else { //all other reference types (except many-to-many) Entity propertyValue = (Entity) referenceInfo.getPropertyValue(); if (propertyValue == null) { entity.setValue(propertyName, null); //in case of NULL value we must delete COMPOSITION entities if (metaProperty.getType() == MetaProperty.Type.COMPOSITION) { Object prevPropertyValue = referenceInfo.getPrevPropertyValue(); if (prevPropertyValue != null) { commitContext.addInstanceToRemove((Entity) prevPropertyValue); } } } else { Entity entityFromLoadedEntities = findEntityInCollection(loadedEntities, propertyValue); if (entityFromLoadedEntities != null) { entity.setValue(propertyName, entityFromLoadedEntities); } else { Entity entityFromCommitContext = findEntityInCollection(commitContext.getCommitInstances(), propertyValue); if (entityFromCommitContext != null) { entity.setValue(propertyName, entityFromCommitContext); } else { LoadContext<? extends Entity> ctx = LoadContext.create(propertyValue.getClass()) .setSoftDeletion(false).setId(propertyValue.getId()); dataManager.load(ctx); Entity loadedReference = dataManager.load(ctx); if (loadedReference == null) { if (referenceInfo.getViewProperty() .getReferenceImportBehaviour() == ReferenceImportBehaviour.ERROR_ON_MISSING) { throw new EntityImportException("Referenced entity for property '" + propertyName + "' with id = " + propertyValue.getId() + " is missing"); } } else { entity.setValue(propertyName, loadedReference); loadedEntities.add(loadedReference); } } } } } }