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.broadleafcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java

protected void extractPropertiesFromPersistentEntity(Map<String, FieldMetadata> mergedProperties,
        Serializable entity, List<Property> props) {
    FieldManager fieldManager = getFieldManager();
    try {//from  w w w  .  ja  v  a  2s  .com
        if (entity instanceof AdminMainEntity) {
            //Create an invisible property for the admin main entity name, if applicable.
            //This is useful for ToOneLookups if that ToOneLookup uses AdminMainEntity to drive
            //its display name.
            try {
                Property propertyItem = new Property();
                propertyItem.setName(AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY);
                propertyItem.setValue(((AdminMainEntity) entity).getMainEntityName());
                props.add(propertyItem);
            } catch (Exception e) {
                //do nothing here except for not add the property. Exceptions could occur when there is a validation
                //issue and some properties/relationships that are used for gleaning the main entity name end up
                //not being set
            }
        }
        for (Entry<String, FieldMetadata> entry : mergedProperties.entrySet()) {
            String property = entry.getKey();
            BasicFieldMetadata metadata = (BasicFieldMetadata) entry.getValue();
            if (Class.forName(metadata.getInheritedFromType()).isAssignableFrom(entity.getClass())
                    || entity.getClass().isAssignableFrom(Class.forName(metadata.getInheritedFromType()))) {
                boolean proceed = true;
                if (property.contains(".")) {
                    StringTokenizer tokens = new StringTokenizer(property, ".");
                    Object testObject = entity;
                    while (tokens.hasMoreTokens()) {
                        String token = tokens.nextToken();
                        if (tokens.hasMoreTokens()) {
                            try {
                                testObject = fieldManager.getFieldValue(testObject, token);
                            } catch (FieldNotAvailableException e) {
                                proceed = false;
                                break;
                            }
                            if (testObject == null) {
                                Property propertyItem = new Property();
                                propertyItem.setName(property);
                                if (props.contains(propertyItem)) {
                                    proceed = false;
                                    break;
                                }
                                propertyItem.setValue(null);
                                props.add(propertyItem);
                                proceed = false;
                                break;
                            }
                        }
                    }
                }
                if (!proceed) {
                    continue;
                }

                boolean isFieldAccessible = true;
                Object value = null;
                try {
                    value = fieldManager.getFieldValue(entity, property);
                } catch (FieldNotAvailableException e) {
                    isFieldAccessible = false;
                }
                checkField: {
                    if (isFieldAccessible) {
                        Property propertyItem = new Property();
                        propertyItem.setName(property);
                        if (props.contains(propertyItem)) {
                            continue;
                        }
                        props.add(propertyItem);
                        String displayVal = propertyItem.getDisplayValue();
                        boolean handled = false;
                        for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                            FieldProviderResponse response = fieldPersistenceProvider
                                    .extractValue(
                                            new ExtractValueRequest(props, fieldManager, metadata, value,
                                                    displayVal, persistenceManager, this, entity),
                                            propertyItem);
                            if (FieldProviderResponse.NOT_HANDLED != response) {
                                handled = true;
                            }
                            if (FieldProviderResponse.HANDLED_BREAK == response) {
                                break;
                            }
                        }
                        if (!handled) {
                            defaultFieldPersistenceProvider
                                    .extractValue(
                                            new ExtractValueRequest(props, fieldManager, metadata, value,
                                                    displayVal, persistenceManager, this, entity),
                                            propertyItem);
                        }
                        break checkField;
                    }
                    //try a direct property acquisition via reflection
                    try {
                        String strVal = null;
                        Method method;
                        try {
                            //try a 'get' prefixed mutator first
                            String temp = "get" + property.substring(0, 1).toUpperCase()
                                    + property.substring(1, property.length());
                            method = entity.getClass().getMethod(temp, new Class[] {});
                        } catch (NoSuchMethodException e) {
                            method = entity.getClass().getMethod(property, new Class[] {});
                        }
                        value = method.invoke(entity, new String[] {});
                        Property propertyItem = new Property();
                        propertyItem.setName(property);
                        if (props.contains(propertyItem)) {
                            continue;
                        }
                        props.add(propertyItem);
                        if (value == null) {
                            strVal = null;
                        } else {
                            if (Date.class.isAssignableFrom(value.getClass())) {
                                strVal = getSimpleDateFormatter().format((Date) value);
                            } else if (Timestamp.class.isAssignableFrom(value.getClass())) {
                                strVal = getSimpleDateFormatter()
                                        .format(new Date(((Timestamp) value).getTime()));
                            } else if (Calendar.class.isAssignableFrom(value.getClass())) {
                                strVal = getSimpleDateFormatter().format(((Calendar) value).getTime());
                            } else if (Double.class.isAssignableFrom(value.getClass())) {
                                strVal = getDecimalFormatter().format(value);
                            } else if (BigDecimal.class.isAssignableFrom(value.getClass())) {
                                strVal = getDecimalFormatter().format(value);
                            } else {
                                strVal = value.toString();
                            }
                        }
                        propertyItem.setValue(strVal);
                    } catch (NoSuchMethodException e) {
                        LOG.debug("Unable to find a specified property in the entity: " + property);
                        //do nothing - this property is simply not in the bean
                    }
                }
            }
        }
    } catch (ClassNotFoundException e) {
        throw new PersistenceException(e);
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InvocationTargetException e) {
        throw new PersistenceException(e);
    }
}

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

