Example usage for java.io Serializable getClass

List of usage examples for java.io Serializable getClass

Introduction

In this page you can find the example usage for java.io Serializable getClass.

Prototype

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

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.alfresco.repo.node.getchildren.GetChildrenCannedQueryTest.java

private void sortAndCheck(NodeRef parentNodeRef, QName sortPropQName, boolean sortAscending) {
    List<Pair<QName, Boolean>> sortPairs = new ArrayList<Pair<QName, Boolean>>(1);
    sortPairs.add(new Pair<QName, Boolean>(sortPropQName, sortAscending));

    PagingResults<NodeRef> results = list(parentNodeRef, -1, -1, 0, null, null, sortPairs);

    int count = results.getPage().size();
    assertTrue(count > 3);//from   w  w w.j a  va 2 s .  c o  m

    if (logger.isInfoEnabled()) {
        logger.info("testSorting: " + count + " items [" + sortPropQName + ","
                + (sortAscending ? " ascending" : " descending") + "]");
    }

    Collator collator = AlfrescoCollator.getInstance(I18NUtil.getContentLocale());

    // check order
    Serializable prevVal = null;
    NodeRef prevNodeRef = null;
    int currentIteration = 0;

    boolean allValsNull = true;

    for (NodeRef nodeRef : results.getPage()) {
        currentIteration++;

        Serializable val = null;

        if (sortPropQName.equals(GetChildrenCannedQuery.SORT_QNAME_CONTENT_SIZE)
                || sortPropQName.equals(GetChildrenCannedQuery.SORT_QNAME_CONTENT_MIMETYPE)) {
            // content data properties (size or mimetype)
            ContentData cd = (ContentData) nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT);
            if (cd != null) {
                if (sortPropQName.equals(GetChildrenCannedQuery.SORT_QNAME_CONTENT_SIZE)) {
                    val = cd.getSize();
                } else if (sortPropQName.equals(GetChildrenCannedQuery.SORT_QNAME_CONTENT_MIMETYPE)) {
                    val = cd.getMimetype();
                }
            }
        } else if (sortPropQName.equals(GetChildrenCannedQuery.SORT_QNAME_NODE_TYPE)) {
            val = nodeService.getType(nodeRef);
        } else if (sortPropQName.equals(GetChildrenCannedQuery.SORT_QNAME_NODE_IS_FOLDER)) {
            val = dictionaryService.isSubClass(nodeService.getType(nodeRef), ContentModel.TYPE_FOLDER);
        } else {
            val = nodeService.getProperty(nodeRef, sortPropQName);
        }

        if (logger.isInfoEnabled()) {
            logger.info("testSorting:     [" + nodeRef + ", " + val + "]");
        }

        int result = 0;

        if (val != null) {
            allValsNull = false;
        }

        if (prevVal == null) {
            result = (val == null ? 0 : 1);
        } else if (val == null) {
            result = -1;
        } else {
            if (val instanceof Date) {
                result = ((Date) val).compareTo((Date) prevVal);
            } else if (val instanceof String) {
                result = collator.compare((String) val, (String) prevVal);
            } else if (val instanceof Long) {
                result = ((Long) val).compareTo((Long) prevVal);
            } else if (val instanceof Integer) {
                result = ((Integer) val).compareTo((Integer) prevVal);
            } else if (val instanceof QName) {
                result = ((QName) val).compareTo((QName) prevVal);
            } else if (val instanceof Boolean) {
                result = ((Boolean) val).compareTo((Boolean) prevVal);
            } else {
                fail("Unsupported sort type (" + nodeRef + "): " + val.getClass().getName());
            }

            String prevName = (String) nodeService.getProperty(prevNodeRef, ContentModel.PROP_NAME);
            String currName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);

            if (!sortAscending) {
                assertTrue("Not descending: " + result + "\n" + "   Iteration: " + currentIteration + " out of "
                        + count + "\n" + "   Previous:  " + prevNodeRef + " had " + prevVal + " (" + prevName
                        + ")\n" + "   Current :  " + nodeRef + " had " + val + " (" + currName + ")",
                        result <= 0);
            } else {
                assertTrue("Not ascending: " + result + "\n" + "   Iteration: " + currentIteration + " out of "
                        + count + "\n" + "   Previous:  " + prevNodeRef + " had " + prevVal + " (" + prevName
                        + ")\n" + "   Current :  " + nodeRef + " had " + val + " (" + currName + ")",
                        result >= 0);
            }
        }
        prevVal = val;
        prevNodeRef = nodeRef;
    }

    assertFalse("All values were null", allValsNull);
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java

