コード例 #1
1
 /*     */ public Source getContent() throws SOAPException {
   /* 193 */ if (this.source != null) {
     /* 194 */ InputStream bis = null;
     /* 195 */ if ((this.source instanceof JAXMStreamSource)) {
       /* 196 */ StreamSource streamSource = (StreamSource) this.source;
       /* 197 */ bis = streamSource.getInputStream();
       /* 198 */ } else if (FastInfosetReflection.isFastInfosetSource(this.source))
     /*     */ {
       /* 200 */ SAXSource saxSource = (SAXSource) this.source;
       /* 201 */ bis = saxSource.getInputSource().getByteStream();
       /*     */ }
     /*     */
     /* 204 */ if (bis != null) {
       /*     */ try {
         /* 206 */ bis.reset();
         /*     */ }
       /*     */ catch (IOException e)
       /*     */ {
         /*     */ }
       /*     */
       /*     */ }
     /*     */
     /* 217 */ return this.source;
     /*     */ }
   /*     */
   /* 220 */ return ((Envelope) getEnvelope()).getContent();
   /*     */ }
コード例 #2
0
  private CharSequence readFile(String href, String baseURI) throws XPathException {
    try {

      // Use resolver as it does a series of tasks for us, and use "binary" mode
      final TransformerURIResolver resolver =
          new TransformerURIResolver(
              null, PipelineContext.get(), null, XMLParsing.ParserConfiguration.PLAIN, "binary");

      final StringBuilder sb = new StringBuilder(1024);

      // Get SAX source using crazy SAX API
      // Source produces a binary document (content Base64-encoded)
      final SAXSource source = (SAXSource) resolver.resolve(href, baseURI);
      final XMLReader xmlReader = source.getXMLReader();
      xmlReader.setContentHandler(
          new XMLReceiverAdapter() {
            public void characters(char ch[], int start, int length) throws SAXException {
              // Append Base64-encoded text only
              sb.append(ch, start, length);
            }
          });
      xmlReader.parse(source.getInputSource());

      // Return content formatted as Base64
      return sb.toString();
    } catch (Exception e) {
      throw new XPathException(e);
    }
  }
  private void parseSAX(Source source, ContentHandler handler)
      throws TransformerConfigurationException {
    try {
      if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;

        XMLReader reader = saxSource.getXMLReader();
        InputSource inputSource = saxSource.getInputSource();

        reader.setContentHandler(handler);

        reader.parse(inputSource);
      } else if (source instanceof StreamSource) {

        XmlParser parser = new Xml();

        parser.setContentHandler(handler);

        ReadStream rs = openPath(source);
        try {
          parser.parse(rs);
        } finally {
          rs.close();
        }
      } else if (source instanceof DOMSource) {
        DOMSource domSource = (DOMSource) source;

        Node node = domSource.getNode();

        XmlUtil.toSAX(node, handler);
      }
    } catch (Exception e) {
      throw new TransformerConfigurationException(e);
    }
  }
コード例 #4
0
 public Source resolve(String href, String base) throws TransformerException {
   if (href == null || href.trim().length() == 0) {
     throw new TransformerException("href is null");
   }
   try {
     String aname = defaultXslStylesheetBase + href;
     if (aname.indexOf("..") != -1) {
       aname = new File(aname).getCanonicalPath().toString();
     }
     if (m_bundleContect.getBundle().getEntry(aname) == null) {
       aname = defaultXslStylesheetBase2 + href;
     }
     if (m_bundleContect.getBundle().getEntry(aname) == null) {
       aname = defaultXslStylesheetBase3 + href;
     }
     SAXSource ss =
         new SAXSource(new InputSource(m_bundleContect.getBundle().getEntry(aname).openStream()));
     XMLReader reader = m_saxParserFactory.newSAXParser().getXMLReader();
     ReaderConfig rc = ((WstxSAXParser) reader).getStaxConfig();
     rc.setXMLResolver(new XslURIResolver(m_bundleContect, m_saxParserFactory));
     ss.setXMLReader(reader);
     return ss;
   } catch (Exception e) {
     throw new RuntimeException("XslURIResolver.resolve", e);
   }
 }