private void filterByPropAndCheck(NodeRef parentNodeRef, QName filterPropQName, String filterVal,
        FilterTypeString filterType, int expectedCount) {
    FilterProp filter = new FilterPropString(filterPropQName, filterVal, filterType);
    List<FilterProp> filterProps = new ArrayList<FilterProp>(1);
    filterProps.add(filter);/*from   w  ww.j  a  v a 2 s . c  o  m*/

    // note: currently inclusive filter
    PagingResults<NodeRef> results = list(parentNodeRef, -1, -1, 0, null, filterProps, null);

    int count = results.getPage().size();
    assertEquals(expectedCount, count);

    if (logger.isInfoEnabled()) {
        logger.info("testFiltering: " + count + " items [" + filterPropQName + "," + filterVal + ","
                + filterType + "]");
    }

    for (NodeRef nodeRef : results.getPage()) {
        Serializable propVal = nodeService.getProperty(nodeRef, filterPropQName);

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

        if (propVal instanceof String) {
            String val = (String) propVal;
            switch (filterType) {
            case STARTSWITH:
                if (!val.startsWith(filterVal)) {
                    fail("Unexpected val: " + val + " (does not 'startWith': " + filterVal + ")");
                }
                break;
            case STARTSWITH_IGNORECASE:
                if (!val.toLowerCase().startsWith(filterVal.toLowerCase())) {
                    fail("Unexpected val: " + val + " (does not 'startWithIgnoreCase': " + filterVal + ")");
                }
                break;
            case EQUALS:
                if (!val.equals(filterVal)) {
                    fail("Unexpected val: " + val + " (does not 'equal': " + filterVal + ")");
                }
                break;
            case EQUALS_IGNORECASE:
                if (!val.equalsIgnoreCase(filterVal)) {
                    fail("Unexpected val: " + val + " (does not 'equalIgnoreCase': " + filterVal + ")");
                }
                break;
            default:
            }
        } else {
            fail("Unsupported filter type: " + propVal.getClass().getName());
        }
    }
}

From source file:org.openbaton.sdk.api.util.RestRequest.java

