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.transfer.RepoPrimaryManifestProcessorImpl.java

/**
 * inject transferred/*ww  w.j a  va2s . co m*/
 */
private void injectTransferred(Map<QName, Serializable> props) {
    if (!props.containsKey(TransferModel.PROP_REPOSITORY_ID)) {
        log.debug("injecting repositoryId property");
        props.put(TransferModel.PROP_REPOSITORY_ID, header.getRepositoryId());
    }
    props.put(TransferModel.PROP_FROM_REPOSITORY_ID, header.getRepositoryId());

    /**
     * For each property
     */
    List<String> contentProps = new ArrayList<String>();
    for (Serializable value : props.values()) {
        if ((value != null) && ContentData.class.isAssignableFrom(value.getClass())) {
            ContentData srcContent = (ContentData) value;

            if (srcContent.getContentUrl() != null && !srcContent.getContentUrl().isEmpty()) {
                log.debug("adding part name to from content field");
                contentProps.add(TransferCommons.URLToPartName(srcContent.getContentUrl()));
            }
        }
    }

    props.put(TransferModel.PROP_FROM_CONTENT, (Serializable) contentProps);
}

From source file:org.apache.pluto.driver.services.container.EventProviderImpl.java

/**
 * Register an event, which should be fired within that request
 * // w  w  w . j a v  a 2 s  . c  om
 * @param qname
 * @param value
 * @throws {@link IllegalArgumentException}
 */
public void registerToFireEvent(QName qname, Serializable value) throws IllegalArgumentException {
    if (isDeclaredAsPublishingEvent(qname)) {

        if (value != null && !isValueInstanceOfDefinedClass(qname, value))
            throw new IllegalArgumentException("Payload has not the right class");

        try {

            if (value == null) {
                savedEvents.addEvent(new EventImpl(qname, value));
            } else if (!(value instanceof Serializable)) {
                throw new IllegalArgumentException("Object payload must implement Serializable");
            } else {

                Writer out = new StringWriter();

                Class clazz = value.getClass();

                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                try {
                    Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
                    JAXBContext jc = JAXBContext.newInstance(clazz);

                    Marshaller marshaller = jc.createMarshaller();

                    JAXBElement<Serializable> element = new JAXBElement<Serializable>(qname, clazz, value);
                    marshaller.marshal(element, out);
                    // marshaller.marshal(value, out);
                } finally {
                    Thread.currentThread().setContextClassLoader(cl);
                }

                if (out != null) {
                    savedEvents.addEvent(new EventImpl(qname, (Serializable) out.toString()));
                } else {
                    savedEvents.addEvent(new EventImpl(qname, value));
                }
            }
        } catch (JAXBException e) {
            // maybe there is no valid jaxb binding
            // TODO wsrp:eventHandlingFailed
            LOG.error("Event handling failed", e);
        } catch (FactoryConfigurationError e) {
            LOG.warn(e);
        }
    }
}

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

