List of usage examples for java.io Serializable getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.alfresco.repo.domain.node.NodePropertyHelper.java
/** * Helper method to convert the <code>Serializable</code> value into a full, persistable {@link NodePropertyValue}. * <p>/*from w w w . j a va 2s. c om*/ * Where the property definition is null, the value will take on the {@link DataTypeDefinition#ANY generic ANY} * value. * <p> * Collections are NOT supported. These must be split up by the calling code before calling this method. Map * instances are supported as plain serializable instances. * * @param propertyDef the property dictionary definition, may be null * @param value the value, which will be converted according to the definition - may be null * @return Returns the persistable property value */ public NodePropertyValue makeNodePropertyValue(PropertyDefinition propertyDef, Serializable value) { // get property attributes final QName propertyTypeQName; 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(); } try { NodePropertyValue propertyValue = null; propertyValue = new NodePropertyValue(propertyTypeQName, value); // done return propertyValue; } catch (TypeConversionException e) { 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: " + value.getClass(), e); } }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java
protected Class<?> getMapFieldType(Serializable instance, FieldManager fieldManager, Property property) { Class<?> returnType = null; Field field = fieldManager.getField(instance.getClass(), property.getName().substring(0, property.getName().indexOf(FieldManager.MAPFIELDSEPARATOR))); java.lang.reflect.Type type = field.getGenericType(); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[1]; Class<?>[] entities = persistenceManager.getDynamicEntityDao() .getAllPolymorphicEntitiesFromCeiling(clazz); if (!ArrayUtils.isEmpty(entities)) { returnType = entities[entities.length - 1]; }/*from w w w . j a v a 2 s .c o m*/ } return returnType; }
From source file:com.mnxfst.testing.handler.exec.PTestPlanExecutionContext.java
/** * The provided pattern names a context variable and an access path along getter methods that * need to be evaluated to fetch the final value. Eg.: ${user.address.street} executes user#getAddress#getStreet * @param replacementPattern/* w w w . j av a 2 s .c om*/ * @return * @throws ContextVariableEvaluationFailedException */ public Object evaluate(String replacementPattern) throws ContextVariableEvaluationFailedException { // validate the replacement pattern if (replacementPattern == null || replacementPattern.trim().isEmpty()) throw new ContextVariableEvaluationFailedException("No replacement pattern provided"); // find replacement pattern in map of previously computed pattern and apply access methods PTestPlanExecutionContextReplacementPattern patternInstance = replacementPatternMapping .get(replacementPattern); if (patternInstance != null) { Serializable ctxVariable = getContextVariable(patternInstance.getName()); return evaluateObject(ctxVariable, patternInstance.getAccessMethods()); } // ensure that the replacement pattern starts with '${' and ends with '}' if (replacementPattern.startsWith("${") && replacementPattern.endsWith("}")) { // extract context variable name String ctxVariableName = extractContextVariableName(replacementPattern); Serializable ctxVariable = getContextVariable(ctxVariableName); if (ctxVariable == null) return null; // if the variable has been found, try to extract the getter method names along the path described. if there // are not getters to be called, just return the variable value String[] getterMethodNames = extractGetterMethodNames(replacementPattern); if (getterMethodNames == null || getterMethodNames.length < 1) return ctxVariable; // convert the getter names into method representations List<Method> getterMethods = new ArrayList<Method>(); extractGetterMethods(ctxVariable.getClass(), getterMethodNames, getterMethods); // create entity for previously mentioned association map for pattern information and insert it PTestPlanExecutionContextReplacementPattern patternMapping = new PTestPlanExecutionContextReplacementPattern( replacementPattern, ctxVariableName); for (Method m : getterMethods) patternMapping.addAccessMethod(m); replacementPatternMapping.put(replacementPattern, patternMapping); // evaluate the getter methods against the variable value return evaluateObject(ctxVariable, getterMethods); } throw new ContextVariableEvaluationFailedException( "Invalid replacement pattern: " + replacementPattern + ". Expected prefix: ${variable}"); }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.MapFieldPersistenceProvider.java
protected void updateAssignableValue(PopulateValueRequest populateValueRequest, Serializable instance, Object parent, Class<?> valueType, boolean persistValue, ValueAssignable assignableValue) throws IllegalAccessException, FieldNotAvailableException, InstantiationException { if (!persistValue) { //pre-merge (can result in a clone for enterprise) parent = populateValueRequest.getPersistenceManager().getDynamicEntityDao().merge(parent); assignableValue = establishAssignableValue(populateValueRequest, parent); }//from w w w .j a v a 2s . c o m String key = populateValueRequest.getProperty().getName().substring( populateValueRequest.getProperty().getName().indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), populateValueRequest.getProperty().getName().length()); populateValueRequest.getProperty().setOriginalValue(String.valueOf(assignableValue)); populateValueRequest.getProperty().setOriginalDisplayValue(String.valueOf(assignableValue)); assignableValue.setName(key); assignableValue.setValue(populateValueRequest.getProperty().getValue()); String fieldName = populateValueRequest.getProperty().getName().substring(0, populateValueRequest.getProperty().getName().indexOf(FieldManager.MAPFIELDSEPARATOR)); Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), fieldName); FieldInfo fieldInfo = buildFieldInfo(field); String manyToField = null; if (populateValueRequest.getMetadata().getManyToField() != null) { manyToField = populateValueRequest.getMetadata().getManyToField(); } if (manyToField == null) { manyToField = fieldInfo.getManyToManyMappedBy(); } if (manyToField == null) { manyToField = fieldInfo.getOneToManyMappedBy(); } if (manyToField != null) { String propertyName = populateValueRequest.getProperty().getName(); Object middleInstance = instance; if (propertyName.contains(".")) { propertyName = propertyName.substring(0, propertyName.lastIndexOf(".")); middleInstance = populateValueRequest.getFieldManager().getFieldValue(instance, propertyName); } populateValueRequest.getFieldManager().setFieldValue(assignableValue, manyToField, middleInstance); if (!populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager() .contains(middleInstance)) { //if this is part of an add for the manyToField object, don't persist this map value, // since it would result in a //transient object exception on the manyToField object (which itself has not been saved yet) persistValue = false; } } if (Searchable.class.isAssignableFrom(valueType)) { ((Searchable) assignableValue).setSearchable(populateValueRequest.getMetadata().getSearchable()); } if (persistValue) { populateValueRequest.getPersistenceManager().getDynamicEntityDao().persist(assignableValue); } }
From source file:org.sakaiproject.evaluation.logic.externals.EvalExternalLogicImpl.java
/** * Get an entity reference to any of the evaluation objects which are treated as entities * /*from ww w .j av a 2 s .c om*/ * @param entity * @return an entity reference string or null if none can be found */ protected String getEntityReference(Serializable entity) { String id; try { Class<? extends Serializable> elementClass = entity.getClass(); Method getIdMethod = elementClass.getMethod("getId", new Class[] {}); Long realId = (Long) getIdMethod.invoke(entity, (Object[]) null); id = realId.toString(); return getEntityReference(elementClass, id); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOG.warn("Failed to get id from entity object", e); return null; } }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.AdornedTargetListPersistenceModule.java
protected Serializable createPopulatedAdornedTargetInstance(AdornedTargetList adornedTargetList, Entity entity) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NumberFormatException, InvocationTargetException, NoSuchMethodException, FieldNotAvailableException { Serializable instance = (Serializable) Class .forName(StringUtils.isEmpty(adornedTargetList.getAdornedTargetEntityPolymorphicType()) ? adornedTargetList.getAdornedTargetEntityClassname() : adornedTargetList.getAdornedTargetEntityPolymorphicType()) .newInstance();/*from w w w .j a v a 2s.c o m*/ String targetPath = adornedTargetList.getTargetObjectPath() + "." + adornedTargetList.getTargetIdProperty(); String linkedPath = adornedTargetList.getLinkedObjectPath() + "." + adornedTargetList.getLinkedIdProperty(); getFieldManager().setFieldValue(instance, linkedPath, Long.valueOf(entity.findProperty(linkedPath).getValue())); Object test1 = getFieldManager().getFieldValue(instance, adornedTargetList.getLinkedObjectPath()); Object test1PersistedObject = persistenceManager.getDynamicEntityDao().retrieve(test1.getClass(), Long.valueOf(entity.findProperty(linkedPath).getValue())); Assert.isTrue(test1PersistedObject != null, "Entity not found"); Class<?> type = getFieldManager().getField(instance.getClass(), targetPath).getType(); if (String.class.isAssignableFrom(type)) { getFieldManager().setFieldValue(instance, targetPath, entity.findProperty(targetPath).getValue()); } else { getFieldManager().setFieldValue(instance, targetPath, Long.valueOf(entity.findProperty(targetPath).getValue())); } Object test2 = getFieldManager().getFieldValue(instance, adornedTargetList.getTargetObjectPath()); Object test2PersistedObject; if (String.class.isAssignableFrom(type)) { test2PersistedObject = persistenceManager.getDynamicEntityDao().retrieve(test2.getClass(), entity.findProperty(targetPath).getValue()); } else { test2PersistedObject = persistenceManager.getDynamicEntityDao().retrieve(test2.getClass(), Long.valueOf(entity.findProperty(targetPath).getValue())); } Assert.isTrue(test2PersistedObject != null, "Entity not found"); return instance; }
From source file:org.alfresco.repo.domain.propval.PropertyValueEntity.java
/** * Shortcut method to set the value. It will be converted as required and the necessary fields * will be populated./* w ww . ja va 2 s . c o m*/ * * @param value the value to persist (may be <tt>null</tt>) * @param converter the converter that will perform and type conversion */ public void setValue(Serializable value, PropertyTypeConverter converter) { if (value == null) { this.persistedType = ORDINAL_NULL; this.persistedTypeEnum = PersistedType.NULL; this.longValue = LONG_ZERO; } else { // The converter will be responsible for deserializing, so let it choose // how the data is to be stored. persistedTypeEnum = converter.getPersistentType(value); persistedType = persistedTypeEnum.getOrdinalNumber(); // Get the class to persist as switch (persistedTypeEnum) { case LONG: longValue = converter.convert(Long.class, value); break; case DOUBLE: doubleValue = converter.convert(Double.class, value); break; case STRING: stringValue = converter.convert(String.class, value); if (stringValue.equals(PropertyStringValueEntity.EMPTY_STRING)) { // Oracle: We can't insert empty strings into the column. stringValue = PropertyStringValueEntity.EMPTY_STRING_REPLACEMENT; } break; case CONSTRUCTABLE: // A special case. There is no conversion, so just Store the name of the class. stringValue = value.getClass().getName(); break; case ENUM: // A special case. Store the string-equivalent representation stringValue = converter.convert(String.class, value); break; case SERIALIZABLE: serializableValue = value; break; default: throw new IllegalStateException( "PropertyTypeConverter.convertToPersistentType returned illegal type: " + " Converter: " + converter + "\n" + " Type Returned: " + persistedTypeEnum + "\n" + " From Value: " + value); } } }
From source file:org.sparkcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java
@Override public Entity[] getRecords(Map<String, FieldMetadata> primaryUnfilteredMergedProperties, List<? extends Serializable> records, Map<String, FieldMetadata> alternateUnfilteredMergedProperties, String pathToTargetObject) { Map<String, FieldMetadata> primaryMergedProperties = filterOutCollectionMetadata( primaryUnfilteredMergedProperties); Map<String, FieldMetadata> alternateMergedProperties = filterOutCollectionMetadata( alternateUnfilteredMergedProperties); Entity[] entities = new Entity[records.size()]; int j = 0;/* w w w .j a v a 2s. co m*/ for (Serializable recordEntity : records) { Serializable entity; if (pathToTargetObject != null) { try { entity = (Serializable) getFieldManager().getFieldValue(recordEntity, pathToTargetObject); } catch (Exception e) { throw new PersistenceException(e); } } else { entity = recordEntity; } Entity entityItem = new Entity(); entityItem.setType(new String[] { entity.getClass().getName() }); entities[j] = entityItem; List<Property> props = new ArrayList<Property>(primaryMergedProperties.size()); extractPropertiesFromPersistentEntity(primaryMergedProperties, entity, props); if (alternateMergedProperties != null) { extractPropertiesFromPersistentEntity(alternateMergedProperties, recordEntity, props); } // Try to add the "main name" property. Log a debug message if we can't try { Property p = new Property(); p.setName(MAIN_ENTITY_NAME_PROPERTY); String mainEntityName = (String) MethodUtils.invokeMethod(entity, "getMainEntityName"); p.setValue(mainEntityName); props.add(p); } catch (Exception e) { LOG.debug(String.format("Could not execute the getMainEntityName() method for [%s]", entity.getClass().getName()), e); } // Try to add the alternate id property if available if (alternateMergedProperties != null) { for (Entry<String, FieldMetadata> entry : alternateMergedProperties.entrySet()) { if (entry.getValue() instanceof BasicFieldMetadata) { if (((BasicFieldMetadata) entry.getValue()).getFieldType() == SupportedFieldType.ID) { Map<String, FieldMetadata> alternateOnEntity = new HashMap<String, FieldMetadata>(); alternateOnEntity.put(entry.getKey(), entry.getValue()); List<Property> props2 = new ArrayList<Property>(); extractPropertiesFromPersistentEntity(alternateOnEntity, recordEntity, props2); if (props2.size() == 1) { Property alternateIdProp = props2.get(0); alternateIdProp.setName(ALTERNATE_ID_PROPERTY); props.add(alternateIdProp); } } } } } Property[] properties = new Property[props.size()]; properties = props.toArray(properties); entityItem.setProperties(properties); j++; } return entities; }
From source file:org.nuxeo.ecm.core.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} *///w ww. j av a 2 s . 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 type = ((ListType) type).getFieldType(); Collection<Object> values; if (type.isComplexType()) { values = (Collection) ((ListProperty) prop).getChildren(); } else 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++) { if (type.isComplexType()) { value = (Serializable) convertComplexPropertyToCMIS((ComplexProperty) list.get(i), callContext); } else { value = (Serializable) convertToCMIS(list.get(i)); } list.set(i, value); } return (U) list; } else { // primitive type or complex type if (type.isComplexType()) { value = (Serializable) convertComplexPropertyToCMIS((ComplexProperty) prop, callContext); } else { value = (Serializable) convertToCMIS(value); } return (U) convertToCMIS(value); } } catch (ClientException | IOException e) { throw new CmisRuntimeException(e.toString(), e); } }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.AdornedTargetListPersistenceModule.java
@Override public Entity update(PersistencePackage persistencePackage) throws ServiceException { String[] customCriteria = persistencePackage.getCustomCriteria(); if (customCriteria != null && customCriteria.length > 0) { LOG.warn(/* w w w . jav a 2 s .c om*/ "custom persistence handlers and custom criteria not supported for update types other than BASIC"); } PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Entity entity = persistencePackage.getEntity(); AdornedTargetList adornedTargetList = (AdornedTargetList) persistencePerspective .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST); if (!adornedTargetList.getMutable()) { throw new SecurityServiceException("Field is not mutable"); } try { AdornedTargetRetrieval adornedTargetRetrieval = new AdornedTargetRetrieval(persistencePackage, entity, adornedTargetList).invokeForUpdate(); List<Serializable> records = adornedTargetRetrieval.getRecords(); Assert.isTrue(!CollectionUtils.isEmpty(records), "Entity not found"); int index = adornedTargetRetrieval.getIndex(); Map<String, FieldMetadata> mergedProperties = adornedTargetRetrieval.getMergedProperties(); FieldManager fieldManager = getFieldManager(); Serializable myRecord; if (adornedTargetList.getSortField() != null && entity.findProperty(adornedTargetList.getSortField()).getValue() != null) { myRecord = records.get(index); BigDecimal requestedSequence = new BigDecimal( entity.findProperty(adornedTargetList.getSortField()).getValue()); BigDecimal previousSequence = new BigDecimal(String .valueOf(getFieldManager().getFieldValue(myRecord, adornedTargetList.getSortField()))); if (!previousSequence.equals(requestedSequence)) { // Sequence has changed. Rebalance the list myRecord = records.remove(index); myRecord = createPopulatedInstance(myRecord, entity, mergedProperties, false); if (CollectionUtils.isEmpty(records)) { records.add(myRecord); } else { records.add(requestedSequence.intValue() - 1, myRecord); } index = 1; Class<?> type = fieldManager.getField(myRecord.getClass(), adornedTargetList.getSortField()) .getType(); boolean isBigDecimal = BigDecimal.class.isAssignableFrom(type); for (Serializable record : records) { fieldManager.setFieldValue(record, adornedTargetList.getSortField(), isBigDecimal ? new BigDecimal(index) : Long.valueOf(index)); index++; } } } else { myRecord = records.get(index); } String ceilingEntityFullyQualifiedClassname = persistencePackage .getCeilingEntityFullyQualifiedClassname(); 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(), ""); myRecord = createPopulatedInstance(myRecord, entity, mergedProperties, false); myRecord = persistenceManager.getDynamicEntityDao().merge(myRecord); List<Serializable> myList = new ArrayList<Serializable>(); myList.add(myRecord); Entity[] payload = getRecords(mergedPropertiesTarget, myList, mergedProperties, adornedTargetList.getTargetObjectPath()); entity = payload[0]; return entity; } catch (Exception e) { throw new ServiceException("Problem updating entity : " + e.getMessage(), e); } }