Example usage for org.apache.commons.beanutils PropertyUtils setSimpleProperty

List of usage examples for org.apache.commons.beanutils PropertyUtils setSimpleProperty

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils setSimpleProperty.

Prototype

public static void setSimpleProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Set the value of the specified simple property of the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java

private AttributeStep stepThroughAttribute(Attribute attribute, AttributeStep step,
        Iterator<ItemPathSegment> segments) {
    Method method = (Method) attribute.getJavaMember();

    switch (attribute.getPersistentAttributeType()) {
    case EMBEDDED:
        step.managedType = entityRegistry.getMapping(attribute.getJavaType());
        Object child = invoke(step.bean, method);
        if (child == null) {
            // embedded entity doesn't exist we have to create it first, so it can be populated later
            Class childType = getRealOutputType(attribute);
            try {
                child = childType.newInstance();
                PropertyUtils.setSimpleProperty(step.bean, attribute.getName(), child);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException
                    | NoSuchMethodException ex) {
                throw new SystemException("Couldn't create new instance of '" + childType.getName()
                        + "', attribute '" + attribute.getName() + "'", ex);
            }// w  ww.j  av a2 s  .  c o  m
        }
        step.bean = child;
        break;
    case ONE_TO_MANY:
        // object extension is handled separately, only {@link Container} and references are handled here
        Class clazz = getRealOutputType(attribute);

        IdItemPathSegment id = (IdItemPathSegment) segments.next();

        Collection c = (Collection) invoke(step.bean, method);
        if (!Container.class.isAssignableFrom(clazz)) {
            throw new SystemException(
                    "Don't know how to go through collection of '" + getRealOutputType(attribute) + "'");
        }

        boolean found = false;
        for (Container o : (Collection<Container>) c) {
            long l = o.getId().longValue();
            if (l == id.getId()) {
                step.managedType = entityRegistry.getMapping(clazz);
                step.bean = o;

                found = true;
                break;
            }
        }

        if (!found) {
            throw new RuntimeException("Couldn't find container of type '" + getRealOutputType(attribute)
                    + "' with id '" + id + "'");
        }
        break;
    case ONE_TO_ONE:
        // assignment extension is handled separately
        break;
    default:
        // nothing to do for other cases
    }

    return step;
}

From source file:com.mirth.connect.server.controllers.MuleEngineController.java