@Override
public Entity add(PersistencePackage persistencePackage) throws ServiceException {
    String[] customCriteria = persistencePackage.getCustomCriteria();
    if (customCriteria != null && customCriteria.length > 0) {
        LOG.warn(//  w w  w. j a va  2s .c  om
                "custom persistence handlers and custom criteria not supported for add types other than BASIC");
    }
    PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
    String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
    Entity entity = persistencePackage.getEntity();
    AdornedTargetList adornedTargetList = (AdornedTargetList) persistencePerspective
            .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST);
    if (!adornedTargetList.getMutable()) {
        throw new SecurityServiceException("Field is not mutable");
    }
    Entity payload;
    try {
        Class<?>[] entities = persistenceManager.getPolymorphicEntities(ceilingEntityFullyQualifiedClassname);
        Map<String, FieldMetadata> mergedPropertiesTarget = persistenceManager.getDynamicEntityDao()
                .getMergedProperties(ceilingEntityFullyQualifiedClassname, entities, null,
                        persistencePerspective.getAdditionalNonPersistentProperties(),
                        persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY,
                        persistencePerspective.getPopulateToOneFields(),
                        persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(),
                        persistencePerspective.getConfigurationKey(), "");
        Class<?>[] entities2 = persistenceManager
                .getPolymorphicEntities(adornedTargetList.getAdornedTargetEntityClassname());
        Map<String, FieldMetadata> mergedProperties = persistenceManager.getDynamicEntityDao()
                .getMergedProperties(adornedTargetList.getAdornedTargetEntityClassname(), entities2, null,
                        new String[] {}, new ForeignKey[] {}, MergedPropertyType.ADORNEDTARGETLIST, false,
                        new String[] {}, new String[] {}, null, "");

        CriteriaTransferObject ctoInserted = new CriteriaTransferObject();
        FilterAndSortCriteria filterCriteriaInsertedLinked = ctoInserted
                .get(adornedTargetList.getCollectionFieldName());
        String linkedPath;
        String targetPath;
        if (adornedTargetList.getInverse()) {
            linkedPath = adornedTargetList.getTargetObjectPath() + "."
                    + adornedTargetList.getTargetIdProperty();
            targetPath = adornedTargetList.getLinkedObjectPath() + "."
                    + adornedTargetList.getLinkedIdProperty();
        } else {
            targetPath = adornedTargetList.getTargetObjectPath() + "."
                    + adornedTargetList.getTargetIdProperty();
            linkedPath = adornedTargetList.getLinkedObjectPath() + "."
                    + adornedTargetList.getLinkedIdProperty();
        }
        filterCriteriaInsertedLinked.setFilterValue(
                entity.findProperty(adornedTargetList.getInverse() ? targetPath : linkedPath).getValue());
        FilterAndSortCriteria filterCriteriaInsertedTarget = ctoInserted
                .get(adornedTargetList.getCollectionFieldName() + "Target");
        filterCriteriaInsertedTarget.setFilterValue(
                entity.findProperty(adornedTargetList.getInverse() ? linkedPath : targetPath).getValue());
        List<FilterMapping> filterMappingsInserted = getAdornedTargetFilterMappings(persistencePerspective,
                ctoInserted, mergedProperties, adornedTargetList);
        List<Serializable> recordsInserted = getPersistentRecords(
                adornedTargetList.getAdornedTargetEntityClassname(), filterMappingsInserted,
                ctoInserted.getFirstResult(), ctoInserted.getMaxResults());
        if (recordsInserted.size() > 0) {
            payload = getRecords(mergedPropertiesTarget, recordsInserted, mergedProperties,
                    adornedTargetList.getTargetObjectPath())[0];
        } else {
            Serializable instance = createPopulatedAdornedTargetInstance(adornedTargetList, entity);
            instance = createPopulatedInstance(instance, entity, mergedProperties, false,
                    persistencePackage.isValidateUnsubmittedProperties());
            instance = createPopulatedInstance(instance, entity, mergedPropertiesTarget, false,
                    persistencePackage.isValidateUnsubmittedProperties());
            FieldManager fieldManager = getFieldManager();
            if (fieldManager.getField(instance.getClass(), "id") != null) {
                fieldManager.setFieldValue(instance, "id", null);
            }
            if (adornedTargetList.getSortField() != null) {
                // Construct a query that gets the last element in the join list ordered by the sort property. This will
                // ensure that the new record is always the last element in the list
                CriteriaTransferObject cto = new CriteriaTransferObject();
                FilterAndSortCriteria filterCriteria = cto.get(adornedTargetList.getCollectionFieldName());
                filterCriteria.setFilterValue(entity
                        .findProperty(adornedTargetList.getInverse() ? targetPath : linkedPath).getValue());
                FilterAndSortCriteria sortCriteria = cto.get(adornedTargetList.getSortField());
                // criteria for which way to sort should be the opposite of how it is normally sorted so that it is
                // always inserted at the end
                sortCriteria.setSortAscending(!adornedTargetList.getSortAscending());
                List<FilterMapping> filterMappings = getAdornedTargetFilterMappings(persistencePerspective, cto,
                        mergedProperties, adornedTargetList);
                List<Serializable> joinList = getPersistentRecords(
                        adornedTargetList.getAdornedTargetEntityClassname(), filterMappings, 0, 1);

                Object adornedLastOrdering = null;
                if (CollectionUtils.isNotEmpty(joinList)) {
                    adornedLastOrdering = fieldManager.getFieldValue(joinList.get(0),
                            adornedTargetList.getSortField());
                }
                Field sortFieldDef = fieldManager.getField(instance.getClass(),
                        adornedTargetList.getSortField());
                int add = (adornedLastOrdering == null) ? 0 : 1;
                if (sortFieldDef.getType().isAssignableFrom(Long.class)) {
                    adornedLastOrdering = (adornedLastOrdering == null) ? new Long(0) : adornedLastOrdering;
                    fieldManager.setFieldValue(instance, adornedTargetList.getSortField(),
                            new Long(((Long) adornedLastOrdering).longValue() + add));
                } else if (sortFieldDef.getType().isAssignableFrom(Integer.class)) {
                    adornedLastOrdering = (adornedLastOrdering == null) ? new Integer(0) : adornedLastOrdering;
                    fieldManager.setFieldValue(instance, adornedTargetList.getSortField(),
                            new Integer(((Integer) adornedLastOrdering).intValue() + add));
                } else if (sortFieldDef.getType().isAssignableFrom(BigDecimal.class)) {
                    adornedLastOrdering = (adornedLastOrdering == null) ? BigDecimal.ZERO : adornedLastOrdering;
                    fieldManager.setFieldValue(instance, adornedTargetList.getSortField(),
                            ((BigDecimal) adornedLastOrdering).add(new BigDecimal(add)));
                }
            }
            instance = persistenceManager.getDynamicEntityDao().merge(instance);
            persistenceManager.getDynamicEntityDao().clear();

            List<Serializable> recordsInserted2 = getPersistentRecords(
                    adornedTargetList.getAdornedTargetEntityClassname(), filterMappingsInserted,
                    ctoInserted.getFirstResult(), ctoInserted.getMaxResults());

            payload = getRecords(mergedPropertiesTarget, recordsInserted2, mergedProperties,
                    adornedTargetList.getTargetObjectPath())[0];
        }
    } catch (Exception e) {
        throw new ServiceException("Problem adding new entity : " + e.getMessage(), e);
    }

    return payload;
}

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