public Serializable requestPost(final String id, final Serializable object) throws SDKException {
    CloseableHttpResponse response = null;
    HttpPost httpPost = null;/*from w w  w  .j  a  va2  s  .c  o  m*/
    try {
        log.trace("Object is: " + object);
        String fileJSONNode;
        if (object instanceof String)
            fileJSONNode = (String) object;
        else
            fileJSONNode = mapper.toJson(object);

        log.trace("sending: " + fileJSONNode.toString());
        log.debug("baseUrl: " + baseUrl);
        log.debug("id: " + baseUrl + "/" + id);

        try {
            checkToken();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new SDKException("Could not get token", e);
        }

        // call the api here
        log.debug("Executing post on: " + this.baseUrl + "/" + id);
        httpPost = new HttpPost(this.baseUrl + "/" + id);
        if (!(object instanceof String)) {
            httpPost.setHeader(new BasicHeader("accept", "application/json"));
            httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
        }
        httpPost.setHeader(new BasicHeader("project-id", projectId));
        if (token != null)
            httpPost.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", "")));
        httpPost.setEntity(new StringEntity(fileJSONNode));

        response = httpClient.execute(httpPost);

        // check response status
        checkStatus(response, HttpURLConnection.HTTP_CREATED);
        // return the response of the request
        String result = "";
        if (response.getEntity() != null)
            result = EntityUtils.toString(response.getEntity());

        if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) {
            if (object instanceof String)
                return result;
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(result);
            result = mapper.toJson(jsonElement);
            log.trace("received: " + result);

            log.trace("Casting it into: " + object.getClass());
            return mapper.fromJson(result, object.getClass());
        }
        response.close();
        httpPost.releaseConnection();
        return null;
    } catch (IOException e) {
        // catch request exceptions here
        log.error(e.getMessage(), e);
        if (httpPost != null)
            httpPost.releaseConnection();
        throw new SDKException("Could not http-post or open the object properly", e);
    } catch (SDKException e) {
        if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            token = null;
            if (httpPost != null)
                httpPost.releaseConnection();
            return requestPost(id);
        } else if (response != null) {
            if (httpPost != null)
                httpPost.releaseConnection();
            throw new SDKException("Status is " + response.getStatusLine().getStatusCode());
        } else {
            throw e;
        }
    }
}