コード例 #5
0
  public void process(Exchange exchange) throws Exception {
    Jaxp11XMLReaderCreator xmlCreator = new Jaxp11XMLReaderCreator();
    DefaultValidationErrorHandler errorHandler = new DefaultValidationErrorHandler();

    PropertyMapBuilder mapBuilder = new PropertyMapBuilder();
    mapBuilder.put(ValidateProperty.XML_READER_CREATOR, xmlCreator);
    mapBuilder.put(ValidateProperty.ERROR_HANDLER, errorHandler);
    PropertyMap propertyMap = mapBuilder.toPropertyMap();

    Validator validator = getSchema().createValidator(propertyMap);

    Message in = exchange.getIn();
    SAXSource saxSource = in.getBody(SAXSource.class);
    if (saxSource == null) {
      Source source = exchange.getIn().getMandatoryBody(Source.class);
      saxSource = ExchangeHelper.convertToMandatoryType(exchange, SAXSource.class, source);
    }
    InputSource bodyInput = saxSource.getInputSource();

    // now lets parse the body using the validator
    XMLReader reader = xmlCreator.createXMLReader();
    reader.setContentHandler(validator.getContentHandler());
    reader.setDTDHandler(validator.getDTDHandler());
    reader.setErrorHandler(errorHandler);
    reader.parse(bodyInput);

    errorHandler.handleErrors(exchange, schema);
  }
コード例 #6
0
ファイル: ERXSLTWrapper.java プロジェクト: konradwyr/wonder
 public static NSData transform(Transformer transformer, NSData data) throws TransformerException {
   ByteArrayInputStream bis = new ByteArrayInputStream(data.bytes());
   SAXSource saxSource = new SAXSource();
   saxSource.setXMLReader(xmlReader);
   saxSource.setInputSource(new InputSource(bis));
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   Result r = new StreamResult(os);
   transformer.transform(saxSource, r);
   NSData result = new NSData(os.toByteArray());
   return result;
 }
  /**
   * Create a compiled stylesheet from an input stream.
   *
   * @param source the source stream
   * @return the compiled stylesheet
   */
  public Templates newTemplates(Source source) throws TransformerConfigurationException {
    String systemId = source.getSystemId();

    try {
      if (systemId != null) {
        StylesheetImpl stylesheet = loadPrecompiledStylesheet(systemId, systemId);

        if (stylesheet != null) return stylesheet;
      }

      if (source instanceof DOMSource) {
        Node node = ((DOMSource) source).getNode();

        return generateFromNode(node, systemId);
      } else if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;
        XMLReader reader = saxSource.getXMLReader();
        InputSource inputSource = saxSource.getInputSource();

        Document doc = new QDocument();
        DOMBuilder builder = new DOMBuilder();
        builder.init(doc);
        reader.setContentHandler(builder);

        reader.parse(inputSource);

        return generateFromNode(doc, systemId);
      }

      ReadStream rs = openPath(source);
      try {
        Path path = rs.getPath();

        Document doc = parseXSL(rs);

        if (systemId != null) {
          String mangledName = getMangledName(systemId);
          Path genPath = getWorkPath().lookup(mangledName);

          genPath.setUserPath(systemId);

          return generate(doc, genPath);
        } else return generateFromNode(doc, null);
      } finally {
        if (rs != null) rs.close();
      }
    } catch (TransformerConfigurationException e) {
      throw e;
    } catch (Exception e) {
      throw new XslParseException(e);
    }
  }
コード例 #8
0
ファイル: JAXBSource.java プロジェクト: JetBrains/jdk8u_jaxws
  /**
   * Creates a new {@link javax.xml.transform.Source} for the given content object.
   *
   * @param marshaller A marshaller instance that will be used to marshal <code>contentObject</code>
   *     into XML. This must be created from a JAXBContext that was used to build <code>
   *     contentObject</code> and must not be null.
   * @param contentObject An instance of a JAXB-generated class, which will be used as a {@link
   *     javax.xml.transform.Source} (by marshalling it into XML). It must not be null.
   * @throws JAXBException if an error is encountered while creating the JAXBSource or if either of
   *     the parameters are null.
   */
  public JAXBSource(Marshaller marshaller, Object contentObject) throws JAXBException {

    if (marshaller == null)
      throw new JAXBException(Messages.format(Messages.SOURCE_NULL_MARSHALLER));

    if (contentObject == null)
      throw new JAXBException(Messages.format(Messages.SOURCE_NULL_CONTENT));

    this.marshaller = marshaller;
    this.contentObject = contentObject;

    super.setXMLReader(pseudoParser);
    // pass a dummy InputSource. We don't care
    super.setInputSource(new InputSource());
  }