@Override
public ExtensionResultStatusType rebalanceForAdd(BasicPersistenceModule basicPersistenceModule,
        PersistencePackage persistencePackage, Serializable instance,
        Map<String, FieldMetadata> mergedProperties, ExtensionResultHolder<Serializable> resultHolder) {
    try {//from w  ww  . j  a  va 2  s. co  m
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems()
                .get(PersistencePerspectiveItemType.FOREIGNKEY);
        CriteriaTransferObject cto = new CriteriaTransferObject();
        FilterAndSortCriteria sortCriteria = cto.get(foreignKey.getSortField());
        sortCriteria.setSortAscending(foreignKey.getSortAscending());
        List<FilterMapping> filterMappings = basicPersistenceModule.getFilterMappings(persistencePerspective,
                cto, persistencePackage.getCeilingEntityFullyQualifiedClassname(), mergedProperties);
        int totalRecords = basicPersistenceModule
                .getTotalRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(), filterMappings);
        Class<?> type = basicPersistenceModule.getFieldManager()
                .getField(instance.getClass(), foreignKey.getSortField()).getType();
        boolean isBigDecimal = BigDecimal.class.isAssignableFrom(type);
        basicPersistenceModule.getFieldManager().setFieldValue(instance, foreignKey.getSortField(),
                isBigDecimal ? new BigDecimal(totalRecords + 1) : Long.valueOf(totalRecords + 1));

        resultHolder.setResult(instance);

    } catch (IllegalAccessException e) {
        throw ExceptionHelper.refineException(e);
    } catch (InstantiationException e) {
        throw ExceptionHelper.refineException(e);
    }

    return ExtensionResultStatusType.HANDLED;
}

From source file:org.mule.security.oauth.BaseOAuth2Manager.java

/**
 * {@inheritDoc}//w  w w. j  a v  a2s.  c  o  m
 */
@Override
public MuleEvent restoreAuthorizationEvent(String eventId)
        throws ObjectStoreException, ObjectDoesNotExistException {
    Serializable maybeEvent = this.accessTokenObjectStore.retrieve(this.buildAuthorizationEventKey(eventId));
    if (maybeEvent instanceof MuleEvent) {
        MuleEvent event = (MuleEvent) maybeEvent;

        if (event instanceof ThreadSafeAccess) {
            ((ThreadSafeAccess) event).resetAccessControl();
        }

        return event;
    } else {
        throw new IllegalArgumentException(String.format(
                "Tried to retrieve authorization event of id %s but instead found object of class %s", eventId,
                maybeEvent.getClass().getCanonicalName()));
    }
}

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

