/** * Examines a property's type to see which method should be used to parse the property's value. * * @param desc The description of the property * @param element The XML element containing the property value * @return The value stored in the element * @throws IOException If there is an error reading the document */ public Object getObjectValue(PropertyDescriptor desc, Element element) throws IOException { // Find out what kind of property it is Class type = desc.getPropertyType(); // If it's an array, get the base type if (type.isArray()) { type = type.getComponentType(); } // For native types, object wrappers for natives, and strings, use the // basic parse routine if (type.equals(Integer.TYPE) || type.equals(Long.TYPE) || type.equals(Short.TYPE) || type.equals(Byte.TYPE) || type.equals(Boolean.TYPE) || type.equals(Float.TYPE) || type.equals(Double.TYPE) || Integer.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type) || Short.class.isAssignableFrom(type) || Byte.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type) || Float.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type) || String.class.isAssignableFrom(type)) { return readBasicType(type, element); } else if (java.util.Date.class.isAssignableFrom(type)) { // If it's a date, use the date parser return readDate(element); } else { try { // If it's an object, create a new instance of the object (it should // be a bean, or there will be trouble) Object newOb = type.newInstance(); // Copy the XML element into the bean readObject(newOb, element); return newOb; } catch (InstantiationException exc) { throw new IOException( "Error creating object for " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error creating object for " + desc.getName() + ": " + exc.toString()); } } }
/* ------------------------------------------------------------ */ public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { if (log.isDebugEnabled()) log.debug("getAttribute " + name); Method getter = (Method) _getter.get(name); if (getter == null) throw new AttributeNotFoundException(name); try { Object o = _object; if (getter.getDeclaringClass().isInstance(this)) o = this; return getter.invoke(o, (java.lang.Object[]) null); } catch (IllegalAccessException e) { log.warn(LogSupport.EXCEPTION, e); throw new AttributeNotFoundException(e.toString()); } catch (InvocationTargetException e) { log.warn(LogSupport.EXCEPTION, e); throw new ReflectionException((Exception) e.getTargetException()); } }
/* ------------------------------------------------------------ */ public void setAttribute(Attribute attr) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { if (attr == null) return; if (log.isDebugEnabled()) log.debug("setAttribute " + attr.getName() + "=" + attr.getValue()); Method setter = (Method) _setter.get(attr.getName()); if (setter == null) throw new AttributeNotFoundException(attr.getName()); try { Object o = _object; if (setter.getDeclaringClass().isInstance(this)) o = this; setter.invoke(o, new Object[] {attr.getValue()}); } catch (IllegalAccessException e) { log.warn(LogSupport.EXCEPTION, e); throw new AttributeNotFoundException(e.toString()); } catch (InvocationTargetException e) { log.warn(LogSupport.EXCEPTION, e); throw new ReflectionException((Exception) e.getTargetException()); } }
protected PsmEvent run(PsmEvent event, PsmInterp interp, Object[] argArray) { try { return (PsmEvent) method.invoke(null, argArray); } catch (IllegalAccessException ex) { // This really should never happen, given the checks at // construction time. throw new PsmMethodActionException(ex.toString()); } catch (InvocationTargetException ex) { // This may occur if the method throws a runtime exception. Rather // than wrap it in a PsmMethodActionException, let it percolate up. // If not a RuntimeException, wrap it in a PsmMethodActionException. Throwable th = ex.getTargetException(); if (th instanceof RuntimeException) { throw (RuntimeException) th; } else { throw new PsmMethodActionException( "Exception thrown from " + "target method invocation " + " is not a Runtime Exception", th); } } }
/** * Invokes the method specified by a method description. * * @param methodDescription the method description of the method that is to be invoked. */ protected void invoke(MethodDescription methodDescription) throws InvocationTargetException { VParamUtil.throwIfNull(methodDescription); Object o = getObject(methodDescription.getObjectID()); ObjectDescription oDesc = getObjectDescription(o); if (o == null) { throw new IllegalStateException("Object must not be null!"); } if (methodDescription.getMethodType() == MethodType.REFERENCE) { Object[] parameters = methodDescription.getParameters(); // error handling if (parameters.length > 1) { throw new IllegalArgumentException( "More than one parameter " + "for reference methods is not allowed!"); } if (parameters.length > 0 && parameters[0] != null) { methodDescription.setReturnValue(parameters[0]); } else { methodDescription.setReturnValue(o); } } else if (o instanceof ProxyObject) { ProxyObject proxy = (ProxyObject) o; methodDescription.setReturnValue(proxy.invoke(methodDescription)); if (!methodDescription .getReturnType() .equals(methodDescription.getReturnValue().getClass())) { System.err.println(">> ProxyObject: wrong type of return value!"); generateErrorMessage(">> ProxyObject:" + " wrong type of return value!", methodDescription); } } else if (methodDescription.getMethodType() == MethodType.DEFAULT || methodDescription.getMethodType() == MethodType.CUSTOM_REFERENCE) { Method m = null; try { m = o.getClass() .getMethod( methodDescription.getMethodName(), methodDescription.getParameterTypes()); // access this method even if language visibility forbids // invocation of this method m.setAccessible(true); methodDescription.setReturnValue(m.invoke(o, methodDescription.getParameters())); } catch (NoSuchMethodException ex) { Logger.getLogger(ObjectInspector.class.getName()).log(Level.SEVERE, null, ex); generateErrorMessage( methodDescription.getMethodName() + "(): " + ex.toString(), methodDescription); } catch (IllegalAccessException ex) { Logger.getLogger(ObjectInspector.class.getName()).log(Level.SEVERE, null, ex); generateErrorMessage( methodDescription.getMethodName() + "(): " + ex.toString(), methodDescription); } catch (IllegalArgumentException ex) { System.err.println(">> ObjectInspector:" + " invoked method with wrong arguments!"); String yourParamStr = ""; String expectedParamStr = ""; if (methodDescription.getParameters() != null) { for (int i = 0; i < methodDescription.getParameters().length; i++) { Object parameter = methodDescription.getParameters()[i]; if (parameter != null) { yourParamStr += parameter.getClass().getName() + " "; } else { yourParamStr += "null "; } } } else { yourParamStr = "no parameters given!"; } for (int i = 0; i < m.getParameterTypes().length; i++) { expectedParamStr += m.getParameterTypes()[i].getName() + " "; } System.err.println(" your parameters: " + yourParamStr); System.err.println(" expected parameters: " + expectedParamStr); generateErrorMessage( methodDescription.getMethodName() + "(): method invoked with wrong arguments!", methodDescription); } catch (InvocationTargetException ex) { Logger.getLogger(ObjectInspector.class.getName()).log(Level.SEVERE, null, ex); generateErrorMessage(methodDescription, ex.getCause()); throw ex; } catch (SecurityException ex) { Logger.getLogger(ObjectInspector.class.getName()).log(Level.SEVERE, null, ex); generateErrorMessage( methodDescription.getMethodName() + "(): " + ex.toString(), methodDescription); } } // end else if (o instanceof ProxyObject) }
public Properties parseURL(String url, Properties defaults) throws java.sql.SQLException { Properties urlProps = (defaults != null) ? new Properties(defaults) : new Properties(); if (url == null) { return null; } if (!StringUtils.startsWithIgnoreCase(url, URL_PREFIX) && !StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX) && !StringUtils.startsWithIgnoreCase(url, LOADBALANCE_URL_PREFIX) && !StringUtils.startsWithIgnoreCase(url, REPLICATION_URL_PREFIX)) { // $NON-NLS-1$ return null; } int beginningOfSlashes = url.indexOf("//"); if (StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)) { urlProps.setProperty( "socketFactory", "com.mysql.management.driverlaunched.ServerLauncherSocketFactory"); } /* * Parse parameters after the ? in the URL and remove them from the * original URL. */ int index = url.indexOf("?"); // $NON-NLS-1$ if (index != -1) { String paramString = url.substring(index + 1, url.length()); url = url.substring(0, index); StringTokenizer queryParams = new StringTokenizer(paramString, "&"); // $NON-NLS-1$ while (queryParams.hasMoreTokens()) { String parameterValuePair = queryParams.nextToken(); int indexOfEquals = StringUtils.indexOfIgnoreCase(0, parameterValuePair, "="); String parameter = null; String value = null; if (indexOfEquals != -1) { parameter = parameterValuePair.substring(0, indexOfEquals); if (indexOfEquals + 1 < parameterValuePair.length()) { value = parameterValuePair.substring(indexOfEquals + 1); } } if ((value != null && value.length() > 0) && (parameter != null && parameter.length() > 0)) { try { urlProps.put(parameter, URLDecoder.decode(value, "UTF-8")); } catch (UnsupportedEncodingException badEncoding) { // punt urlProps.put(parameter, URLDecoder.decode(value)); } catch (NoSuchMethodError nsme) { // punt again urlProps.put(parameter, URLDecoder.decode(value)); } } } } url = url.substring(beginningOfSlashes + 2); String hostStuff = null; int slashIndex = url.indexOf("/"); // $NON-NLS-1$ if (slashIndex != -1) { hostStuff = url.substring(0, slashIndex); if ((slashIndex + 1) < url.length()) { urlProps.put( DBNAME_PROPERTY_KEY, //$NON-NLS-1$ url.substring((slashIndex + 1), url.length())); } } else { hostStuff = url; } if ((hostStuff != null) && (hostStuff.length() > 0)) { urlProps.put(HOST_PROPERTY_KEY, hostStuff); // $NON-NLS-1$ } String propertiesTransformClassName = urlProps.getProperty(PROPERTIES_TRANSFORM_KEY); if (propertiesTransformClassName != null) { try { ConnectionPropertiesTransform propTransformer = (ConnectionPropertiesTransform) Class.forName(propertiesTransformClassName).newInstance(); urlProps = propTransformer.transformProperties(urlProps); } catch (InstantiationException e) { throw SQLError.createSQLException( "Unable to create properties transform instance '" + propertiesTransformClassName + "' due to underlying exception: " + e.toString(), SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); } catch (IllegalAccessException e) { throw SQLError.createSQLException( "Unable to create properties transform instance '" + propertiesTransformClassName + "' due to underlying exception: " + e.toString(), SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); } catch (ClassNotFoundException e) { throw SQLError.createSQLException( "Unable to create properties transform instance '" + propertiesTransformClassName + "' due to underlying exception: " + e.toString(), SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); } } if (Util.isColdFusion() && urlProps.getProperty("autoConfigureForColdFusion", "true").equalsIgnoreCase("true")) { String configs = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY); StringBuffer newConfigs = new StringBuffer(); if (configs != null) { newConfigs.append(configs); newConfigs.append(","); } newConfigs.append("coldFusion"); urlProps.setProperty(USE_CONFIG_PROPERTY_KEY, newConfigs.toString()); } // If we use a config, it actually should get overridden by anything in // the URL or passed-in properties String configNames = null; if (defaults != null) { configNames = defaults.getProperty(USE_CONFIG_PROPERTY_KEY); } if (configNames == null) { configNames = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY); } if (configNames != null) { List splitNames = StringUtils.split(configNames, ",", true); Properties configProps = new Properties(); Iterator namesIter = splitNames.iterator(); while (namesIter.hasNext()) { String configName = (String) namesIter.next(); try { InputStream configAsStream = getClass().getResourceAsStream("configs/" + configName + ".properties"); if (configAsStream == null) { throw SQLError.createSQLException( "Can't find configuration template named '" + configName + "'", SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); } configProps.load(configAsStream); } catch (IOException ioEx) { throw SQLError.createSQLException( "Unable to load configuration template '" + configName + "' due to underlying IOException: " + ioEx, SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE); } } Iterator propsIter = urlProps.keySet().iterator(); while (propsIter.hasNext()) { String key = propsIter.next().toString(); String property = urlProps.getProperty(key); configProps.setProperty(key, property); } urlProps = configProps; } // Properties passed in should override ones in URL if (defaults != null) { Iterator propsIter = defaults.keySet().iterator(); while (propsIter.hasNext()) { String key = propsIter.next().toString(); String property = defaults.getProperty(key); urlProps.setProperty(key, property); } } return urlProps; }
/** * Reads XML element(s) into an indexed bean property by first locating the XML element(s) * corresponding to this property. * * @param ob The bean whose property is being set * @param desc The property that will be set * @param nodes The list of XML items that may contain the property * @throws IOException If there is an error reading the document */ public void readIndexedProperty( Object ob, IndexedPropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs) throws IOException { // Create a vector to hold the property values Vector v = new Vector(); int numAttrs = attrs.getLength(); for (int i = 0; i < numAttrs; i++) { // See if this attribute matches the property name if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) { // Get the property value Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue()); if (obValue != null) { // Add the value to the list of values to be set v.addElement(obValue); } } } int numNodes = nodes.getLength(); for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); // Skip non-element nodes if (!(node instanceof Element)) continue; Element element = (Element) node; // See if this element tag matches the property name if (namesMatch(desc.getName(), element.getTagName())) { // Get the property value Object obValue = getObjectValue(desc, element); if (obValue != null) { // Add the value to the list of values to be set v.addElement(obValue); } } } // Get the method used to set the property value Method setter = desc.getWriteMethod(); // If this property has no setter, don't write it if (setter == null) return; // Create a new array of property values Object propArray = Array.newInstance(desc.getPropertyType().getComponentType(), v.size()); // Copy the vector into the array v.copyInto((Object[]) propArray); try { // Store the array of property values setter.invoke(ob, new Object[] {propArray}); } catch (InvocationTargetException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } }
/** * Reads an XML element into a bean property by first locating the XML element corresponding to * this property. * * @param ob The bean whose property is being set * @param desc The property that will be set * @param nodes The list of XML items that may contain the property * @throws IOException If there is an error reading the document */ public void readProperty(Object ob, PropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs) throws IOException { int numAttrs = attrs.getLength(); for (int i = 0; i < numAttrs; i++) { // See if the attribute name matches the property name if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) { // Get the method used to set this property Method setter = desc.getWriteMethod(); // If this object has no setter, don't bother writing it if (setter == null) continue; // Get the value of the property Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue()); if (obValue != null) { try { // Set the property value setter.invoke(ob, new Object[] {obValue}); } catch (InvocationTargetException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } } return; } } int numNodes = nodes.getLength(); Vector arrayBuild = null; for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); // If this node isn't an element, skip it if (!(node instanceof Element)) continue; Element element = (Element) node; // See if the tag name matches the property name if (namesMatch(desc.getName(), element.getTagName())) { // Get the method used to set this property Method setter = desc.getWriteMethod(); // If this object has no setter, don't bother writing it if (setter == null) continue; // Get the value of the property Object obValue = getObjectValue(desc, element); // 070201 MAW: Modified from change submitted by Steve Poulson if (setter.getParameterTypes()[0].isArray()) { if (arrayBuild == null) { arrayBuild = new Vector(); } arrayBuild.addElement(obValue); // 070201 MAW: Go ahead and read through the rest of the nodes in case // another one matches the array. This has the effect of skipping // over the "return" statement down below continue; } if (obValue != null) { try { // Set the property value setter.invoke(ob, new Object[] {obValue}); } catch (InvocationTargetException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } } return; } } // If we build a vector of array members, convert the vector into // an array and save it in the property if (arrayBuild != null) { // Get the method used to set this property Method setter = desc.getWriteMethod(); if (setter == null) return; Object[] obValues = (Object[]) Array.newInstance(desc.getPropertyType(), arrayBuild.size()); arrayBuild.copyInto(obValues); try { setter.invoke(ob, new Object[] {obValues}); } catch (InvocationTargetException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } return; } }