Esempio n. 1
1
 /**
  * Factory method, equivalent to a "fromXML" for step creation. Looks for a class with the same
  * name as the XML tag, with the first letter capitalized. For example, <call /> is
  * abbot.script.Call.
  */
 public static Step createStep(Resolver resolver, Element el) throws InvalidScriptException {
   String tag = el.getName();
   Map attributes = createAttributeMap(el);
   String name = tag.substring(0, 1).toUpperCase() + tag.substring(1);
   if (tag.equals(TAG_WAIT)) {
     attributes.put(TAG_WAIT, "true");
     name = "Assert";
   }
   try {
     name = "abbot.script." + name;
     Log.debug("Instantiating " + name);
     Class cls = Class.forName(name);
     try {
       // Steps with contents require access to the XML element
       Class[] argTypes = new Class[] {Resolver.class, Element.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, el, attributes});
     } catch (NoSuchMethodException nsm) {
       // All steps must support this ctor
       Class[] argTypes = new Class[] {Resolver.class, Map.class};
       Constructor ctor = cls.getConstructor(argTypes);
       return (Step) ctor.newInstance(new Object[] {resolver, attributes});
     }
   } catch (ClassNotFoundException cnf) {
     String msg = Strings.get("step.unknown_tag", new Object[] {tag});
     throw new InvalidScriptException(msg);
   } catch (InvocationTargetException ite) {
     Log.warn(ite);
     throw new InvalidScriptException(ite.getTargetException().getMessage());
   } catch (Exception exc) {
     Log.warn(exc);
     throw new InvalidScriptException(exc.getMessage());
   }
 }
Esempio n. 2
0
 /**
  * This method is called when 'Finish' button is pressed in the wizard. We will create an
  * operation and run it using wizard as execution context.
  */
 public boolean performFinish() {
   final String containerName = page.getContainerName();
   final String fileName = page.getFileName();
   IRunnableWithProgress op =
       new IRunnableWithProgress() {
         public void run(IProgressMonitor monitor) throws InvocationTargetException {
           try {
             doFinish(containerName, fileName, monitor);
           } catch (CoreException e) {
             throw new InvocationTargetException(e);
           } finally {
             monitor.done();
           }
         }
       };
   try {
     getContainer().run(true, false, op);
   } catch (InterruptedException e) {
     return false;
   } catch (InvocationTargetException e) {
     Throwable realException = e.getTargetException();
     MessageDialog.openError(getShell(), "Error", realException.getMessage());
     return false;
   }
   return true;
 }
Esempio n. 3
0
  /** Reads the view from the specified uri. */
  @Override
  public void read(URI f, URIChooser chooser) throws IOException {
    try {
      final Drawing drawing = createDrawing();
      InputFormat inputFormat = drawing.getInputFormats().get(0);
      inputFormat.read(f, drawing, true);
      SwingUtilities.invokeAndWait(
          new Runnable() {

            @Override
            public void run() {
              view.getDrawing().removeUndoableEditListener(undo);
              view.setDrawing(drawing);
              view.getDrawing().addUndoableEditListener(undo);
              undo.discardAllEdits();
            }
          });
    } catch (InterruptedException e) {
      InternalError error = new InternalError();
      e.initCause(e);
      throw error;
    } catch (InvocationTargetException e) {
      InternalError error = new InternalError();
      e.initCause(e);
      throw error;
    }
  }
Esempio n. 4
0
 /**
  * Insert the source code details, if available.
  *
  * @param ped The given program element.
  */
 public void addSourcePosition(ProgramElementDoc ped, int indent) {
   if (!addSrcInfo) return;
   if (JDiff.javaVersion.startsWith("1.1")
       || JDiff.javaVersion.startsWith("1.2")
       || JDiff.javaVersion.startsWith("1.3")) {
     return; // position() only appeared in J2SE1.4
   }
   try {
     // Could cache the method for improved performance
     Class c = ProgramElementDoc.class;
     Method m = c.getMethod("position", null);
     Object sp = m.invoke(ped, null);
     if (sp != null) {
       for (int i = 0; i < indent; i++) outputFile.print(" ");
       outputFile.println("src=\"" + sp + "\"");
     }
   } catch (NoSuchMethodException e2) {
     System.err.println("Error: method \"position\" not found");
     e2.printStackTrace();
   } catch (IllegalAccessException e4) {
     System.err.println("Error: class not permitted to be instantiated");
     e4.printStackTrace();
   } catch (InvocationTargetException e5) {
     System.err.println("Error: method \"position\" could not be invoked");
     e5.printStackTrace();
   } catch (Exception e6) {
     System.err.println("Error: ");
     e6.printStackTrace();
   }
 }