@Override
public ExtensionResultStatusType rebalanceForUpdate(final BasicPersistenceModule basicPersistenceModule,
        PersistencePackage persistencePackage, Serializable instance,
        Map<String, FieldMetadata> mergedProperties, Object primaryKey,
        ExtensionResultHolder<Serializable> resultHolder) {
    try {/*from w ww.j  av  a2  s  .c  om*/
        Entity entity = persistencePackage.getEntity();
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        ForeignKey foreignKey = (ForeignKey) persistencePerspective.getPersistencePerspectiveItems()
                .get(PersistencePerspectiveItemType.FOREIGNKEY);
        Integer requestedSequence = Integer.valueOf(entity.findProperty(foreignKey.getSortField()).getValue());
        Integer previousSequence = new BigDecimal(String.valueOf(
                basicPersistenceModule.getFieldManager().getFieldValue(instance, foreignKey.getSortField())))
                        .intValue();
        final String idPropertyName = basicPersistenceModule.getIdPropertyName(mergedProperties);
        final Object pKey = primaryKey;

        instance = basicPersistenceModule.createPopulatedInstance(instance, entity, mergedProperties, false,
                persistencePackage.isValidateUnsubmittedProperties());

        if (!previousSequence.equals(requestedSequence)) {
            // Sequence has changed. Rebalance the list
            Serializable manyToField = (Serializable) basicPersistenceModule.getFieldManager()
                    .getFieldValue(instance, foreignKey.getManyToField());
            List<Serializable> records = (List<Serializable>) basicPersistenceModule.getFieldManager()
                    .getFieldValue(manyToField, foreignKey.getOriginatingField());

            Serializable myRecord = (Serializable) CollectionUtils.find(records,
                    new TypedPredicate<Serializable>() {

                        @Override
                        public boolean eval(Serializable record) {
                            try {
                                return (pKey.equals(basicPersistenceModule.getFieldManager()
                                        .getFieldValue(record, idPropertyName)));
                            } catch (IllegalAccessException e) {
                                return false;
                            } catch (FieldNotAvailableException e) {
                                return false;
                            }

                        }

                    });

            records.remove(myRecord);
            if (CollectionUtils.isEmpty(records)) {
                records.add(myRecord);
            } else {
                records.add(requestedSequence - 1, myRecord);
            }

            int index = 1;
            Class<?> type = basicPersistenceModule.getFieldManager()
                    .getField(myRecord.getClass(), foreignKey.getSortField()).getType();
            boolean isBigDecimal = BigDecimal.class.isAssignableFrom(type);
            for (Serializable record : records) {
                basicPersistenceModule.getFieldManager().setFieldValue(record, foreignKey.getSortField(),
                        isBigDecimal ? new BigDecimal(index) : Long.valueOf(index));
                index++;
            }
        }

        resultHolder.setResult(instance);

    } catch (IllegalAccessException e) {
        throw ExceptionHelper.refineException(e);
    } catch (FieldNotAvailableException e) {
        throw ExceptionHelper.refineException(e);
    } catch (ValidationException e) {
        throw ExceptionHelper.refineException(e);
    } catch (InstantiationException e) {
        throw ExceptionHelper.refineException(e);
    }

    return ExtensionResultStatusType.HANDLED;
}

From source file:org.eclipse.ecr.opencmis.impl.server.NuxeoPropertyData.java

/**
 * Conversion from Nuxeo values to CMIS ones.
 *
 * @return either a primitive type or a List of them, or {@code null}
 *///from  ww  w  .ja  va2s  .c  o m
@Override
@SuppressWarnings("unchecked")
public <U> U getValue() {
    try {
        Property prop = doc.getProperty(name);
        Serializable value = prop.getValue();
        if (value == null) {
            return null;
        }
        Type type = prop.getType();
        if (type.isListType()) {
            // array/list
            List<Object> values;
            if (value instanceof Object[]) {
                values = Arrays.asList((Object[]) value);
            } else if (value instanceof List<?>) {
                values = (List<Object>) value;
            } else {
                throw new CmisRuntimeException("Unknown value type: " + value.getClass().getName());
            }
            List<Object> list = new ArrayList<Object>(values);
            for (int i = 0; i < list.size(); i++) {
                list.set(i, convertToCMIS(list.get(i)));
            }
            return (U) list;
        } else {
            // primitive type
            return (U) convertToCMIS(value);
        }
    } catch (ClientException e) {
        throw new CmisRuntimeException(e.toString(), e);
    }
}

From source file:org.unitime.timetable.security.evaluation.UniTimePermissionCheck.java

