コード例 #1
0
ファイル: XPathException.java プロジェクト: nuxleus/saxonica
 /*@NotNull*/ public static XPathException makeXPathException(
     /*@NotNull*/ TransformerException err) {
   if (err instanceof XPathException) {
     return (XPathException) err;
   } else if (err.getException() instanceof XPathException) {
     return (XPathException) err.getException();
   } else {
     return new XPathException(err);
   }
 }
コード例 #2
0
 public void parse(InputSource input) throws IOException, SAXException {
   try {
     LocationFilter handler =
         new LocationFilter(new ErrorFilter(contentHandler, ceh, localizer), systemId);
     transformer.transform(transformSource, new SAXResult(handler));
     SAXException exception = handler.getException();
     if (exception != null) throw exception;
   } catch (TransformerException e) {
     if (e.getException() instanceof IOException) throw (IOException) e.getException();
     throw ValidatorImpl.toSAXException(e);
   }
   if (ceh.getHadErrorOrFatalError()) throw new SAXException(new IncorrectSchemaException());
 }
コード例 #3
0
ファイル: XQueryExpression.java プロジェクト: orbeon/saxon
  /**
   * Get an iterator over the results of the expression. This returns results without any conversion
   * of the returned items to "native" Java classes. The iterator will deliver a sequence of Item
   * objects, each item being either a NodeInfo (representing a node) or an AtomicValue
   * (representing an atomic value).
   *
   * <p>
   *
   * <p>To get the results of the query in the form of an XML document in which each item is wrapped
   * by an element indicating its type, use:
   *
   * <p>
   *
   * <p><code>QueryResult.wrap(iterator(env))</code>
   *
   * <p>
   *
   * <p>To serialize the results to a file, use the QueryResult.serialize() method.
   *
   * @param env Provides the dynamic query evaluation context
   * @return an iterator over the results of the query. The class SequenceIterator is modeled on the
   *     standard Java Iterator class, but has extra functionality and can throw exceptions when
   *     errors occur.
   * @throws XPathException if a dynamic error occurs in evaluating the query. Some dynamic errors
   *     will not be reported by this method, but will only be reported when the individual items of
   *     the result are accessed using the returned iterator.
   */
  public SequenceIterator iterator(DynamicQueryContext env) throws XPathException {
    if (isUpdating) {
      throw new XPathException("Cannot call iterator() on an updating query");
    }
    Controller controller = newController();
    initializeController(env, controller);

    try {
      Item contextItem = env.getContextItem();

      // Bindery bindery = controller.getBindery();
      // bindery.openStackFrame();
      controller.defineGlobalParameters();
      XPathContextMajor context = controller.newXPathContext();

      if (contextItem != null) {
        if (!staticContext
            .getUserQueryContext()
            .getRequiredContextItemType()
            .matchesItem(contextItem, false, env.getConfiguration())) {
          throw new XPathException(
              "The supplied context item does not match the required context item type");
        }
        UnfailingIterator single = SingletonIterator.makeIterator(contextItem);
        single.next();
        context.setCurrentIterator(single);
        controller.setInitialContextItem(contextItem);
      }

      // In tracing/debugging mode, evaluate all the global variables first
      if (controller.getTraceListener() != null) {
        controller.preEvaluateGlobals(context);
      }

      context.openStackFrame(stackFrameMap);

      SequenceIterator iterator = expression.iterate(context);
      return new ErrorReportingIterator(iterator, controller.getErrorListener());
    } catch (XPathException err) {
      TransformerException terr = err;
      while (terr.getException() instanceof TransformerException) {
        terr = (TransformerException) terr.getException();
      }
      XPathException de = XPathException.makeXPathException(terr);
      controller.reportFatalError(de);
      throw de;
    }
  }
コード例 #4
0
  /**
   * Print the the trace of methods from where the error originated. This will trace all nested
   * exception objects, as well as this object.
   *
   * @param s The stream where the dump will be sent to.
   */
  public void printStackTrace(java.io.PrintStream s) {

    if (s == null) s = System.err;

    try {
      super.printStackTrace(s);
    } catch (Exception e) {
    }

    Throwable exception = m_exception;

    for (int i = 0; (i < 10) && (null != exception); i++) {
      s.println("---------");
      exception.printStackTrace(s);

      if (exception instanceof TransformerException) {
        TransformerException se = (TransformerException) exception;
        Throwable prev = exception;

        exception = se.getException();

        if (prev == exception) break;
      } else {
        exception = null;
      }
    }
  }