From source file:org.sparkcommerce.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 {
    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;//from  w  w w  .  jav a2 s.c  o m
        }
        if (FieldProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity),
                unfilteredProperties);
    }
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager()
            .unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        for (Property property : entity.getProperties()) {
            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 = getBasicSparkType(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) {
                            for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                FieldProviderResponse response = fieldPersistenceProvider.populateValue(request,
                                        instance);
                                if (FieldProviderResponse.NOT_HANDLED != response) {
                                    handled = true;
                                }
                                if (FieldProviderResponse.HANDLED_BREAK == response) {
                                    break;
                                }
                            }
                            if (!handled) {
                                defaultFieldPersistenceProvider
                                        .populateValue(
                                                new PopulateValueRequest(setId, fieldManager, property,
                                                        metadata, returnType, value, persistenceManager, this),
                                                instance);
                            }
                        }
                    } 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 {
            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:com.bluexml.side.Integration.alfresco.xforms.webscript.DataLayer.java

/**
 * Extracted from AbstractNodeService.<-- original DataLayer comment <br/>
 * /*  www.  ja  v a 2 s. co  m*/
 * @param propertyDef
 * @param pValue
 * @return
 */
@SuppressWarnings("unchecked")
private Serializable makePropertyValue(PropertyDefinition propertyDef, Serializable pValue) {
    Serializable value = pValue;
    // get property attributes
    QName propertyTypeQName = null;
    if (propertyDef == null) // property not recognised
    {
        // allow it for now - persisting excess properties can be useful
        // sometimes
        propertyTypeQName = DataTypeDefinition.ANY;
    } else {
        propertyTypeQName = propertyDef.getDataType().getName();
        // check that multi-valued properties are allowed
        boolean isMultiValued = propertyDef.isMultiValued();
        if (isMultiValued && !(value instanceof Collection)) {
            if (value != null) {
                // put the value into a collection
                // the implementation gives back a Serializable list
                value = (Serializable) Collections.singletonList(value);
            }
        } else if (!isMultiValued && (value instanceof Collection)) {
            // we only allow this case if the property type is ANY
            if (!propertyTypeQName.equals(DataTypeDefinition.ANY)) {
                throw new DictionaryException(
                        "A single-valued property of this type may not be a collection: \n" + "   Property: "
                                + propertyDef + "\n" + "   Type: " + propertyTypeQName + "\n" + "   Value: "
                                + value);
            }
        }
    }
    try {
        return convertType(propertyTypeQName, value);
    } catch (TypeConversionException e) {
        String classe = "unknown";
        if (value != null) {
            classe = value.getClass().toString();
        }
        throw new TypeConversionException(
                "The property value is not compatible with the type defined for the property: \n"
                        + "   property: " + (propertyDef == null ? "unknown" : propertyDef) + "\n"
                        + "   value: " + value + "\n" + "   value type: " + classe,
                e);
    }
}

From source file:org.rifidi.edge.rest.SensorManagerServiceRestletImpl.java

public String generateReturnString(Serializable message) {
    try {/*from ww w  . ja  v a 2  s  .c om*/
        JAXBContext jaxbContext = JAXBContext.newInstance(message.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        Writer writer = new StringWriter();
        jaxbMarshaller.marshal(message, writer);
        String content = writer.toString();
        writer.close();
        return content;
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }
}

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

@Override
public void remove(PersistencePackage persistencePackage) throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
    ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems()
            .get(PersistencePerspectiveItemType.FOREIGNKEY);
    if (foreignKey != null && !foreignKey.getMutable()) {
        throw new SecurityServiceException("Entity not mutable");
    }//from  w ww.j a  v a2  s . c o m
    try {
        Class<?>[] entities = persistenceManager
                .getPolymorphicEntities(persistencePackage.getCeilingEntityFullyQualifiedClassname());
        Map<String, FieldMetadata> mergedUnfilteredProperties = persistenceManager.getDynamicEntityDao()
                .getMergedProperties(persistencePackage.getCeilingEntityFullyQualifiedClassname(), entities,
                        foreignKey, persistencePerspective.getAdditionalNonPersistentProperties(),
                        persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY,
                        persistencePerspective.getPopulateToOneFields(),
                        persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(),
                        persistencePerspective.getConfigurationKey(), "");
        Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(mergedUnfilteredProperties);
        Object primaryKey = getPrimaryKey(entity, mergedProperties);
        Serializable instance = persistenceManager.getDynamicEntityDao()
                .retrieve(Class.forName(entity.getType()[0]), primaryKey);

        Assert.isTrue(instance != null, "Entity not found");

        switch (persistencePerspective.getOperationTypes().getRemoveType()) {
        case NONDESTRUCTIVEREMOVE:
            FieldManager fieldManager = getFieldManager();
            FieldMetadata manyToFieldMetadata = mergedUnfilteredProperties.get(foreignKey.getManyToField());
            Object foreignKeyValue = entity.getPMap().get(foreignKey.getManyToField()).getValue();
            try {
                foreignKeyValue = Long.valueOf((String) foreignKeyValue);
            } catch (NumberFormatException e) {
                LOG.warn("Foreign primary key is not of type Long, assuming String for remove lookup");
            }
            Serializable foreignInstance = persistenceManager.getDynamicEntityDao()
                    .retrieve(Class.forName(foreignKey.getForeignKeyClass()), foreignKeyValue);
            Collection collection = (Collection) fieldManager.getFieldValue(foreignInstance,
                    foreignKey.getOriginatingField());
            collection.remove(instance);
            // if this is a bi-directional @OneToMany/@ManyToOne and there is no @JoinTable (just a foreign key on
            // the @ManyToOne side) then it will not be updated. In that instance, we have to explicitly
            // set the manyTo field to null so that subsequent lookups will not find it
            if (manyToFieldMetadata instanceof BasicFieldMetadata) {
                if (BooleanUtils.isTrue(((BasicFieldMetadata) manyToFieldMetadata).getRequired())) {
                    throw new ServiceException("Could not remove from the collection as the ManyToOne side is a"
                            + " non-optional relationship. Consider changing 'optional=true' in the @ManyToOne annotation"
                            + " or nullable=true within the @JoinColumn annotation");
                }
                Field manyToField = fieldManager.getField(instance.getClass(), foreignKey.getManyToField());
                Object manyToObject = manyToField.get(instance);
                if (manyToObject != null && !(manyToObject instanceof Collection)
                        && !(manyToObject instanceof Map)) {
                    manyToField.set(instance, null);
                    instance = persistenceManager.getDynamicEntityDao().merge(instance);
                }
            }
            break;
        case BASIC:
            persistenceManager.getDynamicEntityDao().remove(instance);
            break;
        }
    } catch (Exception e) {
        throw new ServiceException("Problem removing entity : " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.core.TestSQLRepositoryQuery.java

/**
 * Make sure that even when we use a sequence, the id is a String, for compat with the rest of the framework.
 *///from   ww  w  . j  av  a  2  s .  c o  m
@Test
public void testIdType() throws Exception {
    createDocs();
    IterableQueryResult res = session.queryAndFetch("SELECT ecm:uuid, ecm:parentId FROM File", NXQL.NXQL);
    assertEquals(3, res.size());
    for (Map<String, Serializable> map : res) {
        Serializable id = map.get(NXQL.ECM_UUID);
        assertTrue(id.getClass().getName(), id instanceof String);
        Serializable parentId = map.get(NXQL.ECM_PARENTID);
        assertTrue(parentId.getClass().getName(), parentId instanceof String);
    }
    res.close();
}

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

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

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

    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);

    // 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);
                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_USERNAME));
                        } 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_TITLE));
                        } 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 {
                    // This property isn't set
                    c.setCellType(Cell.CELL_TYPE_BLANK);
                }
            } else {
                // Regular property, set
                if (val instanceof String) {
                    c.setCellValue((String) val);
                } 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) {
        sheet.autoSizeColumn(colNum);
        colNum++;
    }
}

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