@Override
public boolean hasPermission(UserContext user, Serializable targetId, String targetType, Right right) {
    if (user == null || user.getCurrentAuthority() == null)
        return false;
    if (right == null || !user.getCurrentAuthority().hasRight(right))
        return false;

    if (targetType == null && right.hasType())
        targetType = right.type().getSimpleName();

    if (targetType == null)
        return true;

    if (targetId != null && targetId instanceof Collection) {
        for (Serializable id : (Collection<Serializable>) targetId)
            if (!hasPermission(user, id, targetType, right))
                return false;
        return true;
    }/*from  w w  w. ja  v a2s. com*/

    if (targetId != null && targetId.getClass().isArray()) {
        for (Serializable id : (Serializable[]) targetId)
            if (!hasPermission(user, id, targetType, right))
                return false;
        return true;
    }

    try {
        String className = targetType;
        if (className.indexOf('.') < 0)
            className = "org.unitime.timetable.model." + className;

        // Special cases

        if (targetId == null && Session.class.getName().equals(className))
            targetId = user.getCurrentAcademicSessionId();

        if (targetId == null && Department.class.getName().equals(className)) {

            for (Department d : Department.getUserDepartments(user))
                if (hasPermission(user, d, right))
                    return true;

            return false;
        }

        if (targetId == null && SubjectArea.class.getName().equals(className)) {

            for (SubjectArea sa : SubjectArea.getUserSubjectAreas(user))
                if (hasPermission(user, sa, right))
                    return true;

            return false;
        }

        if (targetId == null && SolverGroup.class.getName().equals(className)) {
            for (SolverGroup g : SolverGroup.getUserSolverGroups(user))
                if (hasPermission(user, g, right))
                    return true;

            return false;
        }

        if (targetId == null)
            return false;

        if (targetId instanceof Qualifiable) {
            Qualifiable q = (Qualifiable) targetId;
            if (targetType == null || targetType.equals(q.getQualifierType()))
                return hasPermission(user, q.getQualifierId(), q.getQualifierType(), right);
            else
                return false;
        }

        if (targetId instanceof String && Department.class.getName().equals(className)) {
            Department dept = Department.findByDeptCode((String) targetId, user.getCurrentAcademicSessionId());
            if (dept != null)
                return hasPermission(user, dept, right);
        }

        if (targetId instanceof String) {
            try {
                targetId = Long.valueOf((String) targetId);
            } catch (NumberFormatException e) {
            }
        }
        if (!(targetId instanceof Long)) {
            try {
                targetId = (Serializable) targetId.getClass().getMethod("getUniqueId").invoke(targetId);
            } catch (Exception e) {
            }
            try {
                targetId = (Serializable) targetId.getClass().getMethod("getId").invoke(targetId);
            } catch (Exception e) {
            }
        }

        Object domainObject = new _RootDAO().getSession().get(Class.forName(className), targetId);
        if (domainObject == null)
            return false;

        return hasPermission(user, domainObject, right);
    } catch (Exception e) {
        return false;
    }
}

From source file:org.alfresco.repo.transfer.RepoPrimaryManifestProcessorImpl.java

/**
 * This method takes all the received properties and separates them into two parts. The content properties are
 * removed from the non-content properties such that the non-content properties remain in the "props" map and the
 * content properties are returned from this method Subsequently, any properties that are to be retained from the
 * local repository are copied over into the "props" map. The result of all this is that, upon return, "props"
 * contains all the non-content properties that are to be written to the local repo, and "contentProps" contains all
 * the content properties that are to be written to the local repo.
 * //from   ww w.java  2s .  com
 * @param nodeToUpdate
 *            The noderef of the existing node in the local repo that is to be updated with these properties. May be
 *            null, indicating that these properties are destined for a brand new local node.
 * @param props the new properties
 * @param existingProps the existing properties, null if this is a create
 * @return A map containing the content properties which are going to be replaced from the supplied "props" map
 */