コード例 #9
0
  /**
   * Returns a SAX source.
   *
   * @param xmlRepresentation The XML representation to wrap.
   * @return A SAX source.
   * @throws IOException
   */
  public static javax.xml.transform.sax.SAXSource getSaxSource(Representation xmlRepresentation)
      throws IOException {
    javax.xml.transform.sax.SAXSource result = null;

    if (xmlRepresentation != null) {
      result =
          new javax.xml.transform.sax.SAXSource(new InputSource(xmlRepresentation.getStream()));

      if (xmlRepresentation.getLocationRef() != null) {
        result.setSystemId(xmlRepresentation.getLocationRef().getTargetRef().toString());
      }
    }

    return result;
  }
コード例 #10
0
ファイル: TransformerImpl.java プロジェクト: blnz/palomar
  /** Process the source tree to the output result. */
  public void transform(Source source, Result result) throws TransformerException {

    XSLProcessorImpl processor = init(result);

    try {
      // now find an adapter for the input source
      XMLReader reader = _factory.getReader(source);
      processor.setSourceReader(reader);
      String sysId = source.getSystemId();
      InputSource src = SAXSource.sourceToInputSource(source);
      if (src == null) {
        if (sysId == null) {
          src = new InputSource("dummy");
        } else {
          src = new InputSource(sysId);
        }
      }

      // FIXME: set error handler
      processor.parse(src);

    } catch (Exception ex) {
      throw new TransformerException(ex);
    }
  }
コード例 #11
0
ファイル: DocumentSource.java プロジェクト: dom4j/dom4j
 /**
  * This method is not supported as this source is always a {@link Document} instance.
  *
  * @param inputSource DOCUMENT ME!
  * @throws UnsupportedOperationException as this method is unsupported
  */
 public void setInputSource(InputSource inputSource) throws UnsupportedOperationException {
   if (inputSource instanceof DocumentInputSource) {
     super.setInputSource((DocumentInputSource) inputSource);
   } else {
     throw new UnsupportedOperationException();
   }
 }
コード例 #12
0
 @POST
 @Path("source")
 @Consumes("text/xml")
 @Produces("text/plain")
 public byte[] xsltPost(Source source) throws IOException {
   final InputSource inputSource = SAXSource.sourceToInputSource(source);
   return TestUtils.getByteArray(inputSource.getByteStream());
 }