Esempio n. 5
0
File: Macro.java Progetto: bramk/bnd
 private String doCommand(Object target, String method, String[] args) {
   if (target == null) ; // System.err.println("Huh? Target should never be null " +
   // domain);
   else {
     String cname = "_" + method.replaceAll("-", "_");
     try {
       Method m = target.getClass().getMethod(cname, new Class[] {String[].class});
       return (String) m.invoke(target, new Object[] {args});
     } catch (NoSuchMethodException e) {
       // Ignore
     } catch (InvocationTargetException e) {
       if (e.getCause() instanceof IllegalArgumentException) {
         domain.error(
             "%s, for cmd: %s, arguments; %s",
             e.getCause().getMessage(), method, Arrays.toString(args));
       } else {
         domain.warning("Exception in replace: %s", e.getCause());
         e.getCause().printStackTrace();
       }
     } catch (Exception e) {
       domain.warning("Exception in replace: " + e + " method=" + method);
       e.printStackTrace();
     }
   }
   return null;
 }
Esempio n. 6
0
 public void process(File cFile) {
   try {
     String cName = ClassNameFinder.thisClass(BinaryFile.read(cFile));
     if (!cName.contains("")) return; // Ignore unpackaged classes
     testClass = Class.forName(cName);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   TestMethods testMethods = new TestMethods();
   Method creator = null;
   Method cleanup = null;
   for (Method m : testClass.getDeclaredMethods()) {
     testMethods.addIfTestMethod(m);
     if (creator == null) creator = checkForCreatorMethod(m);
     if (cleanup == null) cleanup = checkForCleanupMethod(m);
   }
   if (testMethods.size() > 0) {
     if (creator == null)
       try {
         if (!Modifier.isPublic(testClass.getDeclaredConstructor().getModifiers())) {
           Print.print("Error: " + testClass + " default constructor must be public");
           System.exit(1);
         }
       } catch (NoSuchMethodException e) {
         // Synthesized default constructor; OK
       }
     Print.print(testClass.getName());
   }
   for (Method m : testMethods) {
     Print.printnb("  . " + m.getName() + " ");
     try {
       Object testObject = createTestObject(creator);
       boolean success = false;
       try {
         if (m.getReturnType().equals(boolean.class)) success = (Boolean) m.invoke(testObject);
         else {
           m.invoke(testObject);
           success = true; // If no assert fails
         }
       } catch (InvocationTargetException e) {
         // Actual exception is inside e:
         Print.print(e.getCause());
       }
       Print.print(success ? "" : "(failed)");
       testsRun++;
       if (!success) {
         failures++;
         failedTests.add(testClass.getName() + ": " + m.getName());
       }
       if (cleanup != null) cleanup.invoke(testObject, testObject);
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
Esempio n. 7
0
  /**
   * This creates a new <code>{@link Document}</code> from an existing <code>InputStream</code> by
   * letting a DOM parser handle parsing using the supplied stream.
   *
   * @param in <code>InputStream</code> to parse.
   * @param validate <code>boolean</code> to indicate if validation should occur.
   * @return <code>Document</code> - instance ready for use.
   * @throws IOException when I/O error occurs.
   * @throws JDOMException when errors occur in parsing.
   */
  public Document getDocument(InputStream in, boolean validate) throws IOException, JDOMException {

    try {
      // Load the parser class
      Class parserClass = Class.forName("org.apache.xerces.parsers.DOMParser");
      Object parser = parserClass.newInstance();

      // Set validation
      Method setFeature =
          parserClass.getMethod("setFeature", new Class[] {java.lang.String.class, boolean.class});
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/validation", new Boolean(validate)});

      // Set namespaces true
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/namespaces", new Boolean(true)});

      // Set the error handler
      if (validate) {
        Method setErrorHandler =
            parserClass.getMethod("setErrorHandler", new Class[] {ErrorHandler.class});
        setErrorHandler.invoke(parser, new Object[] {new BuilderErrorHandler()});
      }

      // Parse the document
      Method parse = parserClass.getMethod("parse", new Class[] {org.xml.sax.InputSource.class});
      parse.invoke(parser, new Object[] {new InputSource(in)});

      // Get the Document object
      Method getDocument = parserClass.getMethod("getDocument", null);
      Document doc = (Document) getDocument.invoke(parser, null);

      return doc;
    } catch (InvocationTargetException e) {
      Throwable targetException = e.getTargetException();
      if (targetException instanceof org.xml.sax.SAXParseException) {
        SAXParseException parseException = (SAXParseException) targetException;
        throw new JDOMException(
            "Error on line "
                + parseException.getLineNumber()
                + " of XML document: "
                + parseException.getMessage(),
            e);
      } else if (targetException instanceof IOException) {
        IOException ioException = (IOException) targetException;
        throw ioException;
      } else {
        throw new JDOMException(targetException.getMessage(), e);
      }
    } catch (Exception e) {
      throw new JDOMException(e.getClass().getName() + ": " + e.getMessage(), e);
    }
  }
Esempio n. 8
0
 /**
  * Checks if the invocation of the method throws a SQLExceptio as expected.
  *
  * @param LOB the Object that implements the Blob interface
  * @param method the method that needs to be tested to ensure that it throws the correct exception
  * @return true If the method throws the SQLException required after the free method has been
  *     called on the LOB object
  */
 boolean checkIfMethodThrowsSQLException(Object LOB, Method method)
     throws IllegalAccessException, InvocationTargetException {
   try {
     method.invoke(LOB, getNullValues(method.getParameterTypes()));
   } catch (InvocationTargetException ite) {
     Throwable cause = ite.getCause();
     if (cause instanceof SQLException) {
       return ((SQLException) cause).getSQLState().equals("XJ215");
     }
     throw ite;
   }
   return false;
 }
 @Override
 public void exec() {
   if (mParams == null) {
     throw new IllegalArgumentException("Argument unmarshalling has not taken place yet");
   }
   try {
     mResult = mMethodHandle.invokeWithArguments(mParams);
   } catch (final InvocationTargetException e) {
     final Throwable cause = e.getCause();
     throw new MessagingException(cause != null ? cause : e);
   } catch (final Throwable e) {
     throw new MessagingException(e);
   }
 }
 public void loadAndRun(String className) throws Throwable {
   // System.out.println("Loading " + className + "...");
   Class testClass = new VerifyClassLoader().loadClass(className);
   // System.out.println("Loaded " + className);
   try {
     Method main = testClass.getMethod("main", new Class[] {String[].class});
     // System.out.println("Running " + className);
     main.invoke(null, new Object[] {new String[] {}});
     // System.out.println("Finished running " + className);
   } catch (NoSuchMethodException e) {
     return;
   } catch (InvocationTargetException e) {
     throw e.getTargetException();
   }
 }
Esempio n. 11
0
 /**
  * Try to execute given method on given object. Handles invocation target exceptions. XXX nearly
  * duplicates tryMethod in JGEngine.
  *
  * @return null means method does not exist or returned null/void
  */
 static Object tryMethod(Object o, String name, Object[] args) {
   try {
     Method met = JREEngine.getMethod(o.getClass(), name, args);
     if (met == null) return null;
     return met.invoke(o, args);
   } catch (InvocationTargetException ex) {
     Throwable ex_t = ex.getTargetException();
     ex_t.printStackTrace();
     return null;
   } catch (IllegalAccessException ex) {
     System.err.println("Unexpected exception:");
     ex.printStackTrace();
     return null;
   }
 }
Esempio n. 12
0
 // Lookup the value corresponding to a key found in catalog.getKeys().
 // Here we assume that the catalog returns a non-inherited value for
 // these keys. FIXME: Not true. Better see whether handleGetObject is
 // public - it is in ListResourceBundle and PropertyResourceBundle.
 private Object lookup(String key) {
   Object value = null;
   if (lookupMethod != null) {
     try {
       value = lookupMethod.invoke(catalog, new Object[] {key});
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (InvocationTargetException e) {
       e.getTargetException().printStackTrace();
     }
   } else {
     try {
       value = catalog.getObject(key);
     } catch (MissingResourceException e) {
     }
   }
   return value;
 }
 /**
  * Build the documentation, as specified by the given XML element.
  *
  * @param node the XML element that specifies which component to document.
  * @param contentTree content tree to which the documentation will be added
  */
 protected void build(XMLNode node, Content contentTree) {
   String component = node.name;
   try {
     invokeMethod(
         "build" + component,
         new Class<?>[] {XMLNode.class, Content.class},
         new Object[] {node, contentTree});
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
     configuration.root.printError("Unknown element: " + component);
     throw new DocletAbortException(e);
   } catch (InvocationTargetException e) {
     throw new DocletAbortException(e.getCause());
   } catch (Exception e) {
     e.printStackTrace();
     configuration.root.printError(
         "Exception " + e.getClass().getName() + " thrown while processing element: " + component);
     throw new DocletAbortException(e);
   }
 }
Esempio n. 14
0
 protected synchronized Message receiveMessage() throws IOException {
   if (messageBuffer.size() > 0) {
     Message m = (Message) messageBuffer.get(0);
     messageBuffer.remove(0);
     return m;
   }
   try {
     InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer);
     if (remoteAddress != null) {
       int len = receiveBuffer.position();
       receiveBuffer.rewind();
       receiveBuffer.get(buf, 0, len);
       try {
         IP address = IP.fromInetAddress(remoteAddress.getAddress());
         int port = remoteAddress.getPort();
         extractor.appendData(buf, 0, len, new SocketDescriptor(address, port));
         receiveBuffer.clear();
         extractor.updateAvailableMessages();
         return extractor.nextMessage();
       } catch (EOFException exc) {
         exc.printStackTrace();
         System.err.println(buf.length + ", " + len);
       } catch (InvocationTargetException exc) {
         exc.printStackTrace();
       } catch (IllegalAccessException exc) {
         exc.printStackTrace();
       } catch (InstantiationException exc) {
         exc.printStackTrace();
       } catch (IllegalArgumentException e) {
         e.printStackTrace();
       } catch (InvalidCompressionMethodException e) {
         e.printStackTrace();
       }
     }
   } catch (ClosedChannelException exc) {
     if (isKeepAlive()) {
       throw exc;
     }
   }
   return null;
 }
Esempio n. 15
0
  /** Clears the view. */
  @Override
  public void clear() {
    final Drawing newDrawing = createDrawing();
    try {
      SwingUtilities.invokeAndWait(
          new Runnable() {

            @Override
            public void run() {
              view.getDrawing().removeUndoableEditListener(undo);
              view.setDrawing(newDrawing);
              view.getDrawing().addUndoableEditListener(undo);
              undo.discardAllEdits();
            }
          });
    } catch (InvocationTargetException ex) {
      ex.printStackTrace();
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }
  }
Esempio n. 16
0
 /**
  * If the causal chain has a sun.jvm.hotspot.runtime.VMVersionMismatchException, attempt to load
  * VirtualMachineImpl class for target VM version.
  */
 protected static Class handleVMVersionMismatch(InvocationTargetException ite) {
   Throwable cause = ite.getCause();
   if (DEBUG) {
     System.out.println("checking for version mismatch...");
   }
   while (cause != null) {
     try {
       if (isVMVersionMismatch(cause)) {
         if (DEBUG) {
           System.out.println("Triggering cross VM version support...");
         }
         return loadVirtualMachineImplClass(getVMVersion(cause));
       }
     } catch (Exception exp) {
       if (DEBUG) {
         System.out.println("failed to load VirtualMachineImpl class");
         exp.printStackTrace();
       }
       return null;
     }
     cause = cause.getCause();
   }
   return null;
 }
Esempio n. 17
0
  /**
   * Processes the request coming to the servlet and grabs the attributes set by the servlet and
   * uses them to fire off pre-determined methods set in the setupActionMethods function of the
   * servlet.
   *
   * @param request the http request coming from the browser.
   * @param response the http response going to the browser.
   * @throws javax.servlet.ServletException
   * @throws java.io.IOException
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (!actionInitialized) {
      LogController.write(this, "This dispatcher servlet is not initialized properly!");
      return;
    }

    if (actionTag == null) {
      LogController.write(this, "There is no action attribute tag name!");
      return;
    }

    HttpSession httpSession = request.getSession();
    UserSession userSession = (UserSession) httpSession.getAttribute("user_session");

    if (userSession == null) {
      LogController.write(this, "User session is no longer available in this http session.");

      userSession = new UserSession();

      // We always want a user session though...
      httpSession.setAttribute("user_session", userSession);
    }

    String action = (String) request.getAttribute(actionTag);

    try {
      if (action == null) {
        // There is no action attribute specified, check parameters.
        String external_action = (String) request.getParameter(actionTag);

        if (external_action != null) {
          Method method = externalActions.get(external_action);

          if (method != null) {
            LogController.write(this, "Performing external action: " + external_action);
            method.invoke(this, new Object[] {userSession, request, response});
          } else {
            if (defaultExternalMethod != null) {
              LogController.write(this, "Performing default external action.");
              defaultExternalMethod.invoke(this, new Object[] {userSession, request, response});
            } else {
              LogController.write(this, "Unable to perform default external action.");
            }
          }
        } else {
          if (defaultExternalMethod != null) {
            LogController.write(this, "Performing default external action.");
            defaultExternalMethod.invoke(this, new Object[] {userSession, request, response});
          } else {
            LogController.write(this, "Unable to perform default external action.");
          }
        }
      } else {
        Method method = internalActions.get(action);

        if (method != null) {
          LogController.write(this, "Performing internal action: " + action);
          method.invoke(this, new Object[] {userSession, request, response});
        } else {
          if (defaultInternalMethod != null) {
            LogController.write(this, "Performing default internal action.");
            defaultInternalMethod.invoke(this, new Object[] {userSession, request, response});
          } else {
            LogController.write(this, "Unable to perform default internal action.");
          }
        }

        request.removeAttribute("application_action");
      }
    } catch (IllegalAccessException accessEx) {
      LogController.write(this, "Exception while processing request: " + accessEx.getMessage());
    } catch (InvocationTargetException invokeEx) {
      LogController.write(this, "Exception while processing request: " + invokeEx.toString());
      invokeEx.printStackTrace();
    } catch (Exception ex) {
      LogController.write(this, "Unknown exception: " + ex.toString());
    }
  }
Esempio n. 18
0
 private void dump() throws IOException {
   lookupMethod = null;
   try {
     lookupMethod = catalog.getClass().getMethod("lookup", new Class[] {java.lang.String.class});
   } catch (NoSuchMethodException e) {
   } catch (SecurityException e) {
   }
   Method pluralMethod = null;
   try {
     pluralMethod = catalog.getClass().getMethod("get_msgid_plural_table", new Class[0]);
   } catch (NoSuchMethodException e) {
   } catch (SecurityException e) {
   }
   Field pluralField = null;
   try {
     pluralField = catalog.getClass().getField("plural");
   } catch (NoSuchFieldException e) {
   } catch (SecurityException e) {
   }
   // Search for the header entry.
   {
     Object header_entry = null;
     Enumeration keys = catalog.getKeys();
     while (keys.hasMoreElements())
       if ("".equals(keys.nextElement())) {
         header_entry = lookup("");
         break;
       }
     // If there is no header entry, fake one.
     // FIXME: This is not needed; right after po_lex_charset_init set
     // the PO charset to UTF-8.
     if (header_entry == null) header_entry = "Content-Type: text/plain; charset=UTF-8\n";
     dumpMessage("", null, header_entry);
   }
   // Now the other messages.
   {
     Enumeration keys = catalog.getKeys();
     Object plural = null;
     if (pluralMethod != null) {
       // msgfmt versions > 0.13.1 create a static get_msgid_plural_table()
       // method.
       try {
         plural = pluralMethod.invoke(catalog, new Object[0]);
       } catch (IllegalAccessException e) {
         e.printStackTrace();
       } catch (InvocationTargetException e) {
         e.getTargetException().printStackTrace();
       }
     } else if (pluralField != null) {
       // msgfmt versions <= 0.13.1 create a static plural field.
       try {
         plural = pluralField.get(catalog);
       } catch (IllegalAccessException e) {
         e.printStackTrace();
       }
     }
     if (plural instanceof String[]) {
       // A GNU gettext created class with plural handling, Java2 format.
       int i = 0;
       while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         Object value = lookup(key);
         String key_plural = (value instanceof String[] ? ((String[]) plural)[i++] : null);
         if (!"".equals(key)) dumpMessage(key, key_plural, value);
       }
       if (i != ((String[]) plural).length)
         throw new RuntimeException("wrong plural field length");
     } else if (plural instanceof Hashtable) {
       // A GNU gettext created class with plural handling, Java format.
       while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         if (!"".equals(key)) {
           Object value = lookup(key);
           String key_plural =
               (value instanceof String[] ? (String) ((Hashtable) plural).get(key) : null);
           dumpMessage(key, key_plural, value);
         }
       }
     } else if (plural == null) {
       // No plural handling.
       while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         if (!"".equals(key)) dumpMessage(key, null, lookup(key));
       }
     } else throw new RuntimeException("wrong plural field value");
   }
 }
Esempio n. 19
0
  /**
   * 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;
    }
  }
Esempio n. 20
0
  /**
   * 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());
    }
  }