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.validation.EntityValidatorServiceImpl.java

@Override
public void validate(Entity submittedEntity, @Nullable Serializable instance,
        Map<String, FieldMetadata> propertiesMetadata, RecordHelper recordHelper,
        boolean validateUnsubmittedProperties) {
    Object idValue = null;//ww w  .  j a v a 2 s  .  co  m
    if (instance != null) {
        String idField = (String) ((BasicPersistenceModule) recordHelper
                .getCompatibleModule(OperationType.BASIC)).getPersistenceManager().getDynamicEntityDao()
                        .getIdMetadata(instance.getClass()).get("name");
        try {
            idValue = recordHelper.getFieldManager().getFieldValue(instance, idField);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (FieldNotAvailableException e) {
            throw new RuntimeException(e);
        }
    }
    Entity entity;
    boolean isUpdateRequest;
    if (idValue == null) {
        //This is for an add, or if the instance variable is null (e.g. PageTemplateCustomPersistenceHandler)
        entity = submittedEntity;
        isUpdateRequest = false;
    } else {
        if (validateUnsubmittedProperties) {
            //This is for an update, as the submittedEntity instance will likely only contain the dirty properties
            entity = recordHelper.getRecord(propertiesMetadata, instance, null, null);
            //acquire any missing properties not harvested from the instance and add to the entity. A use case for this
            //would be the confirmation field for a password validation
            for (Map.Entry<String, FieldMetadata> entry : propertiesMetadata.entrySet()) {
                if (entity.findProperty(entry.getKey()) == null) {
                    Property myProperty = submittedEntity.findProperty(entry.getKey());
                    if (myProperty != null) {
                        entity.addProperty(myProperty);
                    }
                } else if (submittedEntity.findProperty(entry.getKey()) != null) {
                    // Set the dirty state of the property
                    entity.findProperty(entry.getKey())
                            .setIsDirty(submittedEntity.findProperty(entry.getKey()).getIsDirty());
                }
            }
        } else {
            entity = submittedEntity;
        }
        isUpdateRequest = true;
    }

    List<String> types = getTypeHierarchy(entity);
    //validate each individual property according to their validation configuration
    for (Entry<String, FieldMetadata> metadataEntry : propertiesMetadata.entrySet()) {
        FieldMetadata metadata = metadataEntry.getValue();

        //Don't test this field if it was not inherited from our polymorphic type (or supertype)
        if (instance != null && (types.contains(metadata.getInheritedFromType())
                || instance.getClass().getName().equals(metadata.getInheritedFromType()))) {

            Property property = entity.getPMap().get(metadataEntry.getKey());

            // This property should be set to false only in the case where we are adding a member to a collection
            // that has type of lookup. In this case, we don't have the properties from the target in our entity,
            // and we don't need to validate them.
            if (!validateUnsubmittedProperties && property == null) {
                continue;
            }

            //for radio buttons, it's possible that the entity property was never populated in the first place from the POST
            //and so it will be null
            String propertyName = metadataEntry.getKey();
            String propertyValue = (property == null) ? null : property.getValue();

            if (metadata instanceof BasicFieldMetadata) {
                //First execute the global field validators
                if (CollectionUtils.isNotEmpty(globalEntityValidators)) {
                    for (GlobalPropertyValidator validator : globalEntityValidators) {
                        PropertyValidationResult result = validator.validate(entity, instance,
                                propertiesMetadata, (BasicFieldMetadata) metadata, propertyName, propertyValue);
                        if (!result.isValid()) {
                            submittedEntity.addValidationError(propertyName, result.getErrorMessage());
                        }
                    }
                }

                //Now execute the validators configured for this particular field
                Map<String, Map<String, String>> validations = ((BasicFieldMetadata) metadata)
                        .getValidationConfigurations();
                for (Map.Entry<String, Map<String, String>> validation : validations.entrySet()) {
                    String validationImplementation = validation.getKey();
                    Map<String, String> configuration = validation.getValue();

                    PropertyValidator validator = null;

                    //attempt bean resolution to find the validator
                    if (applicationContext.containsBean(validationImplementation)) {
                        validator = applicationContext.getBean(validationImplementation,
                                PropertyValidator.class);
                    }

                    //not a bean, attempt to instantiate the class
                    if (validator == null) {
                        try {
                            validator = (PropertyValidator) Class.forName(validationImplementation)
                                    .newInstance();
                        } catch (Exception e) {
                            //do nothing
                        }
                    }

                    if (validator == null) {
                        throw new PersistenceException("Could not find validator: " + validationImplementation
                                + " for property: " + propertyName);
                    }

                    PropertyValidationResult result = validator.validate(entity, instance, propertiesMetadata,
                            configuration, (BasicFieldMetadata) metadata, propertyName, propertyValue);
                    if (!result.isValid()) {
                        for (String message : result.getErrorMessages()) {
                            submittedEntity.addValidationError(propertyName, message);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.feilong.core.bean.ConvertUtilTest.java

/**
 * To t test.//www.  j a  va 2s .c  o  m
 */
@Test
public void testConvert() {
    String[] tokenizeToStringArray = StringUtil.tokenizeToStringArray("6", "_");

    LinkedList<Serializable> linkedList = new LinkedList<Serializable>();

    for (String string : tokenizeToStringArray) {
        Serializable t = ConvertUtil.convert(string, Serializable.class);
        LOGGER.debug(t.getClass().getCanonicalName());
        linkedList.add(t);
    }

    Serializable l = 6L;

    LOGGER.debug("linkedList:{},contains:{},{}", linkedList, l, linkedList.contains(l));
}

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

protected boolean populateQuantityRule(PopulateValueRequest populateValueRequest, Serializable instance)
        throws FieldNotAvailableException, IllegalAccessException {
    String prop = populateValueRequest.getProperty().getName();
    Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop);
    OneToMany oneToMany = field.getAnnotation(OneToMany.class);
    if (oneToMany == null) {
        throw new UnsupportedOperationException(
                "RuleFieldPersistenceProvider is currently only compatible with collection fields when modelled using @OneToMany");
    }//from  w w w . j  a  v  a  2  s  .c o  m
    boolean dirty;//currently, this only works with Collection fields
    Class<?> valueType = getListFieldType(instance, populateValueRequest.getFieldManager(),
            populateValueRequest.getProperty(), populateValueRequest.getPersistenceManager());
    if (valueType == null) {
        throw new IllegalAccessException("Unable to determine the valueType for the rule field ("
                + populateValueRequest.getProperty().getName() + ")");
    }
    DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator();
    Collection<QuantityBasedRule> rules;
    rules = (Collection<QuantityBasedRule>) populateValueRequest.getFieldManager().getFieldValue(instance,
            populateValueRequest.getProperty().getName());
    Object parent = extractParent(populateValueRequest, instance);
    //AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version
    dirty = updateQuantityRule(
            populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager(),
            translator,
            RuleIdentifier.ENTITY_KEY_MAP.get(populateValueRequest.getMetadata().getRuleIdentifier()),
            populateValueRequest.getMetadata().getRuleIdentifier(),
            populateValueRequest.getProperty().getUnHtmlEncodedValue(), rules, valueType, parent,
            oneToMany.mappedBy(), populateValueRequest.getProperty());
    return dirty;
}

From source file:com.haulmont.cuba.core.app.ClusterManager.java

@Override
public void send(final Serializable message) {
    if (channel == null)
        return;/*from ww  w.  j a  v  a 2s  . c  o  m*/

    Boolean sync = forceSyncSending.get();
    if (sync != null && sync) {
        internalSend(message, true);
    } else {
        log.trace("Submitting message: {}: {} to send asynchronously", message.getClass(), message);
        executor.execute(new SendMessageRunnable(message));
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.CswRecordConverterTest.java

/** Verifies that Zulu time zone is valid in ISO 8601 date. */
@Test/*from  ww  w .  j a  va  2s. c om*/
public void testConvertISODateMetacardAttribute() {
    String dateStr = "2013-05-03T17:25:04Z";
    Serializable ser = CswUnmarshallHelper.convertStringValueToMetacardValue(AttributeFormat.DATE, dateStr);
    assertThat(ser, notNullValue());
    assertThat(Date.class.isAssignableFrom(ser.getClass()), is(true));
    Date date = (Date) ser;
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    cal.setTime(date);
    assertThat(cal.get(Calendar.MONTH), is(Calendar.MAY));
    assertThat(cal.get(Calendar.YEAR), is(2013));
    assertThat(cal.get(Calendar.DAY_OF_MONTH), is(3));
}

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

@Override
public Entity add(PersistencePackage persistencePackage) throws ServiceException {
    String[] customCriteria = persistencePackage.getCustomCriteria();
    if (customCriteria != null && customCriteria.length > 0) {
        LOG.warn(//from   w  w  w. j  a  v a 2s  .c  om
                "custom persistence handlers and custom criteria not supported for add types other than ENTITY");
    }
    PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
    String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
    Entity entity = persistencePackage.getEntity();
    JoinStructure joinStructure = (JoinStructure) persistencePerspective.getPersistencePerspectiveItems()
            .get(PersistencePerspectiveItemType.JOINSTRUCTURE);
    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(joinStructure.getJoinStructureEntityClassname());
        Map<String, FieldMetadata> mergedProperties = persistenceManager.getDynamicEntityDao()
                .getMergedProperties(joinStructure.getJoinStructureEntityClassname(), entities2, null,
                        new String[] {}, new ForeignKey[] {}, MergedPropertyType.JOINSTRUCTURE, false,
                        new String[] {}, new String[] {}, null, "");

        CriteriaTransferObject ctoInserted = new CriteriaTransferObject();
        FilterAndSortCriteria filterCriteriaInsertedLinked = ctoInserted.get(joinStructure.getName());
        String linkedPath;
        String targetPath;
        if (joinStructure.getInverse()) {
            linkedPath = joinStructure.getTargetObjectPath() + "." + joinStructure.getTargetIdProperty();
            targetPath = joinStructure.getLinkedObjectPath() + "." + joinStructure.getLinkedIdProperty();
        } else {
            targetPath = joinStructure.getTargetObjectPath() + "." + joinStructure.getTargetIdProperty();
            linkedPath = joinStructure.getLinkedObjectPath() + "." + joinStructure.getLinkedIdProperty();
        }
        filterCriteriaInsertedLinked.setFilterValue(
                entity.findProperty(joinStructure.getInverse() ? targetPath : linkedPath).getValue());
        FilterAndSortCriteria filterCriteriaInsertedTarget = ctoInserted
                .get(joinStructure.getName() + "Target");
        filterCriteriaInsertedTarget.setFilterValue(
                entity.findProperty(joinStructure.getInverse() ? linkedPath : targetPath).getValue());
        BaseCtoConverter ctoConverterInserted = getJoinStructureCtoConverter(persistencePerspective,
                ctoInserted, mergedProperties, joinStructure);
        PersistentEntityCriteria queryCriteriaInserted = ctoConverterInserted.convert(ctoInserted,
                joinStructure.getJoinStructureEntityClassname());
        List<Serializable> recordsInserted = persistenceManager.getDynamicEntityDao()
                .query(queryCriteriaInserted, Class.forName(joinStructure.getJoinStructureEntityClassname()));
        if (recordsInserted.size() > 0) {
            payload = getRecords(mergedPropertiesTarget, recordsInserted, mergedProperties,
                    joinStructure.getTargetObjectPath())[0];
        } else {
            Serializable instance = createPopulatedJoinStructureInstance(joinStructure, entity);
            instance = createPopulatedInstance(instance, entity, mergedProperties, false);
            instance = createPopulatedInstance(instance, entity, mergedPropertiesTarget, false);
            FieldManager fieldManager = getFieldManager();
            if (fieldManager.getField(instance.getClass(), "id") != null) {
                fieldManager.setFieldValue(instance, "id", null);
            }
            if (joinStructure.getSortField() != null) {
                CriteriaTransferObject cto = new CriteriaTransferObject();
                FilterAndSortCriteria filterCriteria = cto.get(joinStructure.getName());
                filterCriteria.setFilterValue(
                        entity.findProperty(joinStructure.getInverse() ? targetPath : linkedPath).getValue());
                FilterAndSortCriteria sortCriteria = cto.get(joinStructure.getSortField());
                sortCriteria.setSortAscending(joinStructure.getSortAscending());
                BaseCtoConverter ctoConverter = getJoinStructureCtoConverter(persistencePerspective, cto,
                        mergedProperties, joinStructure);
                int totalRecords = getTotalRecords(joinStructure.getJoinStructureEntityClassname(), cto,
                        ctoConverter);
                fieldManager.setFieldValue(instance, joinStructure.getSortField(),
                        Long.valueOf(totalRecords + 1));
            }
            instance = persistenceManager.getDynamicEntityDao().merge(instance);
            persistenceManager.getDynamicEntityDao().flush();
            persistenceManager.getDynamicEntityDao().clear();

            List<Serializable> recordsInserted2 = persistenceManager.getDynamicEntityDao().query(
                    queryCriteriaInserted, Class.forName(joinStructure.getJoinStructureEntityClassname()));

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

    return payload;
}

From source file:de.micromata.genome.db.jpa.history.impl.HistoryServiceImpl.java

private Long castToLong(Serializable entityPk) {
    if (entityPk == null) {
        return null;
    }/*from w w  w . jav  a 2s. c  om*/
    if (entityPk instanceof Long) {
        return (Long) entityPk;
    }
    if (entityPk instanceof Number) {
        return ((Number) entityPk).longValue();
    }
    throw new IllegalArgumentException("Pk is not a number: " + entityPk.getClass().getName());
}

From source file:org.apereo.portal.portlet.container.EventProviderImpl.java

private boolean isValueInstanceOfDefinedClass(QName qname, Serializable value) {
    final PortletDefinition portletDefinition = this.portletWindow.getPlutoPortletWindow()
            .getPortletDefinition();//from   www. ja v  a  2s  .c  o m
    final PortletApplicationDefinition app = portletDefinition.getApplication();
    final List<? extends EventDefinition> events = app.getEventDefinitions();
    if (events == null) {
        return true;
    }

    final String defaultNamespace = app.getDefaultNamespace();

    for (final EventDefinition eventDefinition : events) {
        if (eventDefinition.getQName() != null) {
            if (eventDefinition.getQName().equals(qname)) {
                final Class<? extends Serializable> valueClass = value.getClass();
                return valueClass.getName().equals(eventDefinition.getValueType());
            }
        } else {
            final QName tmp = new QName(defaultNamespace, eventDefinition.getName());
            if (tmp.equals(qname)) {
                final Class<? extends Serializable> valueClass = value.getClass();
                return valueClass.getName().equals(eventDefinition.getValueType());
            }
        }
    }

    // event not declared
    return true;
}

From source file:com.flexive.ejb.beans.configuration.GenericConfigurationImpl.java

/**
 * Returns the cached value of the given parameter
 *
 * @param path the parameter path/* www  .j ava 2 s  . c  om*/
 * @param key  the parameter key
 * @return the cached value of the given parameter
 * @throws FxCacheException if a cache exception occurred
 */
protected Serializable getCache(String path, String key) throws FxCacheException {
    final Serializable value = (Serializable) CacheAdmin.getInstance().get(path, key);
    if (value == null || value instanceof String || Primitives.isWrapperType(value.getClass())) {
        // immutable value type
        return value;
    }
    if (value instanceof Cloneable) {
        // use clone if possible
        try {
            final Object clone = ObjectUtils.clone(value);
            if (clone != null && clone instanceof Serializable) {
                return (Serializable) clone;
            }
        } catch (CloneFailedException e) {
            LOG.warn("Failed to clone cached configuration value " + path + "/" + key, e);
        }
    }
    // use generic clone via serialization
    return (Serializable) SerializationUtils.clone(value);
}

From source file:ddf.catalog.data.impl.MetacardImpl.java

/**
 * The brains of the operation -- does the interaction with the map or the wrapped metacard.
 *
 * @param <T>           the type of the Attribute value expected
 * @param attributeName the name of the {@link Attribute} to retrieve
 * @param returnType    the class that the value of the {@link ddf.catalog.data.AttributeType} is expected to be bound to
 * @return the value of the requested {@link Attribute} name
 *///www.  j  ava  2s . c  om
protected <T> T requestData(String attributeName, Class<T> returnType) {

    Attribute attribute = getAttribute(attributeName);

    if (attribute == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Attribute " + attributeName + " was not found, returning null");
        }
        return null;
    }

    Serializable data = attribute.getValue();

    if (returnType.isAssignableFrom(data.getClass())) {
        return returnType.cast(data);
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(data.getClass().toString() + " can not be assigned to " + returnType.toString());
        }
    }

    return null;
}