List of usage examples for org.apache.commons.beanutils PropertyUtils getSimpleProperty
public static Object getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Return the value of the specified simple property of the specified bean, with no type conversions.
For more details see PropertyUtilsBean
.
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * Tests that calling/*from w w w . j a va 2s .com*/ * {@link SPPersister#persistObject(String, String, String, int)} for a * session persister will create a new object and set all of the properties * on the object. */ public void testPersisterAddsNewObject() throws Exception { SPObject wo = getObjectUnderTest(); wo.setMagicEnabled(false); WabitSessionPersister persister = new WabitSessionPersister("test persister", session, session.getWorkspace(), true); WorkspacePersisterListener listener = new WorkspacePersisterListener(session, persister, true); WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter( new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); //Set all possible values to new values for testing. Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents(); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnoreForEvents.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(wo, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + wo.getClass().getName()); } } SPObject parent = wo.getParent(); int oldChildCount = parent.getChildren().size(); listener.transactionStarted(null); listener.childRemoved( new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().indexOf(wo), EventType.REMOVED)); listener.transactionEnded(null); //persist the object wo.setParent(parent); listener.transactionStarted(null); listener.childAdded( new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().size(), EventType.ADDED)); listener.transactionEnded(null); //the object must now be added to the super parent assertEquals(oldChildCount, parent.getChildren().size()); SPObject persistedObject = parent.getChildren().get(parent.childPositionOffset(wo.getClass())); persistedObject.setMagicEnabled(false); //check all the properties are what we expect on the new object Set<String> ignorableProperties = getPropertiesToNotPersistOnObjectPersist(); List<String> settablePropertyNames = new ArrayList<String>(); for (PropertyDescriptor pd : settableProperties) { settablePropertyNames.add(pd.getName()); } settablePropertyNames.removeAll(ignorableProperties); for (String persistedPropertyName : settablePropertyNames) { Class<?> classType = null; for (PropertyDescriptor propertyDescriptor : settableProperties) { if (propertyDescriptor.getName().equals(persistedPropertyName)) { classType = propertyDescriptor.getPropertyType(); break; } } logger.debug("Persisted object is of type " + persistedObject.getClass()); Object oldVal = PropertyUtils.getSimpleProperty(wo, persistedPropertyName); Object newVal = PropertyUtils.getSimpleProperty(persistedObject, persistedPropertyName); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && persistedPropertyName.equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } Object basicOldVal = converterFactory.convertToBasicType(oldVal, additionalVals.toArray()); Object basicNewVal = converterFactory.convertToBasicType(newVal, additionalVals.toArray()); logger.debug("Property " + persistedPropertyName + ". oldVal is \"" + basicOldVal + "\" but newVal is \"" + basicNewVal + "\""); assertPersistedValuesAreEqual(oldVal, newVal, basicOldVal, basicNewVal, classType); } }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * Tests passing an object to an {@link SPPersisterListener} will persist * the object and all of the properties that have setters. *///w w w. j a va 2s.c o m public void testSPListenerPersistsNewObjects() throws Exception { CountingSPPersister persister = new CountingSPPersister(); NewValueMaker valueMaker = createNewValueMaker(root, getPLIni()); SPObject objectUnderTest = getSPObjectUnderTest(); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(objectUnderTest, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + objectUnderTest.getClass().getName()); } } //persist the object to the new target root new SPPersisterListener(persister, getConverter()).persistObject(objectUnderTest, objectUnderTest.getParent().getChildren(objectUnderTest.getClass()).indexOf(objectUnderTest)); assertTrue(persister.getPersistPropertyCount() > 0); assertEquals(getSPObjectUnderTest().getUUID(), persister.getPersistObjectList().get(0).getUUID()); //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } Object newValue = null; boolean found = false; for (PersistedSPOProperty persistedSPO : persister.getPersistPropertyList()) { if (persistedSPO.getPropertyName().equals(property.getName()) && persistedSPO.getUUID().equals(getSPObjectUnderTest().getUUID())) { newValue = persistedSPO.getNewValue(); found = true; break; } } assertTrue("Could not find the persist call for property " + property.getName(), found); if (oldVal == null) { assertNull(newValue); } else { assertPersistedValuesAreEqual(oldVal, getConverter().convertToComplexType(newValue, oldVal.getClass()), getConverter().convertToBasicType(oldVal), newValue, property.getPropertyType()); } } }
From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java
private OperationResponse delete(final AbstractEntity record, final Connection conn) throws Exception { OperationResponse response = new OperationResponse(); Class<?> type = record.getClass(); SimpleDbQuery parser = new SimpleDbQuery(); String sql = parser.getDeleteQuery(type); PreparedStatement pstmnt = conn.prepareStatement(sql); try {/*from w w w. j ava2 s .c om*/ List<StructAttributeReflect> keyattrs = new ArrayList<StructAttributeReflect>(); StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(type); response.setEntity(enref.Entity); response.setKey(getEntityKey(record)); for (StructAttributeReflect attr : enref.Attributes) { if (attr == null) { continue; } if (attr.IsKeyColumn) { keyattrs.add(attr); } } for (int ii = 0; ii < keyattrs.size(); ii++) { Object value = PropertyUtils.getSimpleProperty(record, keyattrs.get(ii).Field.getName()); setPreparedValue(pstmnt, ii + 1, keyattrs.get(ii), value, record); } int count = pstmnt.executeUpdate(); if (count > 0) { response.setOperation(EnumPersistenceOperation.Deleted); } else { response.setOperation(EnumPersistenceOperation.Ignored); } log.debug("[" + record.getClass().getCanonicalName() + "] deleted [count=" + count + "]"); return response; } finally { if (pstmnt != null && !pstmnt.isClosed()) { pstmnt.close(); } } }
From source file:catalina.mbeans.MBeanUtils.java
/** * Create an <code>ObjectName</code> for this * <code>Connector</code> object. * * @param domain Domain in which this name is to be created * @param connector The Connector to be named * * @exception MalformedObjectNameException if a name cannot be created *///from w ww . j a v a2 s .c o m public static ObjectName createObjectName(String domain, Connector connector) throws MalformedObjectNameException { ObjectName name = null; if (connector instanceof HttpConnector) { HttpConnector httpConnector = (HttpConnector) connector; Service service = httpConnector.getService(); String serviceName = null; if (service != null) serviceName = service.getName(); name = new ObjectName(domain + ":type=Connector" + ",service=" + serviceName + ",port=" + httpConnector.getPort() + ",address=" + httpConnector.getAddress()); return (name); } else if (connector instanceof org.apache.catalina.connector.http10.HttpConnector) { org.apache.catalina.connector.http10.HttpConnector httpConnector = (org.apache.catalina.connector.http10.HttpConnector) connector; Service service = httpConnector.getService(); String serviceName = null; if (service != null) serviceName = service.getName(); name = new ObjectName(domain + ":type=Connector" + ",service=" + serviceName + ",port=" + httpConnector.getPort() + ",address=" + httpConnector.getAddress()); return (name); } else if ("org.apache.ajp.tomcat4.Ajp13Connector".equals(connector.getClass().getName())) { try { String address = (String) PropertyUtils.getSimpleProperty(connector, "address"); Integer port = (Integer) PropertyUtils.getSimpleProperty(connector, "port"); Service service = connector.getService(); String serviceName = null; if (service != null) serviceName = service.getName(); name = new ObjectName(domain + ":type=Connector" + ",service=" + serviceName + ",port=" + port + ",address=" + address); return (name); } catch (Exception e) { throw new MalformedObjectNameException("Cannot create object name for " + connector + e); } } else if ("org.apache.coyote.tomcat4.CoyoteConnector".equals(connector.getClass().getName())) { try { String address = (String) PropertyUtils.getSimpleProperty(connector, "address"); Integer port = (Integer) PropertyUtils.getSimpleProperty(connector, "port"); Service service = connector.getService(); String serviceName = null; if (service != null) serviceName = service.getName(); name = new ObjectName(domain + ":type=Connector" + ",service=" + serviceName + ",port=" + port + ",address=" + address); return (name); } catch (Exception e) { throw new MalformedObjectNameException("Cannot create object name for " + connector + e); } } else { throw new MalformedObjectNameException("Cannot create object name for " + connector); } }
From source file:com.chiralbehaviors.CoRE.meta.models.JobModelTest.java
/** * Returns a list of fields that do not match between job and chronology * * @param job/*from w w w . jav a 2 s . c o m*/ * @param jobChronology * @return * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws NoSuchMethodException * @throws InvocationTargetException */ private List<String> verifyChronologyFields(JobRecord job, JobChronologyRecord jobChronology) throws Exception { String[] fieldsToMatch = new String[] { "status", "requester", "assignTo", "deliverFrom", "deliverTo" }; List<String> unmatchedFields = new LinkedList<>(); if (!jobChronology.getJob().equals(job.getId())) { unmatchedFields.add("job"); return unmatchedFields; } for (String field : fieldsToMatch) { UUID jobRf = (UUID) PropertyUtils.getSimpleProperty(job, field); UUID chronoRf = (UUID) PropertyUtils.getSimpleProperty(jobChronology, field); if (chronoRf == null && jobRf == null) { continue; } if (!chronoRf.equals(jobRf)) { unmatchedFields.add(field); } } return unmatchedFields; }
From source file:catalina.core.StandardServer.java
/** * Store the relevant attributes of the specified JavaBean. * * @param writer PrintWriter to which we are storing * @param include Should we include a <code>className</code> attribute? * @param bean Bean whose properties are to be rendered as attributes, * * @exception Exception if an exception occurs while storing *//*from ww w. jav a2 s . c o m*/ private void storeAttributes(PrintWriter writer, boolean include, Object bean) throws Exception { // Render a className attribute if requested if (include) { writer.print(" className=\""); writer.print(bean.getClass().getName()); writer.print("\""); } // Acquire the list of properties for this bean PropertyDescriptor descriptors[] = PropertyUtils.getPropertyDescriptors(bean); if (descriptors == null) { descriptors = new PropertyDescriptor[0]; } // Render the relevant properties of this bean String className = bean.getClass().getName(); for (int i = 0; i < descriptors.length; i++) { if (descriptors[i] instanceof IndexedPropertyDescriptor) { continue; // Indexed properties are not persisted } if (!isPersistable(descriptors[i].getPropertyType()) || (descriptors[i].getReadMethod() == null) || (descriptors[i].getWriteMethod() == null)) { continue; // Must be a read-write primitive or String } Object value = PropertyUtils.getSimpleProperty(bean, descriptors[i].getName()); if (value == null) { continue; // Null values are not persisted } if (isException(className, descriptors[i].getName())) { continue; // Skip the specified exceptions } if (!(value instanceof String)) { value = value.toString(); } writer.print(' '); writer.print(descriptors[i].getName()); writer.print("=\""); String strValue = convertStr((String) value); writer.print(strValue); writer.print("\""); } }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * This test will make changes to the {@link SPObject} under test and then * cause an exception forcing the persister to roll back the changes in the * object.//from w w w .ja v a 2s .co m * <p> * Both the changes have to come through the persister initially before the * exception and they have to be reset after the exception. */ public void testSessionPersisterRollsBackProperties() throws Exception { SPObject objectUnderTest = getSPObjectUnderTest(); final Map<PropertyDescriptor, Object> initialProperties = new HashMap<PropertyDescriptor, Object>(); final Map<PropertyDescriptor, Object> newProperties = new HashMap<PropertyDescriptor, Object>(); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); Set<String> ignorePropertySet = getRollbackTestIgnorePropertySet(); NewValueMaker valueMaker = createNewValueMaker(getRootObject(), getPLIni()); SPSessionPersister persister = new TestingSessionPersister("tester", getRootObject(), getConverter()); persister.setWorkspaceContainer(getRootObject().getWorkspaceContainer()); failureReason = null; SPPersisterListener listener = new SPPersisterListener(new CountingSPPersister(), converter) { private boolean transactionAlreadyFinished = false; @Override public void transactionEnded(TransactionEvent e) { if (transactionAlreadyFinished) return; transactionAlreadyFinished = true; try { for (Map.Entry<PropertyDescriptor, Object> newProperty : newProperties.entrySet()) { Object objectUnderTest = getSPObjectUnderTest(); Object newVal = newProperty.getValue(); Object basicNewValue = converter.convertToBasicType(newVal); Object newValAfterSet = PropertyUtils.getSimpleProperty(objectUnderTest, newProperty.getKey().getName()); Object basicExpectedValue = converter.convertToBasicType(newValAfterSet); logger.debug("Testing property " + newProperty.getKey().getName()); assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue, newProperty.getKey().getPropertyType()); } } catch (Throwable ex) { failureReason = ex; throw new RuntimeException(ex); } throw new RuntimeException("Forcing rollback."); } }; //Transactions begin and commits are currently sent on the workspace. getRootObject().getParent().addSPListener(listener); persister.begin(); for (PropertyDescriptor property : settableProperties) { Object oldVal; //Changing the UUID of the object makes it referenced as a different object //and would make the check later in this test fail. if (property.getName().equals("UUID")) continue; if (!propertiesToPersist.contains(property.getName())) continue; if (ignorePropertySet.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } initialProperties.put(property, oldVal); //special case for parent types. If a specific wabit object has a tighter parent then //WabitObject the getParentClass should return the parent type. Class<?> propertyType = property.getPropertyType(); if (property.getName().equals("parent")) { propertyType = getSPObjectUnderTest().getClass().getMethod("getParent").getReturnType(); logger.debug("Persisting parent, type is " + propertyType); } Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName()); DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = converter.convertToBasicType(newVal); persister.begin(); persister.persistProperty(objectUnderTest.getUUID(), property.getName(), type, converter.convertToBasicType(oldVal), basicNewValue); persister.commit(); newProperties.put(property, newVal); } try { persister.commit(); fail("An exception should make the persister hit the exception block."); } catch (Exception e) { //continue, exception expected. } if (failureReason != null) { throw new RuntimeException("Failed when asserting properties were " + "fully persisted.", failureReason); } for (Map.Entry<PropertyDescriptor, Object> entry : initialProperties.entrySet()) { assertEquals("Property " + entry.getKey().getName() + " did not match after rollback.", entry.getValue(), PropertyUtils.getSimpleProperty(objectUnderTest, entry.getKey().getName())); } }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * Reflective test that the wabit object can be persisted as an object and all of * its properties are persisted with it. *///from w w w . j av a2 s. co m public void testPersistsObjectAsChild() throws Exception { //This may need to actually have the wabit object as a child to itself. WabitObject parent = new StubWabitObject(); CountingWabitPersister persister = new CountingWabitPersister(); WorkspacePersisterListener listener = new WorkspacePersisterListener( new StubWabitSession(new StubWabitSessionContext()), persister, true); SPObject wo = getObjectUnderTest(); if (wo.getParent() == null) { wo.setParent(parent); } listener.childAdded(new SPChildEvent(parent, wo.getClass(), wo, 0, EventType.ADDED)); assertTrue(persister.getPersistObjectCount() > 0); PersistedSPObject persistedWabitObject = persister.getAllPersistedObjects().get(0); assertEquals(wo.getClass().getSimpleName(), persistedWabitObject.getType()); assertEquals(wo.getUUID(), persistedWabitObject.getUUID()); //confirm we get one persist property for each getter/setter pair //confirm we get one persist property for each value in one of the constructors in the object. List<PropertyDescriptor> settableProperties = new ArrayList<PropertyDescriptor>( Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass()))); List<PersistedSPOProperty> allPropertyChanges = persister.getAllPropertyChanges(); Set<String> ignorableProperties = getPropertiesToNotPersistOnObjectPersist(); ignorableProperties.addAll(getPropertiesToIgnoreForEvents()); List<PersistedSPOProperty> changesOnObject = new ArrayList<PersistedSPOProperty>(); logger.debug("Looking through properties registered to persist..."); for (int i = allPropertyChanges.size() - 1; i >= 0; i--) { if (allPropertyChanges.get(i).getUUID().equals(wo.getUUID())) { changesOnObject.add(allPropertyChanges.get(i)); logger.debug( "The property " + allPropertyChanges.get(i).getPropertyName() + " is ready to persist!"); } else { logger.debug("The property " + allPropertyChanges.get(i).getPropertyName() + " has not been set in WabitSessionPersister and" + " WorkspacePersisterListener to persist properly!"); } } List<String> settablePropertyNames = new ArrayList<String>(); for (PropertyDescriptor pd : settableProperties) { settablePropertyNames.add(pd.getName()); } settablePropertyNames.removeAll(ignorableProperties); if (settablePropertyNames.size() != changesOnObject.size()) { for (String descriptor : settablePropertyNames) { PersistedSPOProperty foundChange = null; for (PersistedSPOProperty propertyChange : changesOnObject) { if (propertyChange.getPropertyName().equals(descriptor)) { foundChange = propertyChange; break; } } assertNotNull("The property " + descriptor + " was not persisted", foundChange); } } logger.debug("Property names" + settablePropertyNames); assertTrue(settablePropertyNames.size() <= changesOnObject.size()); WabitSessionPersisterSuperConverter factory = new WabitSessionPersisterSuperConverter( new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true); for (String descriptor : settablePropertyNames) { PersistedSPOProperty foundChange = null; for (PersistedSPOProperty propertyChange : changesOnObject) { if (propertyChange.getPropertyName().equals(descriptor)) { foundChange = propertyChange; break; } } assertNotNull("The property " + descriptor + " was not persisted", foundChange); assertTrue(foundChange.isUnconditional()); assertEquals(wo.getUUID(), foundChange.getUUID()); Object value = PropertyUtils.getSimpleProperty(wo, descriptor); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && descriptor.equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } Object valueConvertedToBasic = factory.convertToBasicType(value, additionalVals.toArray()); logger.debug("Property \"" + descriptor + "\": expected \"" + valueConvertedToBasic + "\" but was \"" + foundChange.getNewValue() + "\" of type " + foundChange.getDataType()); assertEquals(valueConvertedToBasic, foundChange.getNewValue()); } }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * This test will set all of the properties in a WabitObject in one transaction then * after committing the next persister after it will throw an exception causing the * persister to undo all of the changes it just made. *//*from w w w.jav a 2s.co m*/ public void testPersisterCommitCanRollbackProperties() throws Exception { SPObject wo = getObjectUnderTest(); WabitSessionPersister persister = new WabitSessionPersister("test persister", session, getWorkspace(), true); CountingWabitListener countingListener = new CountingWabitListener(); ErrorWabitPersister errorPersister = new ErrorWabitPersister(); WorkspacePersisterListener listener = new WorkspacePersisterListener(session, errorPersister, true); SQLPowerUtils.listenToHierarchy(getWorkspace(), listener); wo.addSPListener(countingListener); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); Set<String> propertiesToIgnore = new HashSet<String>(getPropertiesToIgnoreForEvents()); propertiesToIgnore.addAll(getPropertiesToIgnoreForPersisting()); //Track old and new property values to test they are set properly Map<String, Object> propertyNameToOldVal = new HashMap<String, Object>(); //Set all of the properties of the object under test in one transaction. persister.begin(); int propertyChangeCount = 0; for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnore.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } propertyNameToOldVal.put(property.getName(), oldVal); //special case for parent types. If a specific wabit object has a tighter parent then //WabitObject the getParentClass should return the parent type. Class<?> propertyType = property.getPropertyType(); if (property.getName().equals("parent")) { propertyType = getParentClass(); } Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName()); logger.debug("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal + "\" to newVal \"" + newVal + "\""); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = converterFactory.convertToBasicType(newVal, additionalVals.toArray()); persister.persistProperty(wo.getUUID(), property.getName(), type, converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), basicNewValue); propertyChangeCount++; } //Commit the transaction causing the rollback to occur errorPersister.setThrowError(true); try { persister.commit(); fail("The commit method should have an error sent to it and it should rethrow the exception."); } catch (SPPersistenceException t) { //continue } for (PropertyDescriptor property : settableProperties) { Object currentVal; if (propertiesToIgnore.contains(property.getName())) continue; try { currentVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } Object oldVal = propertyNameToOldVal.get(property.getName()); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } logger.debug("Checking property " + property.getName() + " was set to " + oldVal + ", actual value is " + currentVal); assertEquals(converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), converterFactory.convertToBasicType(currentVal, additionalVals.toArray())); } logger.debug("Received " + countingListener.getPropertyChangeCount() + " change events."); assertTrue(propertyChangeCount * 2 <= countingListener.getPropertyChangeCount()); }
From source file:net.siveo.virtualization.vmware.Main.java
public void loadVMX() throws Exception { // ========================================================================================= // Construction de la connexion au VirtualCenter // ========================================================================================= //String hostName="10.62.16.33"; //VMware.create(hostName,443,"root","cahh4gee$",false,-1L); String hostName = "163.172.7.95"; VMware.create(hostName, 443, "eva", "cahh4gee$2015", false, -1L); // ========================================================================================= // //from w w w .j ava 2 s.c om // ========================================================================================= // String vmxParams="config.version = \"8\"\n"+ // "virtualHW.version = \"11\"\n"+ // "nvram = \"VM-JTH-TEST.nvram\""; /* \n \u000a: linefeed LF \r \u000d: carriage return CR * */ String vmxParams = "config.version = \"8\"\r\n" + "virtualHW.version = \"11\"\r\n" + "vmci0.present = \"TRUE\"\r\n" + "floppy0.present = \"FALSE\"\r\n" + "memSize = \"800\"\r\n" + "sched.cpu.units = \"mhz\"\r\n" + "powerType.powerOff = \"soft\"\r\n" + "powerType.suspend = \"hard\"\r\n" + "powerType.reset = \"soft\"\r\n" + "scsi0.virtualDev = \"pvscsi\"\r\n" + "scsi0.present = \"TRUE\"\r\n" + "ide1:0.startConnected = \"FALSE\"\r\n" + "ide1:0.deviceType = \"cdrom-image\"\r\n" + "ide1:0.fileName = \"/usr/lib/vmware/isoimages/linux.iso\"\r\n" + "ide1:0.present = \"TRUE\"\r\n" + "scsi0:0.deviceType = \"scsi-hardDisk\"\r\n" + "scsi0:0.fileName = \"VM-MANU-000001.vmdk\"\r\n" + "scsi0:0.present = \"TRUE\"\r\n" + "displayName = \"VM-MANU\"\r\n" + "guestOS = \"debian7-64\"\r\n" + "toolScripts.afterPowerOn = \"TRUE\"\r\n" + "toolScripts.afterResume = \"TRUE\"\r\n" + "toolScripts.beforeSuspend = \"TRUE\"\r\n" + "toolScripts.beforePowerOff = \"TRUE\"\r\n" + "uuid.bios = \"56 4d 31 7a cc c5 ca a8-f9 5b f7 10 1e 80 9a 19\"\r\n" + "uuid.location = \"56 4d 31 7a cc c5 ca a8-f9 5b f7 10 1e 80 9a 19\"\r\n" + "vc.uuid = \"52 a2 ef 65 1c 00 82 86-29 11 22 99 91 37 90 7e\"\r\n" + "chipset.onlineStandby = \"FALSE\"\r\n" + "sched.cpu.min = \"700\"\r\n" + "sched.cpu.shares = \"normal\"\r\n" + "sched.mem.min = \"100\"\r\n" + "sched.mem.minSize = \"100\"\r\n" + "sched.mem.shares = \"normal\"\r\n" + "vmci0.id = \"110825755\"\r\n" + "ide1:0.allowGuestConnectionControl = \"TRUE\"\r\n" + "tools.syncTime = \"FALSE\"\r\n" + "extendedConfigFile = \"VM-MANU.vmxf\"\r\n" + "numvcpus = \"3\"\r\n" + "sched.cpu.max = \"1100\"\r\n" + "sched.mem.max = \"1200\"\r\n" + "config.readOnly = \"FALSE\"\r\n" + "cleanShutdown = \"TRUE\"\r\n" + "nvram = \"VM-MANU.nvram\"\r\n" + "pciBridge0.present = \"TRUE\"\r\n" + "svga.present = \"TRUE\"\r\n" + "pciBridge4.present = \"TRUE\"\r\n" + "pciBridge4.virtualDev = \"pcieRootPort\"\r\n" + "pciBridge4.functions = \"8\"\r\n" + "pciBridge5.present = \"TRUE\"\r\n" + "pciBridge5.virtualDev = \"pcieRootPort\"\r\n" + "pciBridge5.functions = \"8\"\r\n" + "pciBridge6.present = \"TRUE\"\r\n" + "pciBridge6.virtualDev = \"pcieRootPort\"\r\n" + "pciBridge6.functions = \"8\"\r\n" + "pciBridge7.present = \"TRUE\"\r\n" + "pciBridge7.virtualDev = \"pcieRootPort\"\r\n" + "pciBridge7.functions = \"8\"\r\n" + "hpet0.present = \"true\"\r\n" + "virtualHW.productCompatibility = \"hosted\"\r\n" + "sched.swap.derivedName = \"/vmfs/volumes/561cd9b3-f5eca0e4-c887-204747805988/VM-MANU/VM-MANU-210b39d6.vswp\"\r\n" + "replay.supported = \"false\"\r\n" + "pciBridge0.pciSlotNumber = \"17\"\r\n" + "pciBridge4.pciSlotNumber = \"21\"\r\n" + "pciBridge5.pciSlotNumber = \"22\"\r\n" + "pciBridge6.pciSlotNumber = \"23\"\r\n" + "pciBridge7.pciSlotNumber = \"24\"\r\n" + "scsi0.pciSlotNumber = \"160\"\r\n" + "vmci0.pciSlotNumber = \"32\"\r\n" + "scsi0.sasWWID = \"50 05 05 6a cc c5 ca a0\"\r\n" + "monitor.phys_bits_used = \"42\"\r\n" + "vmotion.checkpointFBSize = \"4194304\"\r\n" + "vmotion.checkpointSVGAPrimarySize = \"4194304\"\r\n" + "softPowerOff = \"FALSE\"\r\n" + "toolsInstallManager.lastInstallError = \"0\"\r\n" + "tools.remindInstall = \"FALSE\"\r\n" + "toolsInstallManager.updateCounter = \"2\"\r\n" + "migrate.hostLog = \"./VM-MANU-65eae829.hlog\"\r\n" + "sched.scsi0:0.throughputCap = \"off\"\r\n" + "RemoteDisplay.vnc.key = \"Fy0lETUECAQjPQcBFDcwIA8YACc7GgUkMC0MAg87CDAfGwICNiEtAScHISQvHggQMxkqABEtIAYVMjQkPzoEAxw5MAA7HQYgOQcAGiozNAIlPxAhNA0oCDsACDA+HjIgMj8oKxEbAAkZKgkAPzQKIy4HEQoGPxAFLAcABT8CEBU=\"\r\n" + "replay.filename = \"\"\r\n" + "scsi0:0.redo = \"\"\r\n" + "sched.scsi0:0.shares = \"normal\"\r\n" + "scsi0:1.deviceType = \"scsi-hardDisk\"\r\n" + "scsi0:1.fileName = \"VM-MANU_1-000001.vmdk\"\r\n" + "scsi0:1.present = \"true\"\r\n" + "scsi0:1.redo = \"\"\r\n" + "scsi0:2.deviceType = \"scsi-hardDisk\"\r\n" + "scsi0:2.fileName = \"VM-MANU_2-000001.vmdk\"\r\n" + "scsi0:2.present = \"TRUE\"\r\n" + "ethernet2.virtualDev = \"e1000\"\r\n" + "ethernet2.networkName = \"Interne\"\r\n" + "ethernet2.addressType = \"generated\"\r\n" + "ethernet2.present = \"TRUE\"\r\n" + "scsi0:2.redo = \"\"\r\n" + "ethernet2.pciSlotNumber = \"35\"\r\n" + "ethernet2.generatedAddress = \"00:0c:29:80:9a:2d\"\r\n" + "ethernet2.generatedAddressOffset = \"20\"\r\n" + "RemoteDisplay.vnc.enabled = \"true\"\r\n" + "RemoteDisplay.vnc.port = \"5901\"\r\n" + "RemoteDisplay.vnc.password = \"li9AH06bAQiXPaW3hV9nkQ==\"\r\n" + "RemoteDisplay.vnc.keyMap = \"fr\"\r\n" + "scsi0:3.deviceType = \"scsi-hardDisk\"\r\n" + "scsi0:3.fileName = \"VM-MANU_5.vmdk\"\r\n" + "scsi0:3.present = \"TRUE\"\r\n" + "scsi0:4.deviceType = \"scsi-hardDisk\"\r\n" + "scsi0:4.fileName = \"VM-MANU_10.vmdk\"\r\n" + "scsi0:4.present = \"TRUE\"\r\n" + "scsi0:4.redo = \"\"\r\n" + "scsi0:3.redo = \"\"\r\n" + "ethernet3.pciSlotNumber = \"192\"\r\n" + "ethernet3.virtualDev = \"vmxnet3\"\r\n" + "ethernet3.uptCompatibility = \"true\"\r\n" + "ethernet3.present = \"TRUE\"\r\n" + "ethernet3.addressType = \"generated\"\r\n" + "ethernet3.generatedAddress = \"00:0c:29:80:9a:37\"\r\n" + "ethernet3.generatedAddressOffset = \"30\"\r\n"; StreamFactory factory = StreamFactory.newInstance(); factory.loadResource("vmxfile.xml"); InputStream in = new ByteArrayInputStream(vmxParams.getBytes()); BeanReader reader = factory.createReader("vmx", new InputStreamReader(in)); Object record = null; Vmx2 vmx = null; while ((record = reader.read()) != null) { vmx = (Vmx2) record; System.out.println("record: " + vmx.getKey() + " / " + vmx.getValue()); } String text = "sched.cpu.max = \"1100\"\r\n" + "sched.cpu.min = \"50\""; String key = "sched.cpu.max\r\n" + "sched.cpu.min"; String value = "\"1100\""; Map<String, String> mapOfValuesByKeys = new HashMap<String, String>(); //mapOfValuesByKeys.put("sched.cpu.max", "\"1100\""); //mapOfValuesByKeys.put("sched.cpu.min", "50"); //mapOfValuesByKeys.put(svga.present = "TRUE"); mapOfValuesByKeys.put("pciBridge0.present", "TRUE"); mapOfValuesByKeys.put("nvram", "VM-JTH-TEST.nvram"); mapOfValuesByKeys.put("virtualHW.version", "11"); mapOfValuesByKeys.put("config.version", "8"); mapOfValuesByKeys.put("pciBridge4.present", "TRUE"); mapOfValuesByKeys.put("pciBridge4.virtualDev", "pcieRootPort"); mapOfValuesByKeys.put("pciBridge4.functions", "8"); // mapOfValuesByKeys.put("vmci0.present", "TRUE"); // mapOfValuesByKeys.put("memSize", "800"); // mapOfValuesByKeys.put("vmci0.id", "110825755"); // mapOfValuesByKeys.put("pciBridge0.present", "TRUE"); //String subClass=null; //String property=null; Class<?> myClass = null; Constructor<?> constructor = null; String paramClass = null; String vmxParam = null; String vmxValue = null; Vmx vmx1 = new Vmx(); Object myObject = null; Object myParentObject = vmx1; Class<?>[] types = null; Object[] varargs = null; List<String> paramsList = new ArrayList<String>(); int index = -1; //Object addListMethod=null; paramsList.add("vmci"); paramsList.add("pciBridge"); HashMap<String, Object> mapOfParamObjectByParamName = new HashMap<String, Object>(); for (Map.Entry<String, String> entry : mapOfValuesByKeys.entrySet()) { vmxParam = entry.getKey(); vmxValue = entry.getValue(); myParentObject = vmx1; index = -1; if (vmxParam.contains(".")) { while (vmxParam.contains(".")) { paramClass = vmxParam.substring(0, vmxParam.indexOf(".")); vmxParam = vmxParam.substring(vmxParam.indexOf(".") + 1); for (String prefix : paramsList) { if (paramClass.startsWith(prefix)) { index = Integer.parseInt(paramClass.substring(prefix.length())); paramClass = paramClass.substring(0, paramClass.length() - 1); } } if (index != -1) { myObject = mapOfParamObjectByParamName.get(paramClass + String.valueOf(index)); } else { // Get the class, create one if doesn't exist myObject = PropertyUtils.getSimpleProperty(myParentObject, paramClass); } if (myObject == null) { myClass = Class.forName("net.siveo.virtualization.vmware.vmx." + paramClass.substring(0, 1).toUpperCase() + paramClass.substring(1)); //constructor=myClass.getConstructor(null); //myObject=constructor.newInstance(null); constructor = myClass.getConstructor(types); myObject = constructor.newInstance(varargs); if (index == -1) { PropertyUtils.setSimpleProperty(myParentObject, paramClass, myObject); } else { if (!mapOfParamObjectByParamName.containsKey(paramClass + String.valueOf(index))) { mapOfParamObjectByParamName.put(paramClass + String.valueOf(index), myObject); PropertyUtils.setSimpleProperty(myParentObject, paramClass, myObject); PropertyUtils.setSimpleProperty(myObject, "index", index); } //addListMethod=PropertyUtils.getSimpleProperty(myParentObject, paramClass+"s"); //vmx1.getVmcis().add(myObject); } } myParentObject = myObject; } PropertyUtils.setSimpleProperty(myParentObject, vmxParam, vmxValue); } else { //myObject=PropertyUtils.getSimpleProperty(vmx1, vmxParam); PropertyUtils.setSimpleProperty(vmx1, vmxParam, vmxValue); // if(myObject==null) // { // myClass=Class.forName("net.siveo.virtualization.vmware.vmx."+paramClass.substring(0,1).toUpperCase()+paramClass.substring(1)); // constructor=myClass.getConstructor(null); // myObject=constructor.newInstance(null); // PropertyUtils.setSimpleProperty(myParentObject, paramClass, myObject); // } //myParentObject=myObject; } } System.out.println("" + vmx1); // while(key.contains(".")) // { // mainClass=key.substring(0,key.indexOf(".")); // key=key.substring(key.indexOf(".")+1); // // // Get the class, create one if doesn't exist // myObject=PropertyUtils.getSimpleProperty(myParentObject, mainClass); // // if(myObject==null) // { // myClass=Class.forName("net.siveo.virtualization.vmware.vmx."+mainClass.substring(0,1).toUpperCase()+mainClass.substring(1)); // constructor=myClass.getConstructor(null); // myObject=constructor.newInstance(null); // PropertyUtils.setSimpleProperty(myParentObject, mainClass, myObject); // } // else // { // //myObject=PropertyUtils.getProperty(bean, name); // } // // myParentObject=myObject; // // } // // PropertyUtils.setSimpleProperty(myParentObject, key, "50"); // String classe=null; // property=key.substring(key.lastIndexOf(".")+1); // key=key.substring(0,key.lastIndexOf(".")); // // while(key.contains(".")) // { // classe=key.substring(key.lastIndexOf(".")+1); // // // // key=key.substring(0,key.lastIndexOf(".")); // } List<String> listOfKeys = new ArrayList<String>(); String temp = null; // String className = "Class1"; // Object xyz = Class.forName(className).newInstance(); // // import java.lang.reflect.*; // // Param1Type param1; // Param2Type param2; // String className = "Class1"; // Class cl = Class.forName(className); // Constructor con = cl.getConstructor(Param1Type.class, Param2Type.class); // Object xyz = con.newInstance(param1, param2); // // vmx1=new Vmx1(); // Config config=new Config(); // // PropertyUtils.setSimpleProperty(config, "version", "12345"); // PropertyUtils.setSimpleProperty(vmx1, "config", config); // // //// PropertyUtils.setMappedProperty(vmx1, "config", config); //// PropertyUtils.setMappedProperty(vmx1, "config", "version", "12"); // // //// PropertyUtils.setMappedProperty(vmx1, "config", config); //// PropertyUtils.setSimpleProperty(vmx1, "config", config); //// PropertyUtils.setNestedProperty(vmx1, "config.version", "12345"); // // // // System.out.println("config.version: "+vmx1.getConfig().getVersion()); // ========================================================================================= // Destruction de la connexion au VirtualCenter // ========================================================================================= VMware.delete(hostName); }