コード例 #5
0
  private String formatXML(String str) {
    try {
      // Use a Transformer for output
      TransformerFactory tFactory = TransformerFactory.newInstance();
      // Surround this setting in a try/catch for compatibility with Java 1.4. This setting is
      // required
      // for Java 1.5
      try {
        tFactory.setAttribute("indent-number", 2);
      } catch (IllegalArgumentException e) {
        // Ignore
      }
      Transformer transformer = tFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      // Transform the requested string into a nice formatted XML string
      StreamSource source = new StreamSource(new StringReader(str));
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);
      transformer.transform(source, result);
      return sw.toString();

    } catch (TransformerConfigurationException tce) {
      // Error generated by the parser
      System.out.println("\n** Transformer Factory error");
      System.out.println("   " + tce.getMessage());

      // Use the contained exception, if any
      Throwable x = tce;
      if (tce.getException() != null) x = tce.getException();
      x.printStackTrace();

    } catch (TransformerException te) {
      // Error generated by the parser
      System.out.println("\n** Transformation error");
      System.out.println("   " + te.getMessage());

      // Use the contained exception, if any
      Throwable x = te;
      if (te.getException() != null) x = te.getException();
      x.printStackTrace();
    }
    return str;
  }
コード例 #6
0
  public void validate(Source source, Result result) throws SAXException, IOException {

    if (result == null || result instanceof StAXResult) {

      if (identityTransformer1 == null) {
        try {
          SAXTransformerFactory tf =
              fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM)
                  ? (SAXTransformerFactory) SAXTransformerFactory.newInstance()
                  : (SAXTransformerFactory)
                      TransformerFactory.newInstance(
                          DEFAULT_TRANSFORMER_IMPL, StAXValidatorHelper.class.getClassLoader());
          identityTransformer1 = tf.newTransformer();
          identityTransformer2 = tf.newTransformerHandler();
        } catch (TransformerConfigurationException e) {
          // this is impossible, but again better safe than sorry
          throw new TransformerFactoryConfigurationError(e);
        }
      }

      handler = new ValidatorHandlerImpl(fComponentManager);
      if (result != null) {
        handler.setContentHandler(identityTransformer2);
        identityTransformer2.setResult(result);
      }

      try {
        identityTransformer1.transform(source, new SAXResult(handler));
      } catch (TransformerException e) {
        if (e.getException() instanceof SAXException) throw (SAXException) e.getException();
        throw new SAXException(e);
      } finally {
        handler.setContentHandler(null);
      }
      return;
    }
    throw new IllegalArgumentException(
        JAXPValidationMessageFormatter.formatMessage(
            Locale.getDefault(),
            "SourceResultMismatch",
            new Object[] {source.getClass().getName(), result.getClass().getName()}));
  }
コード例 #7
0
 SAXParseException transform(TransformerException exception) throws TransformerException {
   Throwable cause = exception.getException();
   // Xalan takes it upon itself to catch exceptions and pass them to the ErrorListener.
   if (cause instanceof RuntimeException) throw (RuntimeException) cause;
   if (cause instanceof SAXException
       || cause instanceof IncorrectSchemaException
       || cause instanceof IOException) throw exception;
   SourceLocator locator = exception.getLocator();
   if (locator == null) return new SAXParseException(exception.getMessage(), null);
   // Xalan sometimes loses the systemId; work around this.
   String s = locator.getSystemId();
   if (s == null) s = systemId;
   return new SAXParseException(exception.getMessage(), null, s, locator.getLineNumber(), -1);
 }
コード例 #8
0
  /**
   * Print the the trace of methods from where the error originated. This will trace all nested
   * exception objects, as well as this object.
   *
   * @param s The writer where the dump will be sent to.
   */
  public void printStackTrace(java.io.PrintWriter s) {

    if (s == null) s = new java.io.PrintWriter(System.err);

    try {
      super.printStackTrace(s);
    } catch (Exception e) {
    }

    boolean isJdk14OrHigher = false;
    try {
      Throwable.class.getMethod("getCause", null);
      isJdk14OrHigher = true;
    } catch (NoSuchMethodException nsme) {
      // do nothing
    }

    // The printStackTrace method of the Throwable class in jdk 1.4
    // and higher will include the cause when printing the backtrace.
    // The following code is only required when using jdk 1.3 or lower
    if (!isJdk14OrHigher) {

      Throwable exception = m_exception;

      for (int i = 0; (i < 10) && (null != exception); i++) {
        s.println("---------");

        try {
          exception.printStackTrace(s);
        } catch (Exception e) {
          s.println("Could not print stack trace...");
        }

        if (exception instanceof TransformerException) {
          TransformerException se = (TransformerException) exception;
          Throwable prev = exception;

          exception = se.getException();

          if (prev == exception) {
            exception = null;

            break;
          }
        } else {
          exception = null;
        }
      }
    }
  }