private UMOTransformer createPreprocessor(Channel channel, String name) throws Exception {
    UMOTransformer umoTransformer = (UMOTransformer) Class
            .forName("com.mirth.connect.server.mule.transformers.JavaScriptPreprocessor").newInstance();
    umoTransformer.setName(name);//www. ja v  a2  s . co m
    PropertyUtils.setSimpleProperty(umoTransformer, "channelId", channel.getId());

    return umoTransformer;
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java

private void handleBasicOrEmbedded(Object bean, ItemDelta delta, Attribute attribute) {
    Class outputType = getRealOutputType(attribute);

    PrismValue anyPrismValue = delta.getAnyValue();

    Object value;// w  w w.  j a va  2 s  .com
    if (delta.isDelete() || (delta.isReplace() && (anyPrismValue == null || anyPrismValue.isEmpty()))) {
        value = null;
    } else {
        value = anyPrismValue.getRealValue();
    }

    value = prismEntityMapper.map(value, outputType);

    try {
        PropertyUtils.setSimpleProperty(bean, attribute.getName(), value);
    } catch (Exception ex) {
        throw new SystemException("Couldn't set simple property for '" + attribute.getName() + "'", ex);
    }
}

From source file:com.panemu.tiwulfx.table.TableControl.java

private void initColumn(TableColumn<R, ?> clm) {
    List<TableColumn<R, ?>> lstColumn = new ArrayList<>();
    lstColumn.add(clm);/*from w w w . j a va 2 s  . c  o m*/
    lstColumn = getColumnsRecursively(lstColumn);
    for (TableColumn column : lstColumn) {
        if (column instanceof BaseColumn) {
            final BaseColumn baseColumn = (BaseColumn) column;
            baseColumn.tableCriteriaProperty().addListener(tableCriteriaListener);
            baseColumn.sortTypeProperty().addListener(sortTypeChangeListener);
            baseColumn.addEventHandler(TableColumn.editCommitEvent(),
                    new EventHandler<TableColumn.CellEditEvent<R, ?>>() {
                        @Override
                        public void handle(CellEditEvent<R, ?> t) {
                            try {
                                if (!(t.getTablePosition().getRow() < t.getTableView().getItems().size())) {
                                    return;
                                }
                                Object persistentObj = t.getTableView().getItems()
                                        .get(t.getTablePosition().getRow());
                                if ((t.getNewValue() == null && t.getOldValue() == null)
                                        || (t.getNewValue() != null
                                                && t.getNewValue().equals(t.getOldValue()))) {
                                }
                                if (mode.get().equals(Mode.EDIT) && t.getOldValue() != t.getNewValue()
                                        && (t.getOldValue() == null
                                                || !t.getOldValue().equals(t.getNewValue()))) {
                                    if (!lstChangedRow.contains((R) persistentObj)) {
                                        lstChangedRow.add((R) persistentObj);
                                    }
                                    baseColumn.addRecordChange(persistentObj, t.getOldValue(), t.getNewValue());
                                }
                                PropertyUtils.setSimpleProperty(persistentObj, baseColumn.getPropertyName(),
                                        t.getNewValue());
                                baseColumn.validate(persistentObj);
                            } catch (IllegalAccessException | InvocationTargetException
                                    | NoSuchMethodException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    });

        }
    }
}

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  www  .  j a  va2  s .c o  m*/
    // =========================================================================================
    //      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);

}

From source file:org.apache.openmeetings.axis.services.RoomWebService.java

/**
 * Method to update arbitrary room parameter.
 * /*ww  w  .  j a va 2  s  .c o  m*/
 * @param SID The SID of the User. This SID must be marked as Loggedin
 * @param room_id the room id
 * @param paramName
 * @param paramValue
 * @return 1 in case of success, -2 if permissions are insufficient
 * @throws AxisFault if any error occurred
 */
public int modifyRoomParameter(String SID, Long room_id, String paramName, String paramValue) throws AxisFault {
    try {
        Long users_id = sessiondataDao.checkSession(SID);
        Long user_level = userManager.getUserLevelByID(users_id);
        if (authLevelUtil.checkWebServiceLevel(user_level)) {
            log.debug("closeRoom 1 " + room_id);
            Room r = roomDao.get(room_id);
            PropertyUtils.setSimpleProperty(r, paramName, paramValue);
            roomDao.update(r, users_id);
        } else {
            return -2;
        }
        return 1;
    } catch (Exception err) {
        log.error("[modifyRoomParameter] ", err);

        throw new AxisFault(err.getMessage());
    }
}

From source file:org.apache.qpid.server.jmx.mbeans.MBeanTestUtils.java

public static void setMBeanAttribute(DefaultManagedObject managedObject, String jmxAttributeName,
        Object newValue) throws Exception {
    PropertyUtils.setSimpleProperty(managedObject, jmxAttributeName, newValue);
}

From source file:org.apache.torque.dsfactory.AbstractDataSourceFactory.java

/**
 * Encapsulates setting configuration properties on
 * <code>DataSource</code> objects.
 *
 * @param property the property to read from the configuration
 * @param c the configuration to read the property from
 * @param ds the <code>DataSource</code> instance to write the property to
 * @throws Exception if anything goes wrong
 *///from  w w w  .j  a  v  a 2 s .c  o m
protected void setProperty(String property, Configuration c, Object ds) throws Exception {
    if (c == null || c.isEmpty()) {
        return;
    }

    String key = property;
    Class<?> dsClass = ds.getClass();
    int dot = property.indexOf('.');
    try {
        if (dot > 0) {
            property = property.substring(0, dot);

            MappedPropertyDescriptor mappedPD = new MappedPropertyDescriptor(property, dsClass);
            Class<?> propertyType = mappedPD.getMappedPropertyType();
            Configuration subProps = c.subset(property);
            // use reflection to set properties
            Iterator<?> j = subProps.getKeys();
            while (j.hasNext()) {
                String subProp = (String) j.next();
                String propVal = subProps.getString(subProp);
                Object value = ConvertUtils.convert(propVal, propertyType);
                PropertyUtils.setMappedProperty(ds, property, subProp, value);

                if (log.isDebugEnabled()) {
                    log.debug(
                            "setMappedProperty(" + ds + ", " + property + ", " + subProp + ", " + value + ")");
                }
            }
        } else {
            if ("password".equals(key)) {
                // do not log value of password
                // for this, ConvertUtils.convert cannot be used
                // as it also logs the value of the converted property
                // so it is assumed here that the password is a String
                String value = c.getString(property);
                PropertyUtils.setSimpleProperty(ds, property, value);
                if (log.isDebugEnabled()) {
                    log.debug("setSimpleProperty(" + ds + ", " + property + ", " + " (value not logged)" + ")");
                }
            } else {
                Class<?> propertyType = PropertyUtils.getPropertyType(ds, property);
                Object value = ConvertUtils.convert(c.getString(property), propertyType);
                PropertyUtils.setSimpleProperty(ds, property, value);

                if (log.isDebugEnabled()) {
                    log.debug("setSimpleProperty(" + ds + ", " + property + ", " + value + ")");
                }
            }
        }
    } catch (RuntimeException e) {
        throw new TorqueRuntimeException("Runtime error setting property " + property, e);
    } catch (Exception e) {
        log.error("Property: " + property + " value: " + c.getString(key) + " is not supported by DataSource: "
                + ds.getClass().getName());
    }
}

From source file:org.apache.torque.JndiConfigurationTest.java

/**
 * Creates a Data Source from the Torque configuration without using Torque.
 * @return a SharedPoolDataSource source.
 * @throws Exception if we cannot create a Data source.
 *//*from  www. j  av  a  2  s . co  m*/
protected BasicDataSource getDataSource() throws Exception {
    Configuration torqueConfiguration = getTorqueConfiguraton();
    String defaultDatabase = getDefaultDatabase(torqueConfiguration);
    Configuration dsfactoryConfiguration = torqueConfiguration
            .subset(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                    + AbstractDataSourceFactory.CONNECTION_KEY);

    BasicDataSource dataSource = new BasicDataSource();
    for (Iterator i = dsfactoryConfiguration.getKeys(); i.hasNext();) {
        String key = (String) i.next();
        String stringValue = dsfactoryConfiguration.getString(key);

        if ("user".equals(key)) {
            // setUser() in SharedPoolDataSouce corresponds to
            // setUsername() in BasicDataSourceFactory
            key = "username";
        } else if ("driver".equals(key)) {
            // setDriver() in SharedPoolDataSouce corresponds to
            // setDriverClassName() in BasicDataSourceFactory
            key = "driverClassName";
        }

        Class propertyType = PropertyUtils.getPropertyType(dataSource, key);
        Object value = ConvertUtils.convert(stringValue, propertyType);
        PropertyUtils.setSimpleProperty(dataSource, key, value);
    }

    return dataSource;
}

From source file:org.bitsofinfo.util.address.usps.ais.loader.USPSRecordParser.java

/**
 * Takes a line of raw USPS data file record data and applies it
 * to a USPSRecord instance (overwriting any previous data) according
 * to the USPSDataFileField annotations defined within the USPSRecord
 * class./*  w w w .  j av  a2 s.  co m*/
 * 
 * @param rawRecord      Raw string of text representing a line from a USPS 
 *                raw database record file
 * 
 * @param target   The target instance (derivative of USPSRecord) which will
 *                be updated with the values parsed from the line of data.
 *                This class MUST have its members annotated with USPSDataFileField
 *                
 * @throws RecordParseException on any error
 */
public void applyRawRecord(String rawRecord, USPSRecord targetRecord) throws RecordParseException {

    Class<? extends USPSRecord> targetClass = targetRecord.getClass();

    // 1st lets do a simple check to make sure this record is compatible...
    CopyrightDetailCode lineType = CopyrightDetailCode.valueOf(rawRecord.substring(0, 1));
    USPSRecordContext productInfo = targetClass.getAnnotation(USPSRecordContext.class);
    if (productInfo.copyrightDetailCode() != lineType) {
        throw new RecordParseException(
                "According to @USPSRecordContext annotation, we cannot apply line data " + " of type "
                        + lineType.name() + " against " + " target USPSRecord of type " + targetClass.getName(),
                rawRecord, null);
    }

    // get the list of all Fields known in this class annotated by USPSDataFileField
    List<Field> dataFileFields = uspsUtils.getFieldsByAnnotation(targetClass, USPSDataFileField.class);

    /* for every member of the target class, located those
     * annotated with DataFileField and located the data within
     * the line which matches the markers described in the annotation.
     * For each value parsed, convert it, then set the value against
     * the USPSRecord instance.
     */
    for (Field f : dataFileFields) {

        Object[] parts = USPSDataFileFieldHelper.extractValue(rawRecord, f);
        Object trueValue = parts[1];
        String rawValue = parts[0].toString();

        // attempt to set the property against our target instance
        try {
            PropertyUtils.setSimpleProperty(targetRecord, f.getName(), trueValue);

        } catch (Exception e) {
            throw new RecordParseException(
                    "Failed when attempting to set value (" + "rawValue=" + rawValue + " objValue="
                            + (trueValue != null
                                    ? (trueValue.toString() + "(" + trueValue.getClass().getName() + ")")
                                    : null)
                            + ") against " + targetClass.getName() + " field=" + f.getName(),
                    rawRecord, e);
        }

    }

}