コード例 #13
0
  public Object unmarshal0(Source source, JaxBeanInfo expectedType) throws JAXBException {
    if (source instanceof SAXSource) {
      SAXSource ss = (SAXSource) source;

      XMLReader reader = ss.getXMLReader();
      if (reader == null) reader = getXMLReader();

      return unmarshal0(reader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
      return unmarshal0(
          getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource)
      return unmarshal0(((DOMSource) source).getNode(), expectedType);

    // we don't handle other types of Source
    throw new IllegalArgumentException();
  }
コード例 #14
0
  @Override
  public <T> JAXBElement<T> unmarshal(Source source, Class<T> expectedType) throws JAXBException {
    if (source instanceof SAXSource) {
      SAXSource ss = (SAXSource) source;

      XMLReader reader = ss.getXMLReader();
      if (reader == null) reader = getXMLReader();

      return unmarshal(reader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
      return unmarshal(
          getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) return unmarshal(((DOMSource) source).getNode(), expectedType);

    // we don't handle other types of Source
    throw new IllegalArgumentException();
  }
コード例 #15
0
  @Override
  protected Object unmarshalFromInputStream(
      Unmarshaller unmarshaller, InputStream is, Annotation[] anns, MediaType mt)
      throws JAXBException {
    try {

      Templates t = createTemplates(getInTemplates(anns, mt), inParamsMap, inProperties);
      if (t == null && supportJaxbOnly) {
        return super.unmarshalFromInputStream(unmarshaller, is, anns, mt);
      }

      if (unmarshaller.getClass().getName().contains("eclipse")) {
        // eclipse MOXy doesn't work properly with the XMLFilter/Reader thing
        // so we need to bounce through a DOM
        Source reader = new StaxSource(StaxUtils.createXMLStreamReader(is));
        DOMResult dom = new DOMResult();
        t.newTransformer().transform(reader, dom);
        return unmarshaller.unmarshal(dom.getNode());
      }
      XMLFilter filter = null;
      try {
        filter = factory.newXMLFilter(t);
      } catch (TransformerConfigurationException ex) {
        TemplatesImpl ti = (TemplatesImpl) t;
        filter = factory.newXMLFilter(ti.getTemplates());
        trySettingProperties(filter, ti);
      }
      XMLReader reader = new StaxSource(StaxUtils.createXMLStreamReader(is));
      filter.setParent(reader);
      SAXSource source = new SAXSource();
      source.setXMLReader(filter);
      if (systemId != null) {
        source.setSystemId(systemId);
      }
      return unmarshaller.unmarshal(source);
    } catch (TransformerException ex) {
      LOG.warning("Transformation exception : " + ex.getMessage());
      throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
  }
コード例 #16
0
  public static Envelope createEnvelope(Source src, SOAPPartImpl soapPart) throws SOAPException {
    // Insert SAX filter to disallow Document Type Declarations since
    // they are not legal in SOAP
    SAXParser saxParser = null;
    if (src instanceof StreamSource) {
      if (src instanceof JAXMStreamSource) {
        try {
          ((JAXMStreamSource) src).reset();
        } catch (java.io.IOException ioe) {
          log.severe("SAAJ0515.source.reset.exception");
          throw new SOAPExceptionImpl(ioe);
        }
      }
      try {
        saxParser = parserPool.get();
      } catch (Exception e) {
        log.severe("SAAJ0601.util.newSAXParser.exception");
        throw new SOAPExceptionImpl("Couldn't get a SAX parser while constructing a envelope", e);
      }
      InputSource is = SAXSource.sourceToInputSource(src);
      XMLReader rejectFilter;
      try {
        rejectFilter = new RejectDoctypeSaxFilter(saxParser);
      } catch (Exception ex) {
        log.severe("SAAJ0510.soap.cannot.create.envelope");
        throw new SOAPExceptionImpl("Unable to create envelope from given source: ", ex);
      }
      src = new SAXSource(rejectFilter, is);
    }

    try {
      Transformer transformer = EfficientStreamingTransformer.newTransformer();
      DOMResult result = new DOMResult(soapPart);
      transformer.transform(src, result);

      Envelope env = (Envelope) soapPart.getEnvelope();
      if (saxParser != null) {
        parserPool.put(saxParser);
      }
      return env;
    } catch (Exception ex) {
      if (ex instanceof SOAPVersionMismatchException) {
        throw (SOAPVersionMismatchException) ex;
      }
      log.severe("SAAJ0511.soap.cannot.create.envelope");
      throw new SOAPExceptionImpl("Unable to create envelope from given source: ", ex);
    }
  }
コード例 #17
0
  public <T> JAXBElement<T> unmarshal(Source source, Class<T> declaredType) throws JAXBException {
    if (source instanceof SAXSource) {
      try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xmlReader = sp.getXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/validation", false);
        xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        ((SAXSource) source).setXMLReader(xmlReader);
        return delegate.unmarshal(source, declaredType);
      } catch (SAXException e) {
        throw new JAXBException(e);
      } catch (ParserConfigurationException e) {
        throw new JAXBException(e);
      }
    }

    throw new UnsupportedOperationException(errorMessage("Source, Class<T>"));
  }
コード例 #18
0
  public void validate(Source source, Result result) throws SAXException, IOException {
    if (result instanceof SAXResult || result == null) {
      final SAXSource saxSource = (SAXSource) source;
      final SAXResult saxResult = (SAXResult) result;

      if (result != null) {
        setContentHandler(saxResult.getHandler());
      }

      try {
        XMLReader reader = saxSource.getXMLReader();
        if (reader == null) {
          // create one now
          SAXParserFactory spf = SAXParserFactory.newInstance();
          spf.setNamespaceAware(true);
          try {
            reader = spf.newSAXParser().getXMLReader();
            // If this is a Xerces SAX parser, set the security manager if there is one
            if (reader instanceof com.sun.org.apache.xerces.internal.parsers.SAXParser) {
              SecurityManager securityManager =
                  (SecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
              if (securityManager != null) {
                try {
                  reader.setProperty(SECURITY_MANAGER, securityManager);
                }
                // Ignore the exception if the security manager cannot be set.
                catch (SAXException exc) {
                }
              }
            }
          } catch (Exception e) {
            // this is impossible, but better safe than sorry
            throw new FactoryConfigurationError(e);
          }
        }

        // If XML names and Namespace URIs are already internalized we
        // can avoid running them through the SymbolTable.
        try {
          fStringsInternalized = reader.getFeature(STRING_INTERNING);
        } catch (SAXException exc) {
          // The feature isn't recognized or getting it is not supported.
          // In either case, assume that strings are not internalized.
          fStringsInternalized = false;
        }

        ErrorHandler errorHandler = fComponentManager.getErrorHandler();
        reader.setErrorHandler(
            errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance());
        reader.setEntityResolver(fResolutionForwarder);
        fResolutionForwarder.setEntityResolver(fComponentManager.getResourceResolver());
        reader.setContentHandler(this);
        reader.setDTDHandler(this);

        InputSource is = saxSource.getInputSource();
        reader.parse(is);
      } finally {
        // release the reference to user's handler ASAP
        setContentHandler(null);
      }
      return;
    }
    throw new IllegalArgumentException(
        JAXPValidationMessageFormatter.formatMessage(
            Locale.getDefault(),
            "SourceResultMismatch",
            new Object[] {source.getClass().getName(), result.getClass().getName()}));
  }
コード例 #19
0
ファイル: XMLSchemaFactory.java プロジェクト: ru-doc/java-sdk
  public Schema newSchema(Source[] schemas) throws SAXException {

    // this will let the loader store parsed Grammars into the pool.
    XMLGrammarPoolImplExtension pool = new XMLGrammarPoolImplExtension();
    fXMLGrammarPoolWrapper.setGrammarPool(pool);

    XMLInputSource[] xmlInputSources = new XMLInputSource[schemas.length];
    InputStream inputStream;
    Reader reader;
    for (int i = 0; i < schemas.length; i++) {
      Source source = schemas[i];
      if (source instanceof StreamSource) {
        StreamSource streamSource = (StreamSource) source;
        String publicId = streamSource.getPublicId();
        String systemId = streamSource.getSystemId();
        inputStream = streamSource.getInputStream();
        reader = streamSource.getReader();
        xmlInputSources[i] = new XMLInputSource(publicId, systemId, null);
        xmlInputSources[i].setByteStream(inputStream);
        xmlInputSources[i].setCharacterStream(reader);
      } else if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;
        InputSource inputSource = saxSource.getInputSource();
        if (inputSource == null) {
          throw new SAXException(
              JAXPValidationMessageFormatter.formatMessage(
                  Locale.getDefault(), "SAXSourceNullInputSource", null));
        }
        xmlInputSources[i] = new SAXInputSource(saxSource.getXMLReader(), inputSource);
      } else if (source instanceof DOMSource) {
        DOMSource domSource = (DOMSource) source;
        Node node = domSource.getNode();
        String systemID = domSource.getSystemId();
        xmlInputSources[i] = new DOMInputSource(node, systemID);
      } else if (source == null) {
        throw new NullPointerException(
            JAXPValidationMessageFormatter.formatMessage(
                Locale.getDefault(), "SchemaSourceArrayMemberNull", null));
      } else {
        throw new IllegalArgumentException(
            JAXPValidationMessageFormatter.formatMessage(
                Locale.getDefault(),
                "SchemaFactorySourceUnrecognized",
                new Object[] {source.getClass().getName()}));
      }
    }

    try {
      fXMLSchemaLoader.loadGrammar(xmlInputSources);
    } catch (XNIException e) {
      // this should have been reported to users already.
      throw Util.toSAXException(e);
    } catch (IOException e) {
      // this hasn't been reported, so do so now.
      SAXParseException se = new SAXParseException(e.getMessage(), null, e);
      fErrorHandler.error(se);
      throw se; // and we must throw it.
    }

    // Clear reference to grammar pool.
    fXMLGrammarPoolWrapper.setGrammarPool(null);

    // Select Schema implementation based on grammar count.
    final int grammarCount = pool.getGrammarCount();
    if (grammarCount > 1) {
      return new XMLSchema(new ReadOnlyGrammarPool(pool));
    } else if (grammarCount == 1) {
      Grammar[] grammars = pool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
      return new SimpleXMLSchema(grammars[0]);
    } else {
      return EmptyXMLSchema.getInstance();
    }
  }
コード例 #20
0
  /**
   * Get an instance of a DTM, loaded with the content from the specified source. If the unique flag
   * is true, a new instance will always be returned. Otherwise it is up to the DTMManager to return
   * a new instance or an instance that it already created and may be being used by someone else. (I
   * think more parameters will need to be added for error handling, and entity resolution).
   *
   * @param source the specification of the source object.
   * @param unique true if the returned DTM must be unique, probably because it is going to be
   *     mutated.
   * @param whiteSpaceFilter Enables filtering of whitespace nodes, and may be null.
   * @param incremental true if the DTM should be built incrementally, if possible.
   * @param doIndexing true if the caller considers it worth it to use indexing schemes.
   * @param hasUserReader true if <code>source</code> is a <code>SAXSource</code> object that has an
   *     <code>XMLReader</code>, that was specified by the user.
   * @param size Specifies initial size of tables that represent the DTM
   * @param buildIdIndex true if the id index table should be built.
   * @param newNameTable true if we want to use a separate ExpandedNameTable for this DTM.
   * @return a non-null DTM reference.
   */
  public DTM getDTM(
      Source source,
      boolean unique,
      DTMWSFilter whiteSpaceFilter,
      boolean incremental,
      boolean doIndexing,
      boolean hasUserReader,
      int size,
      boolean buildIdIndex,
      boolean newNameTable) {
    if (DEBUG && null != source) {
      System.out.println(
          "Starting " + (unique ? "UNIQUE" : "shared") + " source: " + source.getSystemId());
    }

    int dtmPos = getFirstFreeDTMID();
    int documentID = dtmPos << IDENT_DTM_NODE_BITS;

    if ((null != source) && source instanceof StAXSource) {
      final StAXSource staxSource = (StAXSource) source;
      StAXEvent2SAX staxevent2sax = null;
      StAXStream2SAX staxStream2SAX = null;
      if (staxSource.getXMLEventReader() != null) {
        final XMLEventReader xmlEventReader = staxSource.getXMLEventReader();
        staxevent2sax = new StAXEvent2SAX(xmlEventReader);
      } else if (staxSource.getXMLStreamReader() != null) {
        final XMLStreamReader xmlStreamReader = staxSource.getXMLStreamReader();
        staxStream2SAX = new StAXStream2SAX(xmlStreamReader);
      }

      SAXImpl dtm;

      if (size <= 0) {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                DTMDefaultBase.DEFAULT_BLOCKSIZE,
                buildIdIndex,
                newNameTable);
      } else {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                size,
                buildIdIndex,
                newNameTable);
      }

      dtm.setDocumentURI(source.getSystemId());

      addDTM(dtm, dtmPos, 0);

      try {
        if (staxevent2sax != null) {
          staxevent2sax.setContentHandler(dtm);
          staxevent2sax.parse();
        } else if (staxStream2SAX != null) {
          staxStream2SAX.setContentHandler(dtm);
          staxStream2SAX.parse();
        }

      } catch (RuntimeException re) {
        throw re;
      } catch (Exception e) {
        throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(e);
      }

      return dtm;
    } else if ((null != source) && source instanceof DOMSource) {
      final DOMSource domsrc = (DOMSource) source;
      final org.w3c.dom.Node node = domsrc.getNode();
      final DOM2SAX dom2sax = new DOM2SAX(node);

      SAXImpl dtm;

      if (size <= 0) {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                DTMDefaultBase.DEFAULT_BLOCKSIZE,
                buildIdIndex,
                newNameTable);
      } else {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                size,
                buildIdIndex,
                newNameTable);
      }

      dtm.setDocumentURI(source.getSystemId());

      addDTM(dtm, dtmPos, 0);

      dom2sax.setContentHandler(dtm);

      try {
        dom2sax.parse();
      } catch (RuntimeException re) {
        throw re;
      } catch (Exception e) {
        throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(e);
      }

      return dtm;
    } else {
      boolean isSAXSource = (null != source) ? (source instanceof SAXSource) : true;
      boolean isStreamSource = (null != source) ? (source instanceof StreamSource) : false;

      if (isSAXSource || isStreamSource) {
        XMLReader reader;
        InputSource xmlSource;

        if (null == source) {
          xmlSource = null;
          reader = null;
          hasUserReader = false; // Make sure the user didn't lie
        } else {
          reader = getXMLReader(source);
          xmlSource = SAXSource.sourceToInputSource(source);

          String urlOfSource = xmlSource.getSystemId();

          if (null != urlOfSource) {
            try {
              urlOfSource = SystemIDResolver.getAbsoluteURI(urlOfSource);
            } catch (Exception e) {
              // %REVIEW% Is there a better way to send a warning?
              System.err.println("Can not absolutize URL: " + urlOfSource);
            }

            xmlSource.setSystemId(urlOfSource);
          }
        }

        // Create the basic SAX2DTM.
        SAXImpl dtm;
        if (size <= 0) {
          dtm =
              new SAXImpl(
                  this,
                  source,
                  documentID,
                  whiteSpaceFilter,
                  null,
                  doIndexing,
                  DTMDefaultBase.DEFAULT_BLOCKSIZE,
                  buildIdIndex,
                  newNameTable);
        } else {
          dtm =
              new SAXImpl(
                  this,
                  source,
                  documentID,
                  whiteSpaceFilter,
                  null,
                  doIndexing,
                  size,
                  buildIdIndex,
                  newNameTable);
        }

        // Go ahead and add the DTM to the lookup table.  This needs to be
        // done before any parsing occurs. Note offset 0, since we've just
        // created a new DTM.
        addDTM(dtm, dtmPos, 0);

        if (null == reader) {
          // Then the user will construct it themselves.
          return dtm;
        }

        reader.setContentHandler(dtm.getBuilder());

        if (!hasUserReader || null == reader.getDTDHandler()) {
          reader.setDTDHandler(dtm);
        }

        if (!hasUserReader || null == reader.getErrorHandler()) {
          reader.setErrorHandler(dtm);
        }

        try {
          reader.setProperty("http://xml.org/sax/properties/lexical-handler", dtm);
        } catch (SAXNotRecognizedException e) {
        } catch (SAXNotSupportedException e) {
        }

        try {
          reader.parse(xmlSource);
        } catch (RuntimeException re) {
          throw re;
        } catch (Exception e) {
          throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(e);
        } finally {
          if (!hasUserReader) {
            releaseXMLReader(reader);
          }
        }

        if (DUMPTREE) {
          System.out.println("Dumping SAX2DOM");
          dtm.dumpDTM(System.err);
        }

        return dtm;
      } else {
        // It should have been handled by a derived class or the caller
        // made a mistake.
        throw new DTMException(
            XMLMessages.createXMLMessage(
                XMLErrorResources.ER_NOT_SUPPORTED, new Object[] {source}));
      }
    }
  }