@Override
public Serializable createPopulatedInstance(Serializable instance, Entity entity,
        Map<String, FieldMetadata> unfilteredProperties, Boolean setId, Boolean validateUnsubmittedProperties)
        throws ValidationException {
    final Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(unfilteredProperties);
    FieldManager fieldManager = getFieldManager();
    boolean handled = false;
    for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
        FieldProviderResponse response = fieldPersistenceProvider
                .filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
        if (FieldProviderResponse.NOT_HANDLED != response) {
            handled = true;//w w w. java2 s . c  om
        }
        if (FieldProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity),
                unfilteredProperties);
    }
    //Order media field, map field and rule builder fields last, as they will have some validation components that depend on previous values
    Property[] sortedProperties = entity.getProperties();
    Arrays.sort(sortedProperties, new Comparator<Property>() {
        @Override
        public int compare(Property o1, Property o2) {
            BasicFieldMetadata mo1 = (BasicFieldMetadata) mergedProperties.get(o1.getName());
            BasicFieldMetadata mo2 = (BasicFieldMetadata) mergedProperties.get(o2.getName());
            boolean isLate1 = mo1 != null && mo1.getFieldType() != null && mo1.getName() != null
                    && (SupportedFieldType.RULE_SIMPLE == mo1.getFieldType()
                            || SupportedFieldType.RULE_WITH_QUANTITY == mo1.getFieldType()
                            || SupportedFieldType.MEDIA == mo1.getFieldType()
                            || o1.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            boolean isLate2 = mo2 != null && mo2.getFieldType() != null && mo2.getName() != null
                    && (SupportedFieldType.RULE_SIMPLE == mo2.getFieldType()
                            || SupportedFieldType.RULE_WITH_QUANTITY == mo2.getFieldType()
                            || SupportedFieldType.MEDIA == mo2.getFieldType()
                            || o2.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            if (isLate1 && !isLate2) {
                return 1;
            } else if (!isLate1 && isLate2) {
                return -1;
            }
            return 0;
        }
    });
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager()
            .unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        RuntimeException entityPersistenceException = null;
        for (Property property : sortedProperties) {
            BasicFieldMetadata metadata = (BasicFieldMetadata) mergedProperties.get(property.getName());
            Class<?> returnType;
            if (!property.getName().contains(FieldManager.MAPFIELDSEPARATOR)
                    && !property.getName().startsWith("__")) {
                Field field = fieldManager.getField(instance.getClass(), property.getName());
                if (field == null) {
                    LOG.debug("Unable to find a bean property for the reported property: " + property.getName()
                            + ". Ignoring property.");
                    continue;
                }
                returnType = field.getType();
            } else {
                if (metadata == null) {
                    LOG.debug("Unable to find a metadata property for the reported property: "
                            + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = getMapFieldType(instance, fieldManager, property);
                if (returnType == null) {
                    returnType = getBasicBroadleafType(metadata.getFieldType());
                }
            }
            if (returnType == null) {
                throw new IllegalAccessException(
                        "Unable to determine the value type for the property (" + property.getName() + ")");
            }
            String value = property.getValue();
            if (metadata != null) {
                Boolean mutable = metadata.getMutable();
                Boolean readOnly = metadata.getReadOnly();

                if (metadata.getFieldType().equals(SupportedFieldType.BOOLEAN)) {
                    if (value == null) {
                        value = "false";
                    }
                }

                if ((mutable == null || mutable) && (readOnly == null || !readOnly)) {
                    if (value != null) {
                        handled = false;
                        PopulateValueRequest request = new PopulateValueRequest(setId, fieldManager, property,
                                metadata, returnType, value, persistenceManager, this);

                        boolean attemptToPopulate = true;
                        for (PopulateValueRequestValidator validator : populateValidators) {
                            PropertyValidationResult validationResult = validator.validate(request, instance);
                            if (!validationResult.isValid()) {
                                entity.addValidationError(property.getName(),
                                        validationResult.getErrorMessage());
                                attemptToPopulate = false;
                            }
                        }

                        if (attemptToPopulate) {
                            try {
                                boolean isBreakDetected = false;
                                for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                    if (!isBreakDetected || fieldPersistenceProvider.alwaysRun()) {
                                        FieldProviderResponse response = fieldPersistenceProvider
                                                .populateValue(request, instance);
                                        if (FieldProviderResponse.NOT_HANDLED != response) {
                                            handled = true;
                                        }
                                        if (FieldProviderResponse.HANDLED_BREAK == response) {
                                            isBreakDetected = true;
                                        }
                                    }
                                }
                                if (!handled) {
                                    defaultFieldPersistenceProvider.populateValue(
                                            new PopulateValueRequest(setId, fieldManager, property, metadata,
                                                    returnType, value, persistenceManager, this),
                                            instance);
                                }
                            } catch (ParentEntityPersistenceException
                                    | javax.validation.ValidationException e) {
                                entityPersistenceException = e;
                                cleanupFailedPersistenceAttempt(instance);
                                break;
                            }
                        }
                    } else {
                        try {
                            if (fieldManager.getFieldValue(instance, property.getName()) != null
                                    && (metadata.getFieldType() != SupportedFieldType.ID || setId)
                                    && metadata.getFieldType() != SupportedFieldType.PASSWORD) {
                                if (fieldManager.getFieldValue(instance, property.getName()) != null) {
                                    property.setIsDirty(true);
                                }
                                fieldManager.setFieldValue(instance, property.getName(), null);
                            }
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                }
            }
        }
        validate(entity, instance, mergedProperties, validateUnsubmittedProperties);
        //if validation failed, refresh the current instance so that none of the changes will be persisted
        if (entity.isValidationFailure()) {
            //only refresh the instance if it was managed to begin with
            if (persistenceManager.getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
                persistenceManager.getDynamicEntityDao().refresh(instance);
            }

            //re-initialize the valid properties for the entity in order to deal with the potential of not
            //completely sending over all checkbox/radio fields
            List<Serializable> entityList = new ArrayList<Serializable>(1);
            entityList.add(instance);
            Entity invalid = getRecords(mergedProperties, entityList, null, null)[0];
            invalid.setPropertyValidationErrors(entity.getPropertyValidationErrors());
            invalid.overridePropertyValues(entity);

            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, List<String>> entry : invalid.getPropertyValidationErrors().entrySet()) {
                Iterator<String> itr = entry.getValue().iterator();
                while (itr.hasNext()) {
                    sb.append(entry.getKey());
                    sb.append(" : ");
                    sb.append(itr.next());
                    if (itr.hasNext()) {
                        sb.append(" / ");
                    }
                }
            }

            throw new ValidationException(invalid, "The entity has failed validation - " + sb.toString());
        } else if (entityPersistenceException != null) {
            throw ExceptionHelper.refineException(entityPersistenceException.getCause());
        } else {
            fieldManager.persistMiddleEntities();
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } finally {
        session.setFlushMode(originalFlushMode);
    }
    return instance;
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

/**
 * Serializes and packages an intercepted change in object state.
 * <p>/*from   w  ww.  ja v  a  2 s  .c  o m*/
 * IMPORTANT serialization notes:
 * <p>
 * Transient Properties. Transients are not serialized/journalled. Marking an object property as
 * transient is the supported way of designating it as something not to be recorded into the
 * journal.
 * <p/>
 * Hibernate Identity property. A property designated in Hibernate as identity (i.e. primary
 * key) *is* not serialized. This is because sync does not enforce global uniqueness of database
 * primary keys. Instead, custom uuid property is used. This allows us to continue to use native
 * types for 'traditional' entity relationships.
 *
 * @param entity The object changed.
 * @param currentState Array containing data for each field in the object as they will be saved.
 * @param propertyNames Array containing name for each field in the object, corresponding to
 *            currentState.
 * @param types Array containing Type of the field in the object, corresponding to currentState.
 * @param state SyncItemState, e.g. NEW, UPDATED, DELETED
 * @param id Value of the identifier for this entity
 */
protected void packageObject(OpenmrsObject entity, Object[] currentState, String[] propertyNames, Type[] types,
        Serializable id, SyncItemState state) throws SyncException {

    String objectUuid = null;
    String originalRecordUuid = null;
    Set<String> transientProps = null;
    String infoMsg = null;

    ClassMetadata data = null;
    String idPropertyName = null;
    org.hibernate.tuple.IdentifierProperty idPropertyObj = null;

    // The container of values to be serialized:
    // Holds tuples of <property-name> -> {<property-type-name>,
    // <property-value as string>}
    HashMap<String, PropertyClassValue> values = new HashMap<String, PropertyClassValue>();

    try {
        objectUuid = entity.getUuid();

        // pull-out sync-network wide change id for the sync *record* (not the entity itself),
        // if one was already assigned (i.e. this change is coming from some other server)
        originalRecordUuid = getSyncRecord().getOriginalUuid();

        if (log.isDebugEnabled()) {
            // build up a starting msg for all logging:
            StringBuilder sb = new StringBuilder();
            sb.append("In PackageObject, entity type:");
            sb.append(entity.getClass().getName());
            sb.append(", entity uuid:");
            sb.append(objectUuid);
            sb.append(", originalUuid uuid:");
            sb.append(originalRecordUuid);
            log.debug(sb.toString());
        }

        // Transient properties are not serialized.
        transientProps = new HashSet<String>();
        for (Field f : entity.getClass().getDeclaredFields()) {
            if (Modifier.isTransient(f.getModifiers())) {
                transientProps.add(f.getName());
                if (log.isDebugEnabled())
                    log.debug("The field " + f.getName() + " is transient - so we won't serialize it");
            }
        }

        /*
         * Retrieve metadata for this type; we need to determine what is the
         * PK field for this type. We need to know this since PK values are
         * *not* journalled; values of primary keys are assigned where
         * physical DB records are created. This is so to avoid issues with
         * id collisions.
         *
         * In case of <generator class="assigned" />, the Identifier
         * property is already assigned value and needs to be journalled.
         * Also, the prop will *not* be part of currentState,thus we need to
         * pull it out with reflection/metadata.
         */
        data = getSessionFactory().getClassMetadata(entity.getClass());
        if (data.hasIdentifierProperty()) {
            idPropertyName = data.getIdentifierPropertyName();
            idPropertyObj = ((org.hibernate.persister.entity.AbstractEntityPersister) data).getEntityMetamodel()
                    .getIdentifierProperty();

            if (id != null && idPropertyObj.getIdentifierGenerator() != null
                    && (idPropertyObj.getIdentifierGenerator() instanceof org.hibernate.id.Assigned
                    //   || idPropertyObj.getIdentifierGenerator() instanceof org.openmrs.api.db.hibernate.NativeIfNotAssignedIdentityGenerator
                    )) {
                // serialize value as string
                values.put(idPropertyName, new PropertyClassValue(id.getClass().getName(), id.toString()));
            }
        } else if (data.getIdentifierType() instanceof EmbeddedComponentType) {
            // if we have a component identifier type (like AlertRecipient),
            // make
            // sure we include those properties
            EmbeddedComponentType type = (EmbeddedComponentType) data.getIdentifierType();
            for (int i = 0; i < type.getPropertyNames().length; i++) {
                String propertyName = type.getPropertyNames()[i];
                Object propertyValue = type.getPropertyValue(entity, i, org.hibernate.EntityMode.POJO);
                addProperty(values, entity, type.getSubtypes()[i], propertyName, propertyValue, infoMsg);
            }
        }

        /*
         * Loop through all the properties/values and put in a hash for
         * duplicate removal
         */
        for (int i = 0; i < types.length; i++) {
            String typeName = types[i].getName();
            if (log.isDebugEnabled())
                log.debug("Processing, type: " + typeName + " Field: " + propertyNames[i]);

            if (propertyNames[i].equals(idPropertyName) && log.isInfoEnabled())
                log.debug(infoMsg + ", Id for this class: " + idPropertyName + " , value:" + currentState[i]);

            if (currentState[i] != null) {
                // is this the primary key or transient? if so, we don't
                // want to serialize
                if (propertyNames[i].equals(idPropertyName)
                        || ("personId".equals(idPropertyName) && "patientId".equals(propertyNames[i]))
                        //|| ("personId".equals(idPropertyName) && "userId".equals(propertyNames[i]))
                        || transientProps.contains(propertyNames[i])) {
                    // if (log.isInfoEnabled())
                    log.debug("Skipping property (" + propertyNames[i]
                            + ") because it's either the primary key or it's transient.");

                } else {

                    addProperty(values, entity, types[i], propertyNames[i], currentState[i], infoMsg);
                }
            } else {
                // current state null -- skip
                if (log.isDebugEnabled())
                    log.debug("Field Type: " + typeName + " Field Name: " + propertyNames[i]
                            + " is null, skipped");
            }
        }

        /*
         * Now serialize the data identified and put in the value-map
         */
        // Setup the serialization data structures to hold the state
        Package pkg = new Package();
        String className = entity.getClass().getName();
        Record xml = pkg.createRecordForWrite(className);
        Item entityItem = xml.getRootItem();

        // loop through the map of the properties that need to be serialized
        for (Map.Entry<String, PropertyClassValue> me : values.entrySet()) {
            String property = me.getKey();

            // if we are processing onDelete event all we need is uuid
            if ((state == SyncItemState.DELETED) && (!"uuid".equals(property))) {
                continue;
            }

            try {
                PropertyClassValue pcv = me.getValue();
                appendRecord(xml, entity, entityItem, property, pcv.getClazz(), pcv.getValue());
            } catch (Exception e) {
                String msg = "Could not append attribute. Error while processing property: " + property + " - "
                        + e.getMessage();
                throw (new SyncException(msg, e));
            }
        }

        values.clear(); // Be nice to GC

        if (objectUuid == null)
            throw new SyncException("uuid is null for: " + className + " with id: " + id);

        /*
         * Create SyncItem and store change in SyncRecord kept in
         * ThreadLocal.
         */
        SyncItem syncItem = new SyncItem();
        syncItem.setKey(new SyncItemKey<String>(objectUuid, String.class));
        syncItem.setState(state);
        syncItem.setContent(xml.toStringAsDocumentFragment());
        syncItem.setContainedType(entity.getClass());

        if (log.isDebugEnabled())
            log.debug("Adding SyncItem to SyncRecord");

        getSyncRecord().addItem(syncItem);
        getSyncRecord().addContainedClass(entity.getClass().getName());

        // set the originating uuid for the record: do this once per Tx;
        // else we may end up with empty string
        if (getSyncRecord().getOriginalUuid() == null || "".equals(getSyncRecord().getOriginalUuid())) {
            getSyncRecord().setOriginalUuid(originalRecordUuid);
        }
    } catch (SyncException ex) {
        log.error("Journal error\n", ex);
        throw (ex);
    } catch (Exception e) {
        log.error("Journal error\n", e);
        throw (new SyncException("Error in interceptor, see log messages and callstack.", e));
    }

    return;
}

From source file:org.bonitasoft.engine.api.impl.ProcessAPIImpl.java

protected List<Operation> createSetDataOperation(final long processDefinitionId,
        final Map<String, Serializable> initialVariables) throws ProcessExecutionException {
    final ClassLoaderService classLoaderService = getTenantAccessor().getClassLoaderService();
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    final List<Operation> operations = new ArrayList<Operation>();
    try {//from   w ww .j av a2 s .  c o  m
        final ClassLoader localClassLoader = classLoaderService.getLocalClassLoader(ScopeType.PROCESS.name(),
                processDefinitionId);
        Thread.currentThread().setContextClassLoader(localClassLoader);
        if (initialVariables != null) {
            for (final Entry<String, Serializable> initialVariable : initialVariables.entrySet()) {
                final String name = initialVariable.getKey();
                final Serializable value = initialVariable.getValue();
                final Expression expression = new ExpressionBuilder().createExpression(name, name,
                        value.getClass().getName(), ExpressionType.TYPE_INPUT);
                final Operation operation = new OperationBuilder().createSetDataOperation(name, expression);
                operations.add(operation);
            }
        }
    } catch (final SClassLoaderException cle) {
        throw new ProcessExecutionException(cle);
    } catch (final InvalidExpressionException iee) {
        throw new ProcessExecutionException(iee);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
    return operations;
}

From source file:org.bonitasoft.engine.api.impl.ProcessAPIImpl.java

private void verifyTypeOfNewDataValue(final SDataInstance sDataInstance, final Serializable dataValue)
        throws UpdateException {
    final String dataClassName = sDataInstance.getClassName();
    Class<?> dataClass;/*from w w w . ja v a 2s  . co  m*/
    try {
        dataClass = Class.forName(dataClassName);
    } catch (final ClassNotFoundException e) {
        throw new UpdateException(e);
    }
    if (!dataClass.isInstance(dataValue)) {
        final UpdateException e = new UpdateException("The type of new value [" + dataValue.getClass().getName()
                + "] is not compatible with the type of the data.");
        e.setDataName(sDataInstance.getName());
        e.setDataClassName(dataClassName);
        throw e;
    }
}

From source file:de.fme.alfresco.repo.web.scripts.datalist.DataListDownloadWebScript.java

@SuppressWarnings("deprecation")
@Override/*from ww  w  .  j a  v a 2  s.com*/
protected void populateBody(Object resource, Workbook workbook, Sheet sheet, List<QName> properties)
        throws IOException {
    NodeRef list = (NodeRef) resource;
    List<NodeRef> items = getItems(list);

    // Our various formats
    DataFormat formatter = workbook.createDataFormat();
    CreationHelper createHelper = workbook.getCreationHelper();

    CellStyle styleInt = workbook.createCellStyle();
    styleInt.setDataFormat(formatter.getFormat("0"));
    CellStyle styleDate = workbook.createCellStyle();
    styleDate.setDataFormat(formatter.getFormat("yyyy-mm-dd"));
    CellStyle styleDouble = workbook.createCellStyle();
    styleDouble.setDataFormat(formatter.getFormat("General"));
    CellStyle styleNewLines = workbook.createCellStyle();
    styleNewLines.setWrapText(true);

    CellStyle hlink_style = workbook.createCellStyle();
    Font hlink_font = workbook.createFont();
    hlink_font.setUnderline(Font.U_SINGLE);
    hlink_font.setColor(IndexedColors.BLUE.getIndex());
    hlink_style.setFont(hlink_font);

    // Export the items
    int rowNum = 1, colNum = 0;
    for (NodeRef item : items) {
        Row r = sheet.createRow(rowNum);

        colNum = 0;
        for (QName prop : properties) {
            Cell c = r.createCell(colNum);

            Serializable val = nodeService.getProperty(item, prop);
            if (val == null) {
                // Is it an association, or just missing?
                List<AssociationRef> assocs = nodeService.getTargetAssocs(item, prop);
                Set<QName> qnames = new HashSet<QName>(1, 1.0f);
                qnames.add(prop);
                List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(item, qnames);
                if (assocs.size() > 0) {
                    StringBuffer text = new StringBuffer();
                    int lines = 1;

                    for (AssociationRef ref : assocs) {
                        NodeRef child = ref.getTargetRef();
                        QName type = nodeService.getType(child);
                        if (ContentModel.TYPE_PERSON.equals(type)) {
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_FIRSTNAME));
                            text.append(" ");
                            text.append(nodeService.getProperty(child, ContentModel.PROP_LASTNAME));
                        } else if (ContentModel.TYPE_CONTENT.equals(type)) {
                            // TODO Link to the content
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_NAME));
                            text.append(" (");
                            text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE));
                            text.append(") ");
                            /*MessageFormat.format(CONTENT_DOWNLOAD_PROP_URL, new Object[] {
                                    child.getStoreRef().getProtocol(),
                                    child.getStoreRef().getIdentifier(),
                                    child.getId(),
                                    URLEncoder.encode((String)nodeService.getProperty(child, ContentModel.PROP_TITLE)),
                                    URLEncoder.encode(ContentModel.PROP_CONTENT.toString()) });
                            */
                            /*currently only one link per cell possible
                             * Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
                             *link.setAddress("http://poi.apache.org/");
                             *c.setHyperlink(link);
                             *c.setCellStyle(hlink_style);*/
                        } else if (ApplicationModel.TYPE_FILELINK.equals(type)) {
                            NodeRef linkRef = (NodeRef) nodeService.getProperty(child,
                                    ContentModel.PROP_LINK_DESTINATION);
                            if (linkRef != null) {
                                if (text.length() > 0) {
                                    text.append('\n');
                                    lines++;
                                }
                                text.append("link to: ");
                                try {
                                    text.append(nodeService.getProperty(linkRef, ContentModel.PROP_NAME));
                                    text.append(" (");
                                    text.append(nodeService.getProperty(linkRef, ContentModel.PROP_TITLE));
                                    text.append(") ");
                                } catch (Exception e) {
                                    text.append(nodeService.getProperty(child, ContentModel.PROP_NAME));
                                    text.append(" (");
                                    text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE));
                                    text.append(") ");

                                }
                            }
                        } else {
                            System.err.println("TODO: handle " + type + " for " + child);
                        }
                    }

                    String v = text.toString();
                    c.setCellValue(v);
                    if (lines > 1) {
                        c.setCellStyle(styleNewLines);
                        r.setHeightInPoints(lines * sheet.getDefaultRowHeightInPoints());
                    }
                } else if (childAssocs.size() > 0) {
                    StringBuffer text = new StringBuffer();
                    for (ChildAssociationRef childAssociationRef : childAssocs) {
                        NodeRef child = childAssociationRef.getChildRef();
                        QName type = nodeService.getType(child);
                        if (type.equals(ForumModel.TYPE_FORUM)) {
                            List<ChildAssociationRef> topics = nodeService.getChildAssocs(child);
                            if (topics.size() > 0) {
                                ChildAssociationRef topicRef = topics.get(0);
                                List<ChildAssociationRef> comments = nodeService
                                        .getChildAssocs(topicRef.getChildRef());
                                for (ChildAssociationRef commentChildRef : comments) {
                                    NodeRef commentRef = commentChildRef.getChildRef();

                                    ContentData data = (ContentData) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CONTENT);
                                    TemplateContentData contentData = new TemplateContentData(data,
                                            ContentModel.PROP_CONTENT);

                                    String commentString = "";
                                    try {
                                        commentString = contentData.getContentAsText(commentRef, -1);
                                    } catch (Exception e) {
                                        logger.warn("failed to extract content for nodeRef " + commentRef, e);
                                    }

                                    String creator = (String) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CREATOR);
                                    NodeRef person = personService.getPerson(creator, false);
                                    if (person != null) {
                                        creator = nodeService.getProperty(person, ContentModel.PROP_FIRSTNAME)
                                                + " "
                                                + nodeService.getProperty(person, ContentModel.PROP_LASTNAME);
                                    }
                                    Date created = (Date) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CREATED);

                                    text.append(creator).append(" (")
                                            .append(DateFormatUtils.format(created, "yyyy-MM-dd"))
                                            .append("):\n ");
                                    text.append(commentString).append("\n");
                                }
                            }
                        }
                    }
                    String v = text.toString();
                    c.setCellValue(v);
                    c.setCellStyle(styleNewLines);

                } else {
                    // This property isn't set
                    c.setCellType(Cell.CELL_TYPE_BLANK);
                }
            } else {
                // Regular property, set
                if (val instanceof String) {
                    c.setCellValue((String) val);
                    c.setCellStyle(styleNewLines);
                } else if (val instanceof Date) {
                    c.setCellValue((Date) val);
                    c.setCellStyle(styleDate);
                } else if (val instanceof Integer || val instanceof Long) {
                    double v = 0.0;
                    if (val instanceof Long)
                        v = (double) (Long) val;
                    if (val instanceof Integer)
                        v = (double) (Integer) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleInt);
                } else if (val instanceof Float || val instanceof Double) {
                    double v = 0.0;
                    if (val instanceof Float)
                        v = (double) (Float) val;
                    if (val instanceof Double)
                        v = (double) (Double) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleDouble);
                } else {
                    // TODO
                    System.err.println("TODO: handle " + val.getClass().getName() + " - " + val);
                }
            }

            colNum++;
        }

        rowNum++;
    }

    // Sensible column widths please!
    colNum = 0;
    for (QName prop : properties) {
        try {
            sheet.autoSizeColumn(colNum);
        } catch (IllegalArgumentException e) {
            sheet.setColumnWidth(colNum, 40 * 256);
        }

        colNum++;
    }
}