/** * Build a map of logical to physical names for use in Orm Updates for a given descriptor. * * <p>This includes the dbWrite scalar properties and imported foreign key properties. */ public static Map<String, String> build(BeanDescriptor<?> descriptor) { Map<String, String> deployMap = new HashMap<String, String>(); String shortName = descriptor.getName(); String beanName = shortName.toLowerCase(); deployMap.put(beanName, descriptor.getBaseTable()); BeanProperty[] baseScalar = descriptor.propertiesBaseScalar(); for (BeanProperty baseProp : baseScalar) { // excluding formula, secondary table properties if (baseProp.isDbInsertable() || baseProp.isDbUpdatable()) { deployMap.put(baseProp.getName().toLowerCase(), baseProp.getDbColumn()); } } BeanPropertyAssocOne<?>[] oneImported = descriptor.propertiesOneImported(); for (BeanPropertyAssocOne<?> assocOne : oneImported) { ImportedId importedId = assocOne.getImportedId(); if (importedId == null) { String m = descriptor.getFullName() + " importedId is null for associated: " + assocOne.getFullBeanName(); logger.log(Level.SEVERE, m); } else if (importedId.isScalar()) { deployMap.put(importedId.getLogicalName(), importedId.getDbColumn()); } } return deployMap; }
/** Return a bean from the bean cache. */ @SuppressWarnings("unchecked") private T beanCacheGetInternal(Object id, Boolean readOnly, PersistenceContext context) { CachedBeanData data = (CachedBeanData) getBeanCache().get(id); if (data == null) { if (beanLog.isTraceEnabled()) { beanLog.trace(" GET {}({}) - cache miss", cacheName, id); } return null; } if (cacheSharableBeans && !Boolean.FALSE.equals(readOnly)) { Object bean = data.getSharableBean(); if (bean != null) { if (beanLog.isTraceEnabled()) { beanLog.trace(" GET {}({}) - hit shared bean", cacheName, id); } if (desc.isReadAuditing()) { desc.readAuditBean("l2", "", bean); } return (T) bean; } } return (T) loadBean(id, readOnly, data, context); }
private static Object getProperty(Object object, String name) throws InvocationTargetException { try { Object value; if (name.contains("[")) { value = getIndexedProperty(object, name); } else { if (object instanceof Map<?, ?>) { int index = name.indexOf('.'); if (index > -1) { String key = name.substring(0, index); value = getProperty(((Map<?, ?>) object).get(key), name.substring(index + 1)); } else { value = ((Map<?, ?>) object).get(name); } } else { int index = name.indexOf('.'); if (index > -1) { String newName = name.substring(0, index); value = getProperty(getObject(object, newName), name.substring(index + 1)); } else { BeanDescriptor cd = getBeanDescriptor(object.getClass()); Method method = cd.getGetter(name); if (method == null) { throw new NoSuchMethodException( "No GET method for property " + name + " on instance of " + object.getClass().getName()); } try { value = method.invoke(object, NO_ARGUMENTS); } catch (Throwable t) { throw unwrapThrowable(t); } } } } return value; } catch (InvocationTargetException e) { throw e; } catch (Throwable t) { if (object == null) { throw new InvocationTargetException( t, "Could not get property '" + name + "' from null reference. Cause: " + t.toString()); } else { throw new InvocationTargetException( t, "Could not get property '" + name + "' from " + object.getClass().getName() + ". Cause: " + t.toString()); } } }
/*lazy BeanDescriptor*/ private static BeanDescriptor getBdescriptor() { BeanDescriptor beanDescriptor = new BeanDescriptor(Bean21341Hidden.class, null); beanDescriptor.setShortDescription("ShortDescription"); // GEN-HEADEREND:BeanDescriptor beanDescriptor.setValue("helpID", "HelpID"); beanDescriptor.setValue("propertiesHelpID", "PropertiesHelpID"); beanDescriptor.setValue("expertHelpID", "ExpertHelpID"); // Here you can add code for customizing the BeanDescriptor. return beanDescriptor; } // GEN-LAST:BeanDescriptor
private static BeanDescriptor getBdescriptor() { // GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. if (beanDescriptor == null) beanDescriptor = new BeanDescriptor(StrokeToolBarBeanInfo.class); beanDescriptor.setValue("isContainer", Boolean.FALSE); beanDescriptor.setDisplayName("StrokeToolPane"); return beanDescriptor; } // GEN-LAST:BeanDescriptor
private static BeanDescriptor getBdescriptor() { // GEN-HEADEREND:BeanDescriptor // Here you can add code for customizing the BeanDescriptor. if (beanDescriptor == null) { beanDescriptor = new BeanDescriptor(JAttributeTextFieldBeanInfo.class); } beanDescriptor.setValue("isContainer", Boolean.FALSE); beanDescriptor.setDisplayName("JAttributeTextField"); return beanDescriptor; } // GEN-LAST:BeanDescriptor
/** * For a bean built from the cache this sets up its persistence context for future lazy loading * etc. */ private void setupContext(Object bean, PersistenceContext context) { if (context == null) { context = new DefaultPersistenceContext(); } // Not using a loadContext for beans coming out of L2 cache // so that means no batch lazy loading for these beans EntityBean entityBean = (EntityBean) bean; EntityBeanIntercept ebi = entityBean._ebean_getIntercept(); ebi.setPersistenceContext(context); Object id = desc.getId(entityBean); desc.contextPut(context, id, bean); }
private CachedManyIds createManyIds(BeanPropertyAssocMany<?> many, Object details) { BeanDescriptor<?> targetDescriptor = many.getTargetDescriptor(); List<Object> idList = new ArrayList<>(); Collection<?> actualDetails = BeanCollectionUtil.getActualEntries(details); if (actualDetails == null) { return null; } for (Object bean : actualDetails) { idList.add(targetDescriptor.getId((EntityBean) bean)); } return new CachedManyIds(idList); }
/** * Initialise the property before returning to client code. Used to initialise variables that * can't be done in construction due to recursive issues. */ public void initialise() { // do nothing for normal BeanProperty if (!isTransient && scalarType == null) { String msg = "No ScalarType assigned to " + descriptor.getFullName() + "." + getName(); throw new RuntimeException(msg); } }
/** Put a bean into the bean cache. */ void beanCachePut(EntityBean bean) { if (desc.inheritInfo != null) { desc.descOf(bean.getClass()).cacheBeanPutDirect(bean); } else { beanCachePutDirect(bean); } }
/** Load the entity bean from cache data given this is the root bean type. */ EntityBean loadBeanDirect( Object id, Boolean readOnly, CachedBeanData data, PersistenceContext context) { if (context == null) { context = new DefaultPersistenceContext(); } EntityBean bean = desc.createEntityBean(); id = desc.convertSetId(id, bean); CachedBeanDataToBean.load(desc, bean, data, context); EntityBeanIntercept ebi = bean._ebean_getIntercept(); // Not using a loadContext for beans coming out of L2 cache // so that means no batch lazy loading for these beans ebi.setBeanLoader(desc.getEbeanServer()); if (Boolean.TRUE.equals(readOnly)) { ebi.setReadOnly(true); } ebi.setPersistenceContext(context); desc.contextPut(context, id, bean); if (beanLog.isTraceEnabled()) { beanLog.trace(" GET {}({}) - hit", cacheName, id); } if (desc.isReadAuditing()) { desc.readAuditBean("l2", "", bean); } return bean; }
private String tableAliasIntern( BeanDescriptor<?> descriptor, String s, boolean dbEncrypted, String dbColumn) { if (descriptor != null) { s = StringHelper.replaceString(s, "${ta}.", "${}"); s = StringHelper.replaceString(s, "${ta}", "${}"); if (dbEncrypted) { s = dbEncryptFunction.getDecryptSql(s); String namedParam = ":encryptkey_" + descriptor.getBaseTable() + "___" + dbColumn; s = StringHelper.replaceString(s, "?", namedParam); } } return InternString.intern(s); }
/** Try to load the bean collection from cache return true if successful. */ boolean manyPropLoad( BeanPropertyAssocMany<?> many, BeanCollection<?> bc, Object parentId, Boolean readOnly) { CachedManyIds entry = manyPropGet(parentId, many.getName()); if (entry == null) { // not in cache so return unsuccessful return false; } Object ownerBean = bc.getOwnerBean(); EntityBeanIntercept ebi = ((EntityBean) ownerBean)._ebean_getIntercept(); PersistenceContext persistenceContext = ebi.getPersistenceContext(); BeanDescriptor<?> targetDescriptor = many.getTargetDescriptor(); List<Object> idList = entry.getIdList(); bc.checkEmptyLazyLoad(); for (Object id : idList) { Object refBean = targetDescriptor.createReference(readOnly, false, id, persistenceContext); many.add(bc, (EntityBean) refBean); } return true; }
/** Derive the cache notify flags. */ void deriveNotifyFlags() { cacheNotifyOnAll = (beanCache != null || queryCache != null); cacheNotifyOnDelete = !cacheNotifyOnAll && isNotifyOnDeletes(); if (logger.isDebugEnabled()) { if (isBeanCaching() || isQueryCaching() || cacheNotifyOnAll || cacheNotifyOnDelete) { String notifyMode = cacheNotifyOnAll ? "All" : (cacheNotifyOnDelete ? "Delete" : "None"); logger.debug( "l2 caching on {} - beanCaching:{} queryCaching:{} notifyMode:{} ", desc.getFullName(), isBeanCaching(), isQueryCaching(), notifyMode); } } }
static { try { descr = new BeanDescriptor(AppletExecutor.class); ResourceBundle bundle = NbBundle.getBundle(AppletExecutorBeanInfo.class); descr.setName(bundle.getString("CTL_Exec_Name")); prop = new PropertyDescriptor[1]; prop[0] = new PropertyDescriptor("externalExecutor", AppletExecutor.class); // 0 prop[0].setDisplayName(bundle.getString("PROP_External_path")); prop[0].setShortDescription(bundle.getString("HINT_External_path")); } catch (IntrospectionException ex) { if (Boolean.getBoolean("netbeans.debug.exceptions")) { ex.printStackTrace(); } } }
/** Put the bean into the bean cache. */ void beanCachePutDirect(EntityBean bean) { CachedBeanData beanData = beanExtractData(desc, bean); Object id = desc.getId(bean); if (beanLog.isDebugEnabled()) { beanLog.debug(" PUT {}({}) data:{}", cacheName, id, beanData); } getBeanCache().put(id, beanData); if (naturalKeyProperty != null) { Object naturalKey = beanData.getData(naturalKeyProperty); if (naturalKey != null) { if (natLog.isDebugEnabled()) { natLog.debug(" PUT {}({}, {})", cacheName, naturalKey, id); } naturalKeyCache.get().put(naturalKey, id); } } }
/** Add appropriate cache changes to support insert. */ void handleInsert(PersistRequestBean<T> insertRequest, CacheChangeSet changeSet) { queryCacheClear(changeSet); cacheDeleteImported(false, insertRequest.getEntityBean(), changeSet); changeSet.addBeanInsert(desc.getBaseTable()); }
/** * Create a Matching BeanProperty with some attributes overridden. * * <p>Primarily for supporting Embedded beans with overridden dbColumn mappings. */ public BeanProperty(BeanProperty source, BeanPropertyOverride override) { this.descriptor = source.descriptor; this.name = InternString.intern(source.getName()); this.propertyIndex = source.propertyIndex; this.dbColumn = InternString.intern(override.getDbColumn()); // override with sqlFormula not currently supported this.sqlFormulaJoin = null; this.sqlFormulaSelect = null; this.formula = false; this.excludedFromHistory = source.excludedFromHistory; this.draft = source.draft; this.draftDirty = source.draftDirty; this.draftOnly = source.draftOnly; this.draftReset = source.draftReset; this.softDelete = source.softDelete; this.softDeleteDbSet = source.softDeleteDbSet; this.softDeleteDbPredicate = source.softDeleteDbPredicate; this.fetchEager = source.fetchEager; this.unidirectionalShadow = source.unidirectionalShadow; this.discriminator = source.discriminator; this.localEncrypted = source.isLocalEncrypted(); this.isTransient = source.isTransient(); this.secondaryTable = source.isSecondaryTable(); this.secondaryTableJoin = source.secondaryTableJoin; this.secondaryTableJoinPrefix = source.secondaryTableJoinPrefix; this.dbComment = source.dbComment; this.dbBind = source.getDbBind(); this.dbEncrypted = source.isDbEncrypted(); this.dbEncryptedType = source.getDbEncryptedType(); this.dbEncryptFunction = source.dbEncryptFunction; this.dbRead = source.isDbRead(); this.dbInsertable = source.isDbInsertable(); this.dbUpdatable = source.isDbUpdatable(); this.nullable = source.isNullable(); this.unique = source.isUnique(); this.naturalKey = source.isNaturalKey(); this.dbLength = source.getDbLength(); this.dbScale = source.getDbScale(); this.dbColumnDefn = InternString.intern(source.getDbColumnDefn()); this.dbColumnDefault = source.dbColumnDefault; this.inherited = source.isInherited(); this.owningType = source.owningType; this.local = owningType.equals(descriptor.getBeanType()); this.version = source.isVersion(); this.embedded = source.isEmbedded(); this.id = source.isId(); this.generatedProperty = source.getGeneratedProperty(); this.getter = source.getter; this.setter = source.setter; this.dbType = source.getDbType(true); this.scalarType = source.scalarType; this.lob = isLobType(dbType); this.propertyType = source.getPropertyType(); this.field = source.getField(); this.docOptions = source.docOptions; this.elPlaceHolder = override.replace(source.elPlaceHolder, source.dbColumn); this.elPlaceHolderEncrypted = override.replace(source.elPlaceHolderEncrypted, source.dbColumn); this.jsonSerialize = source.jsonSerialize; this.jsonDeserialize = source.jsonDeserialize; }
/** * Retrieve a field. * * @param key field name * @return the field (even if the field does not exist you get a field) */ public Field field(String key) { // Value String fieldValue = null; if (data.containsKey(key)) { fieldValue = data.get(key); } else { if (value.isPresent()) { BeanWrapper beanWrapper = new BeanWrapperImpl(value.get()); beanWrapper.setAutoGrowNestedPaths(true); String objectKey = key; if (rootName != null && key.startsWith(rootName + ".")) { objectKey = key.substring(rootName.length() + 1); } if (beanWrapper.isReadableProperty(objectKey)) { Object oValue = beanWrapper.getPropertyValue(objectKey); if (oValue != null) { final String objectKeyFinal = objectKey; fieldValue = withRequestLocale( () -> formatters.print( beanWrapper.getPropertyTypeDescriptor(objectKeyFinal), oValue)); } } } } // Error List<ValidationError> fieldErrors = errors.get(key); if (fieldErrors == null) { fieldErrors = new ArrayList<>(); } // Format Tuple<String, List<Object>> format = null; BeanWrapper beanWrapper = new BeanWrapperImpl(blankInstance()); beanWrapper.setAutoGrowNestedPaths(true); try { for (Annotation a : beanWrapper.getPropertyTypeDescriptor(key).getAnnotations()) { Class<?> annotationType = a.annotationType(); if (annotationType.isAnnotationPresent(play.data.Form.Display.class)) { play.data.Form.Display d = annotationType.getAnnotation(play.data.Form.Display.class); if (d.name().startsWith("format.")) { List<Object> attributes = new ArrayList<>(); for (String attr : d.attributes()) { Object attrValue = null; try { attrValue = a.getClass().getDeclaredMethod(attr).invoke(a); } catch (Exception e) { // do nothing } attributes.add(attrValue); } format = Tuple(d.name(), attributes); } } } } catch (NullPointerException e) { // do nothing } // Constraints List<Tuple<String, List<Object>>> constraints = new ArrayList<>(); Class<?> classType = backedType; String leafKey = key; if (rootName != null && leafKey.startsWith(rootName + ".")) { leafKey = leafKey.substring(rootName.length() + 1); } int p = leafKey.lastIndexOf('.'); if (p > 0) { classType = beanWrapper.getPropertyType(leafKey.substring(0, p)); leafKey = leafKey.substring(p + 1); } if (classType != null) { BeanDescriptor beanDescriptor = play.data.validation.Validation.getValidator().getConstraintsForClass(classType); if (beanDescriptor != null) { PropertyDescriptor property = beanDescriptor.getConstraintsForProperty(leafKey); if (property != null) { constraints = Constraints.displayableConstraint(property.getConstraintDescriptors()); } } } return new Field(this, key, constraints, format, fieldErrors, fieldValue); }
@Override public <T> BeanDescriptor<T> provide(Class<T> ofClass, Type ofType, Genson genson) { Map<String, LinkedList<PropertyMutator>> mutatorsMap = new LinkedHashMap<String, LinkedList<PropertyMutator>>(); Map<String, LinkedList<PropertyAccessor>> accessorsMap = new LinkedHashMap<String, LinkedList<PropertyAccessor>>(); List<BeanCreator> creators = provideBeanCreators(ofType, genson); provideBeanPropertyAccessors(ofType, accessorsMap, genson); provideBeanPropertyMutators(ofType, mutatorsMap, genson); List<PropertyAccessor> accessors = new ArrayList<PropertyAccessor>(accessorsMap.size()); for (Map.Entry<String, LinkedList<PropertyAccessor>> entry : accessorsMap.entrySet()) { PropertyAccessor accessor = checkAndMergeAccessors(entry.getKey(), entry.getValue()); // in case of... if (accessor != null) accessors.add(accessor); } Map<String, PropertyMutator> mutators = new HashMap<String, PropertyMutator>(mutatorsMap.size()); for (Map.Entry<String, LinkedList<PropertyMutator>> entry : mutatorsMap.entrySet()) { PropertyMutator mutator = checkAndMergeMutators(entry.getKey(), entry.getValue()); if (mutator != null) mutators.put(mutator.name, mutator); } BeanCreator ctr = checkAndMerge(ofType, creators); if (ctr != null) mergeAccessorsWithCreatorProperties(ofType, accessors, ctr); if (ctr != null) mergeMutatorsWithCreatorProperties(ofType, mutators, ctr); // 1 - prepare the converters for the accessors for (PropertyAccessor accessor : accessors) { accessor.propertySerializer = provide(accessor, genson); } // 2 - prepare the mutators for (PropertyMutator mutator : mutators.values()) { mutator.propertyDeserializer = provide(mutator, genson); } // 3 - prepare the converters for creator parameters if (ctr != null) { for (PropertyMutator mutator : ctr.parameters.values()) { mutator.propertyDeserializer = provide(mutator, genson); } } // lets fail fast if the BeanDescriptor has been built for the wrong type. // another option could be to pass in all the methods an additional parameter Class<T> that // would not necessarily correspond to the rawClass of ofType. In fact we authorize that // ofType rawClass is different from Class<T>, but the BeanDescriptor must match! BeanDescriptor<T> descriptor = create(ofClass, ofType, ctr, accessors, mutators, genson); if (!ofClass.isAssignableFrom(descriptor.getOfClass())) throw new ClassCastException( "Actual implementation of BeanDescriptorProvider " + getClass() + " seems to do something wrong. Expected BeanDescriptor for type " + ofClass + " but provided BeanDescriptor for type " + descriptor.getOfClass()); return descriptor; }
/** * Gets an instance of BeanDescriptor for the specified class. * * @param clazz The class for which to lookup the ClassDescriptor cache. * @return The ClassDescriptor cache for the class */ private static BeanDescriptor getBeanDescriptor(Class<?> clazz) { return BeanDescriptor.getInstance(clazz); }
private static void setProperty(Object object, String name, Object value) throws InvocationTargetException { try { if (name.contains("[")) { setIndexedProperty(object, name, value); } else { if (object instanceof Map<?, ?>) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) object; map.put(name, value); } else { BeanDescriptor cd = getBeanDescriptor(object.getClass()); Method method = cd.getSetter(name); if (method == null) { throw new NoSuchMethodException( "No SET method for property " + name + " on instance of " + object.getClass().getName()); } Object[] params = new Object[] {value}; try { method.invoke(object, params); } catch (Throwable t) { throw unwrapThrowable(t); } } } } catch (InvocationTargetException e) { throw e; } catch (Throwable t) { try { if (value != null) { MethodUtils.invokeSetter(object, name, value); return; } } catch (Throwable tt) { // ignore } if (object == null) { throw new InvocationTargetException( t, "Could not set property '" + name + "' to value '" + value + "' for null reference. Cause: " + t.toString()); } else { throw new InvocationTargetException( t, "Could not set property '" + name + "' to value '" + value + "' for " + object.getClass().getName() + ". Cause: " + t.toString()); } } }
/** Return true if this is a ManyToMany with history support (on the intersection table). */ public boolean isManyToManyWithHistory() { return !excludedFromHistory && descriptor.isHistorySupport(); }
/** Load the embedded bean given this is the bean type. */ EntityBean embeddedBeanLoadDirect(CachedBeanData data, PersistenceContext context) { EntityBean bean = desc.createEntityBean(); CachedBeanDataToBean.load(desc, bean, data, context); return bean; }
/** Return the full name of this property. */ public String getFullBeanName() { return descriptor.getFullName() + "." + name; }
/** Return the encrypt key for the column matching this property. */ public EncryptKey getEncryptKey() { return descriptor.getEncryptKey(this); }