コード例 #21
0
ファイル: DocumentSource.java プロジェクト: dom4j/dom4j
 /**
  * Sets the document used as the JAXP {@link SAXSource}
  *
  * @param document DOCUMENT ME!
  */
 public void setDocument(Document document) {
   super.setInputSource(new DocumentInputSource(document));
 }
コード例 #22
0
ファイル: Util.java プロジェクト: srnsw/xena
  /** Creates a SAX2 InputSource object from a TrAX Source object */
  public static InputSource getInputSource(XSLTC xsltc, Source source)
      throws TransformerConfigurationException {
    InputSource input = null;

    String systemId = source.getSystemId();

    try {
      // Try to get InputSource from SAXSource input
      if (source instanceof SAXSource) {
        final SAXSource sax = (SAXSource) source;
        input = sax.getInputSource();
        // Pass the SAX parser to the compiler
        try {
          XMLReader reader = sax.getXMLReader();

          /*
           * Fix for bug 24695
           * According to JAXP 1.2 specification if a SAXSource
           * is created using a SAX InputSource the Transformer or
           * TransformerFactory creates a reader via the
           * XMLReaderFactory if setXMLReader is not used
           */

          if (reader == null) {
            try {
              reader = XMLReaderFactory.createXMLReader();
            } catch (Exception e) {
              try {

                // Incase there is an exception thrown
                // resort to JAXP
                SAXParserFactory parserFactory = SAXParserFactory.newInstance();
                parserFactory.setNamespaceAware(true);

                if (xsltc.isSecureProcessing()) {
                  try {
                    parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                  } catch (org.xml.sax.SAXException se) {
                  }
                }

                reader = parserFactory.newSAXParser().getXMLReader();

              } catch (ParserConfigurationException pce) {
                throw new TransformerConfigurationException("ParserConfigurationException", pce);
              }
            }
          }
          reader.setFeature("http://xml.org/sax/features/namespaces", true);
          reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);

          xsltc.setXMLReader(reader);
        } catch (SAXNotRecognizedException snre) {
          throw new TransformerConfigurationException("SAXNotRecognizedException ", snre);
        } catch (SAXNotSupportedException snse) {
          throw new TransformerConfigurationException("SAXNotSupportedException ", snse);
        } catch (SAXException se) {
          throw new TransformerConfigurationException("SAXException ", se);
        }

      }
      // handle  DOMSource
      else if (source instanceof DOMSource) {
        final DOMSource domsrc = (DOMSource) source;
        final Document dom = (Document) domsrc.getNode();
        final DOM2SAX dom2sax = new DOM2SAX(dom);
        xsltc.setXMLReader(dom2sax);

        // Try to get SAX InputSource from DOM Source.
        input = SAXSource.sourceToInputSource(source);
        if (input == null) {
          input = new InputSource(domsrc.getSystemId());
        }
      }
      // Try to get InputStream or Reader from StreamSource
      else if (source instanceof StreamSource) {
        final StreamSource stream = (StreamSource) source;
        final InputStream istream = stream.getInputStream();
        final Reader reader = stream.getReader();
        xsltc.setXMLReader(null); // Clear old XML reader

        // Create InputSource from Reader or InputStream in Source
        if (istream != null) {
          input = new InputSource(istream);
        } else if (reader != null) {
          input = new InputSource(reader);
        } else {
          input = new InputSource(systemId);
        }
      } else {
        ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR);
        throw new TransformerConfigurationException(err.toString());
      }
      input.setSystemId(systemId);
    } catch (NullPointerException e) {
      ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR, "TransformerFactory.newTemplates()");
      throw new TransformerConfigurationException(err.toString());
    } catch (SecurityException e) {
      ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
      throw new TransformerConfigurationException(err.toString());
    }
    return input;
  }