コード例 #9
0
  /** Unwraps original throwable from the transformer/ SAX stack. */
  private Throwable unwrapCause(TransformerException e) {
    Throwable t;

    if (e.getException() != null) {
      t = e.getException();
    } else if (e.getCause() != null) {
      t = e.getCause();
    } else {
      return e;
    }

    do {
      if (t instanceof IOException) {
        // break early on IOException
        return t;
      } else if (t.getCause() != null) {
        t = t.getCause();
      } else if (t instanceof SAXException && ((SAXException) t).getException() != null) {
        t = ((SAXException) t).getException();
      } else {
        return t;
      }
    } while (true);
  }
コード例 #10
0
  /**
   * Find the most contained message.
   *
   * @return The error message of the originating exception.
   */
  public String getMessage() {

    String lastMessage = super.getMessage();
    Throwable exception = m_exception;

    while (null != exception) {
      String nextMessage = exception.getMessage();

      if (null != nextMessage) lastMessage = nextMessage;

      if (exception instanceof TransformerException) {
        TransformerException se = (TransformerException) exception;
        Throwable prev = exception;

        exception = se.getException();

        if (prev == exception) break;
      } else {
        exception = null;
      }
    }

    return (null != lastMessage) ? lastMessage : "";
  }
コード例 #11
0
  /**
   * Saves the templates as XML.
   *
   * @param templates the templates to save
   * @param result the stream result to write to
   * @throws IOException if writing the templates fails
   */
  private void save(TemplatePersistenceData[] templates, StreamResult result) throws IOException {
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.newDocument();

      Node root = document.createElement(TEMPLATE_ROOT);
      document.appendChild(root);

      for (int i = 0; i < templates.length; i++) {
        TemplatePersistenceData data = templates[i];
        Template template = data.getTemplate();

        Node node = document.createElement(TEMPLATE_ELEMENT);
        root.appendChild(node);

        NamedNodeMap attributes = node.getAttributes();

        String id = data.getId();
        if (id != null) {
          Attr idAttr = document.createAttribute(ID_ATTRIBUTE);
          idAttr.setValue(id);
          attributes.setNamedItem(idAttr);
        }

        if (template != null) {
          Attr name = document.createAttribute(NAME_ATTRIBUTE);
          name.setValue(template.getName());
          attributes.setNamedItem(name);
        }

        if (template != null) {
          Attr proposalDesc = document.createAttribute(PROPOSAL_POPUP_DESCRIPTION);
          if (template instanceof SQLTemplate) {
            proposalDesc.setValue(((SQLTemplate) template).getProposalPopupDescription());
          }
          attributes.setNamedItem(proposalDesc);
        }

        if (template != null) {
          Attr description = document.createAttribute(DESCRIPTION_ATTRIBUTE);
          description.setValue(template.getDescription());
          attributes.setNamedItem(description);
        }

        if (template != null) {
          Attr context = document.createAttribute(CONTEXT_ATTRIBUTE);
          context.setValue(template.getContextTypeId());
          attributes.setNamedItem(context);
        }

        Attr enabled = document.createAttribute(ENABLED_ATTRIBUTE);
        enabled.setValue(data.isEnabled() ? Boolean.toString(true) : Boolean.toString(false));
        attributes.setNamedItem(enabled);

        Attr deleted = document.createAttribute(DELETED_ATTRIBUTE);
        deleted.setValue(data.isDeleted() ? Boolean.toString(true) : Boolean.toString(false));
        attributes.setNamedItem(deleted);

        if (template != null) {
          Attr autoInsertable = document.createAttribute(AUTO_INSERTABLE_ATTRIBUTE);
          autoInsertable.setValue(
              template.isAutoInsertable() ? Boolean.toString(true) : Boolean.toString(false));
          attributes.setNamedItem(autoInsertable);
        }

        if (template != null) {
          Text pattern = document.createTextNode(template.getPattern());
          node.appendChild(pattern);
        }
      }

      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // $NON-NLS-1$
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // $NON-NLS-1$
      DOMSource source = new DOMSource(document);

      transformer.transform(source, result);

    } catch (ParserConfigurationException e) {
      Assert.isTrue(false);
    } catch (TransformerException e) {
      if (e.getException() instanceof IOException) throw (IOException) e.getException();
      Assert.isTrue(false);
    }
  }
コード例 #12
0
 private SAXException toSAXException(TransformerException e, boolean hadError)
     throws IOException, IncorrectSchemaException {
   return causeToSAXException(e.getException(), hadError);
 }