@Override
public void remove(PersistencePackage persistencePackage) throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
    ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems()
            .get(PersistencePerspectiveItemType.FOREIGNKEY);
    if (foreignKey != null && !foreignKey.getMutable()) {
        throw new SecurityServiceException("Entity not mutable");
    }/*from   w  w w  .j  ava 2  s.c o m*/
    try {
        Class<?>[] entities = persistenceManager
                .getPolymorphicEntities(persistencePackage.getCeilingEntityFullyQualifiedClassname());
        Map<String, FieldMetadata> mergedUnfilteredProperties = persistenceManager.getDynamicEntityDao()
                .getMergedProperties(persistencePackage.getCeilingEntityFullyQualifiedClassname(), entities,
                        foreignKey, persistencePerspective.getAdditionalNonPersistentProperties(),
                        persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY,
                        persistencePerspective.getPopulateToOneFields(),
                        persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(),
                        persistencePerspective.getConfigurationKey(), "");
        Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(mergedUnfilteredProperties);
        Object primaryKey = getPrimaryKey(entity, mergedProperties);
        Serializable instance = persistenceManager.getDynamicEntityDao()
                .retrieve(Class.forName(entity.getType()[0]), primaryKey);

        Assert.isTrue(instance != null, "Entity not found");

        switch (persistencePerspective.getOperationTypes().getRemoveType()) {
        case NONDESTRUCTIVEREMOVE:
            FieldManager fieldManager = getFieldManager();
            FieldMetadata manyToFieldMetadata = mergedUnfilteredProperties.get(foreignKey.getManyToField());
            Object foreignKeyValue = entity.getPMap().get(foreignKey.getManyToField()).getValue();
            try {
                foreignKeyValue = Long.valueOf((String) foreignKeyValue);
            } catch (NumberFormatException e) {
                LOG.warn("Foreign primary key is not of type Long, assuming String for remove lookup");
            }
            Serializable foreignInstance = persistenceManager.getDynamicEntityDao()
                    .retrieve(Class.forName(foreignKey.getForeignKeyClass()), foreignKeyValue);
            Collection collection = (Collection) fieldManager.getFieldValue(foreignInstance,
                    foreignKey.getOriginatingField());
            collection.remove(instance);
            // if this is a bi-directional @OneToMany/@ManyToOne and there is no @JoinTable (just a foreign key on
            // the @ManyToOne side) then it will not be updated. In that instance, we have to explicitly
            // set the manyTo field to null so that subsequent lookups will not find it
            if (manyToFieldMetadata instanceof BasicFieldMetadata) {
                if (BooleanUtils.isTrue(((BasicFieldMetadata) manyToFieldMetadata).getRequired())) {
                    throw new ServiceException("Could not remove from the collection as the ManyToOne side is a"
                            + " non-optional relationship. Consider changing 'optional=true' in the @ManyToOne annotation"
                            + " or nullable=true within the @JoinColumn annotation");
                }
                //Since this is occuring on a remove persistence package, merge up-front (before making a change) for proper operation in the presence of the enterprise module
                instance = persistenceManager.getDynamicEntityDao().merge(instance);
                Field manyToField = fieldManager.getField(instance.getClass(), foreignKey.getManyToField());
                Object manyToObject = manyToField.get(instance);
                if (manyToObject != null && !(manyToObject instanceof Collection)
                        && !(manyToObject instanceof Map)) {
                    manyToField.set(instance, null);
                    instance = persistenceManager.getDynamicEntityDao().merge(instance);
                }
            }
            break;
        case BASIC:
            persistenceManager.getDynamicEntityDao().remove(instance);
            break;
        }
    } catch (Exception e) {
        throw new ServiceException("Problem removing entity : " + e.getMessage(), e);
    }
}