コード例 #23
0
  protected Document getXmlDocument(final FacesContext context, UIComponent component, Object value)
      throws ParserConfigurationException, SAXException, IOException {
    if (value == null) {
      return null;
    }

    Document document;
    // First of all detect pre-built doms
    if (value instanceof Document) {
      document = (Document) value;
    } else if (value instanceof DOMSource) {
      final DOMSource source = (DOMSource) value;
      final DocumentBuilder builder = getDocumentBuilder();
      document = builder.newDocument();
      document.appendChild(source.getNode());
    } else if ((value instanceof InputSource) || (value instanceof SAXSource)) {
      InputSource inputSource;
      if (value instanceof SAXSource) {
        final SAXSource source = (SAXSource) value;
        inputSource = source.getInputSource();
      } else {
        inputSource = (InputSource) value;
      }
      final DocumentBuilder builder = getDocumentBuilder();
      document = builder.parse(inputSource);
    } else {
      InputStream stream = null;
      boolean closeStream = true;
      if (value instanceof StreamSource) {
        final StreamSource source = (StreamSource) value;
        stream = source.getInputStream();
      } else if (value instanceof File) {
        stream = new FileInputStream((File) value);
      } else if (value instanceof URL) {
        stream = ((URL) value).openStream();
      } else if (value instanceof String) {
        final JRFacesContext jrContext = JRFacesContext.getInstance(context);
        final Resource resource = jrContext.createResource(context, component, (String) value);
        stream = resource.getInputStream();
      } else if (value instanceof InputStream) {
        stream = (InputStream) value;
        closeStream = false;
      }

      if (stream == null) {
        throw new SourceException(
            "Unrecognized XML " + "value source type: " + value.getClass().getName());
      }

      try {
        final DocumentBuilder builder = getDocumentBuilder();
        document = builder.parse(stream);
      } finally {
        if (stream != null && closeStream) {
          try {
            stream.close();
          } catch (final IOException e) {;
          }
        }
        stream = null;
      }
    }

    return document;
  }
コード例 #24
0
ファイル: XsltBuilder.java プロジェクト: pax95/camel
 private void tryAddEntityResolver(SAXSource source) {
   // expecting source to have not null XMLReader
   if (this.entityResolver != null && source != null) {
     source.getXMLReader().setEntityResolver(this.entityResolver);
   }
 }