private Map<QName, Serializable> processProperties(NodeRef nodeToUpdate, Map<QName, Serializable> props,
        Map<QName, Serializable> existingProps) {
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
    // ...and copy any supplied content properties into this new map...
    for (Map.Entry<QName, Serializable> propEntry : props.entrySet()) {
        Serializable value = propEntry.getValue();
        QName key = propEntry.getKey();
        if (log.isDebugEnabled()) {
            if (value == null) {
                log.debug("Received a null value for property " + propEntry.getKey());
            }
        }
        if ((value != null) && ContentData.class.isAssignableFrom(value.getClass())) {
            if (existingProps != null) {
                // This is an update and we have content data 
                File stagingDir = getStagingFolder();
                ContentData contentData = (ContentData) propEntry.getValue();
                String contentUrl = contentData.getContentUrl();
                String fileName = TransferCommons.URLToPartName(contentUrl);
                File stagedFile = new File(stagingDir, fileName);
                if (stagedFile.exists()) {
                    if (log.isDebugEnabled()) {
                        log.debug("replace content for node:" + nodeToUpdate + ", " + key);
                    }
                    // Yes we are going to replace the content item
                    contentProps.put(propEntry.getKey(), propEntry.getValue());
                } else {
                    // Staging file does not exist
                    if (props.containsKey(key)) {
                        if (log.isDebugEnabled()) {
                            log.debug("keep existing content for node:" + nodeToUpdate + ", " + key);
                        }
                        // keep the existing content value
                        props.put(propEntry.getKey(), existingProps.get(key));
                    }
                }
            } else {
                // This is a create so all content items are new
                contentProps.put(propEntry.getKey(), propEntry.getValue());
            }
        }
    }

    // Now we can remove the content properties from amongst the other kinds
    // of properties
    // (no removeAll on a Map...)
    for (QName contentPropertyName : contentProps.keySet()) {
        props.remove(contentPropertyName);
    }

    if (existingProps != null) {
        // Finally, overlay the repo-specific properties from the existing
        // node (if there is one)
        for (QName localProperty : getLocalProperties()) {
            Serializable existingValue = existingProps.get(localProperty);
            if (existingValue != null) {
                props.put(localProperty, existingValue);
            } else {
                props.remove(localProperty);
            }
        }
    }
    return contentProps;
}

From source file:org.alfresco.repo.transfer.TransferServiceImpl2.java

private void mapTransferTarget(NodeRef nodeRef, TransferTargetImpl def) {
    def.setNodeRef(nodeRef);/*from   w w  w.j a v  a 2 s. c  o m*/
    Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);
    String name = (String) properties.get(ContentModel.PROP_NAME);

    String endpointPath = (String) properties.get(TransferModel.PROP_ENDPOINT_PATH);
    if (endpointPath == null)
        throw new TransferException(MSG_MISSING_ENDPOINT_PATH, new Object[] { name });
    def.setEndpointPath(endpointPath);

    String endpointProtocol = (String) properties.get(TransferModel.PROP_ENDPOINT_PROTOCOL);
    if (endpointProtocol == null)
        throw new TransferException(MSG_MISSING_ENDPOINT_PROTOCOL, new Object[] { name });
    def.setEndpointProtocol(endpointProtocol);

    String endpointHost = (String) properties.get(TransferModel.PROP_ENDPOINT_HOST);
    if (endpointHost == null)
        throw new TransferException(MSG_MISSING_ENDPOINT_HOST, new Object[] { name });
    def.setEndpointHost(endpointHost);

    Integer endpointPort = (Integer) properties.get(TransferModel.PROP_ENDPOINT_PORT);
    if (endpointPort == null)
        throw new TransferException(MSG_MISSING_ENDPOINT_PORT, new Object[] { name });
    def.setEndpointPort(endpointPort);

    String username = (String) properties.get(TransferModel.PROP_USERNAME);
    if (username == null)
        throw new TransferException(MSG_MISSING_ENDPOINT_USERNAME, new Object[] { name });
    def.setUsername(username);

    Serializable passwordVal = properties.get(TransferModel.PROP_PASSWORD);
    if (passwordVal == null)
        throw new TransferException(MSG_MISSING_ENDPOINT_PASSWORD, new Object[] { name });
    if (passwordVal.getClass().isArray()) {
        def.setPassword(decrypt((char[]) passwordVal));
    }
    if (passwordVal instanceof String) {
        String password = (String) passwordVal;
        def.setPassword(decrypt(password.toCharArray()));
    }

    def.setName(name);
    def.setTitle((String) properties.get(ContentModel.PROP_TITLE));
    def.setDescription((String) properties.get(ContentModel.PROP_DESCRIPTION));

    if (nodeService.hasAspect(nodeRef, TransferModel.ASPECT_ENABLEABLE)) {
        def.setEnabled((Boolean) properties.get(TransferModel.PROP_ENABLED));
    } else {
        // If the enableable aspect is not present then we don't want transfer failing.
        def.setEnabled(Boolean.TRUE);
    }
}