예제 #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
1
 private String getStringFromStreamSource(StreamSource src, int length) throws Exception {
   byte buf[] = null;
   if (src == null) return null;
   InputStream outStr = src.getInputStream();
   if (outStr != null) {
     int len = outStr.available();
     if (outStr.markSupported()) outStr.reset();
     buf = new byte[len];
     outStr.read(buf, 0, len);
     // System.out.println("From inputstream: "+new String(buf));
     return new String(buf);
   } else {
     char buf1[] = new char[length];
     Reader r = src.getReader();
     if (r == null) return null;
     r.reset();
     r.read(buf1);
     // System.out.println("From Reader: "+new String(buf));
     return new String(buf1);
   }
 }
예제 #3
0
  public void writeAsAttachment(Object obj, OutputStream out) throws IOException {
    try {
      if (obj instanceof StreamSource) {
        StreamSource source = (StreamSource) obj;
        InputSource inputSource = null;

        InputStream is = source.getInputStream();
        Reader reader = source.getReader();
        String systemId = source.getSystemId();

        if (is != null) inputSource = new InputSource(is);
        else if (reader != null) inputSource = new InputSource(reader);
        else if (systemId != null) inputSource = new InputSource(systemId);

        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setEntityResolver(_entityResolver);

        SAXSource saxSource = new SAXSource(xmlReader, inputSource);
        _transformer.transform(saxSource, new StreamResult(out));
      } else _transformer.transform((Source) obj, new StreamResult(out));
    } catch (TransformerException e) {
      IOException ioe = new IOException();
      ioe.initCause(e);

      throw ioe;
    } catch (SAXException saxe) {
      IOException ioe = new IOException();
      ioe.initCause(saxe);

      throw ioe;
    }
  }
예제 #4
0
 public <T> JAXBElement<T> unmarshal(Source source, Class<T> tClass) throws JAXBException {
   if (!(source instanceof StreamSource))
     throw new UnsupportedOperationException(Messages.MESSAGES.expectingStreamSource());
   StreamSource stream = (StreamSource) source;
   XMLStreamReader reader = getBadgerFishReader(new InputStreamReader(stream.getInputStream()));
   return unmarshal(reader, tClass);
 }
  /**
   * Apply an XSLT transform to the current XML object in this transaction.
   *
   * @throws IllegalStateException if the current root object is null
   * @throws PersistentObjectException if an error occurs
   * @throws TransformerException if the transformation fails
   */
  public void transform(Transformer transformer) throws TransformerException {

    // Sanity check
    if (this.current == null) throw new PersistentObjectException("no data to transform");

    // Debug
    // System.out.println("************************** BEFORE TRANSFORM");
    // System.out.println(this.current);

    // Set up source and result
    StreamSource source = new StreamSource(new StringReader(this.current));
    source.setSystemId(this.systemId);
    StringWriter buffer = new StringWriter(BUFFER_SIZE);
    StreamResult result = new StreamResult(buffer);
    result.setSystemId(this.systemId);

    // Apply transform
    transformer.transform(source, result);

    // Save result as the new current value
    this.current = buffer.toString();

    // Debug
    // System.out.println("************************** AFTER TRANSFORM");
    // System.out.println(this.current);
  }
  private static InputSource streamSourceToInputSource(StreamSource ss) {
    InputSource is = new InputSource();
    is.setSystemId(ss.getSystemId());
    is.setByteStream(ss.getInputStream());
    is.setCharacterStream(ss.getReader());

    return is;
  }
  /**
   * Returns a stream of XML markup.
   *
   * @return A stream of XML markup.
   * @throws IOException
   */
  public javax.xml.transform.stream.StreamSource getStreamSource() throws IOException {
    final javax.xml.transform.stream.StreamSource result =
        new javax.xml.transform.stream.StreamSource(getStream());

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

    return result;
  }
예제 #8
0
 @Override
 protected Object unmarshalStreamSource(StreamSource streamSource)
     throws XmlMappingException, IOException {
   if (streamSource.getInputStream() != null) {
     return unmarshalInputStream(streamSource.getInputStream());
   } else if (streamSource.getReader() != null) {
     return unmarshalReader(streamSource.getReader());
   } else {
     throw new IllegalArgumentException("StreamSource contains neither InputStream nor Reader");
   }
 }
예제 #9
0
 public DefaultJaxpStreamSource(Source source) {
   this.source = source;
   this.key = DefaultKey.newInstance();
   if (source instanceof javax.xml.transform.stream.StreamSource) {
     javax.xml.transform.stream.StreamSource stream =
         (javax.xml.transform.stream.StreamSource) source;
     this.systemId = stream.getSystemId() == null ? key.toString() : stream.getSystemId();
   } else {
     this.systemId = key.toString();
   }
   this.charset = null;
 }
예제 #10
0
 @Override
 public TypeDescriptor scanFile(Store store, StreamSource streamSource) throws IOException {
   DescriptorResolverFactory resolverFactory = new DescriptorResolverFactory(store);
   ClassVisitor visitor = new ClassVisitor(new VisitorHelper(store, resolverFactory));
   new ClassReader(streamSource.getInputStream()).accept(visitor, 0);
   TypeDescriptor typeDescriptor = visitor.getTypeDescriptor();
   scannedClasses++;
   return typeDescriptor;
 }
예제 #11
0
    public static void closeSource(final Source source) {
      if (!(source instanceof StreamSource)) {
        return;
      }

      StreamSource stream = (StreamSource) source;
      try {
        if (stream.getInputStream() != null) {
          stream.getInputStream().close();
        }
      } catch (IOException e) {
      }
      try {
        if (stream.getReader() != null) {
          stream.getReader().close();
        }
      } catch (IOException e) {
      }
    }
예제 #12
0
 public SourceDataSource(String name, String contentType, StreamSource data) {
   this.name = name;
   this.contentType = contentType == null ? CONTENT_TYPE : contentType;
   os = new ByteArrayOutputStream();
   try {
     if (data != null) {
       // Try the Reader first
       Reader reader = data.getReader();
       if (reader != null) {
         reader = new BufferedReader(reader);
         int ch;
         while ((ch = reader.read()) != -1) {
           os.write(ch);
         }
       } else {
         // Try the InputStream
         InputStream is = data.getInputStream();
         if (is == null) {
           // Try the URL
           String id = data.getSystemId();
           if (id != null) {
             URL url = new URL(id);
             is = url.openStream();
           }
         }
         if (is != null) {
           is = new BufferedInputStream(is);
           // If reading from a socket or URL, we could get a partial read.
           byte[] bytes = null;
           int avail;
           while ((avail = is.available()) > 0) {
             if (bytes == null || avail > bytes.length) bytes = new byte[avail];
             is.read(bytes, 0, avail);
             os.write(bytes, 0, avail);
           }
         }
       }
     }
   } catch (Exception e) {
     // Is this sufficient?
   }
 } // ctor
  /** Opens a path based on a Source. */
  ReadStream openPath(Source source) throws TransformerException, IOException {
    String systemId = source.getSystemId();

    Path path;
    if (systemId != null) path = getSearchPath().lookup(systemId);
    else path = getSearchPath().lookup("anonymous.xsl");

    if (source instanceof StreamSource) {
      StreamSource stream = (StreamSource) source;

      InputStream is = stream.getInputStream();

      if (is instanceof ReadStream) {
        ReadStream rs = (ReadStream) is;

        rs.setPath(path);

        return rs;
      } else if (is != null) {
        ReadStream rs = Vfs.openRead(is);
        rs.setPath(path);

        return rs;
      }

      Reader reader = stream.getReader();

      if (reader != null) {
        ReadStream rs = Vfs.openRead(reader);
        rs.setPath(path);

        return rs;
      }
    }

    if (systemId != null) return getSearchPath().lookup(systemId).openRead();

    throw new TransformerException("bad source " + source);
  }
예제 #14
0
  public String write(Object in) throws IOException, JAXBException {
    Source src = (Source) in;

    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();

      _transformer.transform(src, new StreamResult(out));

      return Base64.encodeFromByteArray(out.toByteArray());
    } catch (TransformerException e) {
      if (src instanceof StreamSource) {
        StreamSource ss = (StreamSource) src;

        InputStream is = ss.getInputStream();

        if (is != null) {
          ByteArrayOutputStream out = new ByteArrayOutputStream();

          for (int ch = is.read(); ch >= 0; ch = is.read()) out.write(ch);

          return Base64.encodeFromByteArray(out.toByteArray());
        }

        Reader reader = ss.getReader();

        if (reader != null) {
          CharArrayWriter out = new CharArrayWriter();

          for (int ch = reader.read(); ch >= 0; ch = reader.read()) out.write(ch);

          return Base64.encode(new String(out.toCharArray()));
        }
      }

      throw new JAXBException(e);
    }
  }
  public void writeDoc() throws Exception {

    if (!isReadOnly && !getValue("readOnly").equalsIgnoreCase("true")) {
      final InputStream stylesheet =
          this.getClass().getResourceAsStream("/org/jpedal/examples/viewer/res/xmlstyle.xslt");

      final StreamResult str = new StreamResult(configFile);
      final StreamSource ss = new StreamSource(stylesheet);
      final DOMSource dom = new DOMSource(doc);
      final TransformerFactory transformerFactory = TransformerFactory.newInstance();
      final Transformer transformer = transformerFactory.newTransformer(ss);
      transformer.transform(dom, str);

      stylesheet.close();
      if (ss != null) {
        ss.getInputStream().close();
      }

      // Prevents exception when viewer is closing.
      if (str != null && str.getOutputStream() != null) {
        str.getOutputStream().close();
      }
    }
  }
예제 #16
0
  /**
   * This method is responsible for saving a macro as an XML document. The document follows the
   * structure of the macro tree.
   */
  public static void saveMacro(final MacroDefinition macroDef, final String saveLocation)
      throws NullPointerException, IOException, ParserConfigurationException, DOMException,
          TransformerConfigurationException, TransformerException {

    MacroWriter.macro = macroDef;
    File macroFile = null;

    if (saveLocation.equals("")) {
      // test if macro save location exists
      File macroSaveLocation = new File(MacroManager.macroSaveLocation);
      if (!macroSaveLocation.exists()) macroSaveLocation.mkdir();

      String macroPath = MacroManager.macroSaveLocation + MacroWriter.macro.getName() + ".xml";
      macroFile = new File(macroPath);
    } else {
      macroFile = new File(saveLocation);
    }

    Document ptDOM = null;
    StreamSource xsltSource = null;
    Transformer transformer = null;

    try {
      // Build a PTML Document
      DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = builderFactory.newDocumentBuilder();
      ptDOM = builder.newDocument();

      // PTML Element
      Element ptmlElement = ptDOM.createElement("ptml");
      ptDOM.appendChild(ptmlElement);

      // Macro Element
      Element macroElement = ptDOM.createElement("macro");
      macroElement.setAttribute("name", MacroWriter.macro.getName());
      macroElement.setAttribute("description", MacroWriter.macro.getDescription());
      macroElement.setAttribute("returntype", MacroWriter.macro.getReturnType());
      ptmlElement.appendChild(macroElement);

      // put nodes into HashMap, so that we can check whether they have
      // been processed already
      // (in case of recursion when child nodes are processed)
      ArrayList<PerformanceTreeNode> nodesArray = MacroWriter.macro.getMacroNodes();
      Iterator<PerformanceTreeNode> i = nodesArray.iterator();
      while (i.hasNext()) {
        PerformanceTreeNode nodeNotProcessedYet = i.next();
        String nodeID = nodeNotProcessedYet.getId();
        MacroWriter.nodesProcessed.put(nodeID, "false");
      }

      // serialise node and their arcs
      i = nodesArray.iterator();
      while (i.hasNext()) {
        PerformanceTreeNode nodeToSerialise = i.next();
        String nodeToSerialiseID = nodeToSerialise.getId();
        boolean nodeProcessedAlready = false;
        if ((MacroWriter.nodesProcessed.get(nodeToSerialiseID)).equals("true")) {
          nodeProcessedAlready = true;
        } else if ((MacroWriter.nodesProcessed.get(nodeToSerialiseID)).equals("false")) {
          nodeProcessedAlready = false;
        }

        if (!nodeProcessedAlready)
          MacroWriter.createNodeElement(nodeToSerialise, macroElement, ptDOM);
      }

      // serialise state and action labels
      MacroWriter.serialiseStateAndActionLabels(macroElement, ptDOM);

      ptDOM.normalize();

      // Create Transformer with XSL Source File
      xsltSource =
          new StreamSource(
              Thread.currentThread()
                  .getContextClassLoader()
                  .getResourceAsStream(
                      "pipe"
                          + System.getProperty("file.separator")
                          + "modules"
                          + System.getProperty("file.separator")
                          + "queryeditor"
                          + System.getProperty("file.separator")
                          + "io"
                          + System.getProperty("file.separator")
                          + "WriteMacroXML.xsl"));
      transformer = TransformerFactory.newInstance().newTransformer(xsltSource);

      // Write file and do XSLT transformation to generate correct PTML
      File outputObjectArrayList = macroFile;
      DOMSource source = new DOMSource(ptDOM);
      StreamResult result = new StreamResult(outputObjectArrayList);
      transformer.transform(source, result);
    } catch (DOMException e) {
      System.out.println(
          "DOMException thrown in saveMacro()"
              + " : MacroWriter Class : modules.queryeditor.io Package"
              + " : filename=\""
              + macroFile.getCanonicalPath()
              + "\" xslt=\""
              + xsltSource.getSystemId()
              + "\" transformer=\""
              + transformer.getURIResolver()
              + "\"");
    } catch (ParserConfigurationException e) {
      System.out.println(
          "ParserConfigurationException thrown in saveMacro()"
              + " : MacroWriter Class : modules.queryeditor.io Package"
              + " : filename=\""
              + macroFile.getCanonicalPath()
              + "\" xslt=\""
              + "\" transformer=\""
              + "\"");
    } catch (TransformerConfigurationException e) {
      System.out.println(
          "TransformerConfigurationException thrown in saveMacro()"
              + " : MacroWriter Class : modules.queryeditor.io Package"
              + " : filename=\""
              + macroFile.getCanonicalPath()
              + "\" xslt=\""
              + xsltSource.getSystemId()
              + "\" transformer=\""
              + transformer.getURIResolver()
              + "\"");
    } catch (TransformerException e) {
      System.out.println(
          "TransformerException thrown in saveMacro()"
              + " : MacroWriter Class : modules.queryeditor.io Package"
              + " : filename=\""
              + macroFile.getCanonicalPath()
              + "\" xslt=\""
              + xsltSource.getSystemId()
              + "\" transformer=\""
              + transformer.getURIResolver()
              + "\"");
    }
  }
예제 #17
0
  /**
   * Creates a proper {@link XMLInputSource} from a {@link StreamSource}.
   *
   * @return always return non-null valid object.
   */
  public static final XMLInputSource toXMLInputSource(StreamSource in) {
    if (in.getReader() != null)
      return new XMLInputSource(
          in.getPublicId(), in.getSystemId(), in.getSystemId(), in.getReader(), null);
    if (in.getInputStream() != null)
      return new XMLInputSource(
          in.getPublicId(), in.getSystemId(), in.getSystemId(), in.getInputStream(), null);

    return new XMLInputSource(in.getPublicId(), in.getSystemId(), in.getSystemId());
  }
예제 #18
0
파일: Jelly.java 프로젝트: alwold/jelly
  public void doRequest(HttpServletRequest req, HttpServletResponse res, WebUser user)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    Document doc = null;
    try {
      doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException pce) {
      out.println("Parser Configuration Exception: " + pce.getMessage());
      out.println("<!--");
      pce.printStackTrace(out);
      out.println("-->");
    }

    // Make sure this person is authorized
    if (!Util.isAuthorized(user.getUserID())) {
      res.setContentType("text/html");
      out.println("<title>JELlY</title>");
      out.println(
          "You are not authorized to use Jelly.  Please talk to Brian Samson if"
              + "you believe this message is in error");
      return;
    }

    if (req.getParameter("action") == null) {
      // main page, show list of modules
      Element projects = doc.createElement("projects");
      List projectList = Configuration.getInstance().getJellyConfiguration().getProject();
      for (Iterator i = projectList.iterator(); i.hasNext(); ) {
        ProjectType project = (ProjectType) i.next();
        Element projectElement = doc.createElement("project");
        projectElement.setAttribute("name", project.getName());
        projects.appendChild(projectElement);
      }
      doc.appendChild(projects);
    } else if (req.getParameter("action").equals("selectproject")) {
      String project = req.getParameter("project");
      Element optionsPage = doc.createElement("optionsPage");
      Element projectElement = doc.createElement("project");
      projectElement.setAttribute("name", project);
      optionsPage.appendChild(projectElement);

      ServiceFactory serviceFactory = ServiceFactory.getInstance();

      ISource source = serviceFactory.getSource(project);
      Element sourceElement = doc.createElement("source");
      sourceElement.setAttribute("class", source.getClass().getName());
      sourceElement.appendChild(getOptions(source, project, doc));
      optionsPage.appendChild(sourceElement);

      IBuilder builder = serviceFactory.getBuilder(project);
      Element builderElement = doc.createElement("builder");
      builderElement.setAttribute("class", builder.getClass().getName());
      builderElement.appendChild(getOptions(builder, project, doc));
      optionsPage.appendChild(builderElement);

      IDeployer deployer = serviceFactory.getDeployer(project);
      Element deployerElement = doc.createElement("deployer");
      deployerElement.setAttribute("class", deployer.getClass().getName());
      deployerElement.appendChild(getOptions(deployer, project, doc));
      optionsPage.appendChild(deployerElement);

      doc.appendChild(optionsPage);
    } else if (req.getParameter("action").equals("go")) {
      String project = req.getParameter("project");
      ServiceFactory serviceFactory = ServiceFactory.getInstance();

      String sourceDir = "/tmp/jelly." + project + "/src";
      String destDir = "/tmp/jelly." + project + "/dest";

      try {
        Element go = doc.createElement("go");

        ISource source = serviceFactory.getSource(project);
        Map options = getOptions("source", req);
        source.retrieveSource(project, sourceDir, options);

        IBuilder builder = serviceFactory.getBuilder(project);
        options = getOptions("builder", req);
        String buildOutput =
            builder.build(project, sourceDir + File.separator + project, destDir, options);
        Element build = doc.createElement("build");
        build.appendChild(doc.createTextNode(buildOutput));
        go.appendChild(build);

        IDeployer deployer = serviceFactory.getDeployer(project);
        options = getOptions("deployer", req);
        deployer.deploy(destDir, IDeployer.ENV_QA);

        doc.appendChild(go);
      } catch (SourceException e) {
        Element error = doc.createElement("error");
        error.setAttribute("message", e.getMessage());
        doc.appendChild(error);
      }
    }

    try {
      URL url = this.getClass().getResource("/edu/asu/wmac/jelly/servlets/jelly.xsl");
      StreamSource stylesheet = new StreamSource(url.openConnection().getInputStream());
      stylesheet.setSystemId(url.toString());
      Transformer trans = TransformerFactory.newInstance().newTransformer(stylesheet);
      trans.setParameter("requestURL", req.getRequestURI());
      trans.transform(new DOMSource(doc), new StreamResult(out));
    } catch (TransformerException tce) {
      out.println("Transformer exception: " + tce.getMessage());
      out.println("<!--");
      tce.printStackTrace(out);
      out.println("-->");
    }
  }
  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;
  }
예제 #20
0
  public void validate(Source source, Result result) throws SAXException, IOException {
    if (result instanceof StreamResult || result == null) {
      final StreamSource streamSource = (StreamSource) source;
      final StreamResult streamResult = (StreamResult) result;
      XMLInputSource input =
          new XMLInputSource(streamSource.getPublicId(), streamSource.getSystemId(), null);
      input.setByteStream(streamSource.getInputStream());
      input.setCharacterStream(streamSource.getReader());

      // Gets the parser configuration. We'll create and initialize a new one, if we
      // haven't created one before or if the previous one was garbage collected.
      boolean newConfig = false;
      XMLParserConfiguration config = (XMLParserConfiguration) fConfiguration.get();
      if (config == null) {
        config = initialize();
        newConfig = true;
      }
      // If settings have changed on the component manager, refresh the error handler and entity
      // resolver.
      else if (fComponentManager.getFeature(PARSER_SETTINGS)) {
        config.setProperty(ENTITY_RESOLVER, fComponentManager.getProperty(ENTITY_RESOLVER));
        config.setProperty(ERROR_HANDLER, fComponentManager.getProperty(ERROR_HANDLER));
        config.setProperty(SECURITY_MANAGER, fComponentManager.getProperty(SECURITY_MANAGER));
      }

      // prepare for parse
      fComponentManager.reset();

      if (streamResult != null) {
        if (fSerializerFactory == null) {
          fSerializerFactory = SerializerFactory.getSerializerFactory(Method.XML);
        }

        // there doesn't seem to be a way to reset a serializer, so we need to make
        // a new one each time.
        Serializer ser;
        if (streamResult.getWriter() != null) {
          ser = fSerializerFactory.makeSerializer(streamResult.getWriter(), new OutputFormat());
        } else if (streamResult.getOutputStream() != null) {
          ser =
              fSerializerFactory.makeSerializer(streamResult.getOutputStream(), new OutputFormat());
        } else if (streamResult.getSystemId() != null) {
          String uri = streamResult.getSystemId();
          OutputStream out = XMLEntityManager.createOutputStream(uri);
          ser = fSerializerFactory.makeSerializer(out, new OutputFormat());
        } else {
          throw new IllegalArgumentException(
              JAXPValidationMessageFormatter.formatMessage(
                  fComponentManager.getLocale(), "StreamResultNotInitialized", null));
        }

        // we're using the parser only as an XNI-to-SAX converter,
        // so that we can use the SAX-based serializer
        SAXParser parser = (SAXParser) fParser.get();
        if (newConfig || parser == null) {
          parser = new SAXParser(config);
          fParser = new SoftReference(parser);
        } else {
          parser.reset();
        }
        config.setDocumentHandler(fSchemaValidator);
        fSchemaValidator.setDocumentHandler(parser);
        parser.setContentHandler(ser.asContentHandler());
      } else {
        fSchemaValidator.setDocumentHandler(null);
      }

      try {
        config.parse(input);
      } catch (XMLParseException e) {
        throw Util.toSAXParseException(e);
      } catch (XNIException e) {
        throw Util.toSAXException(e);
      } finally {
        // release the references to the SAXParser and Serializer
        fSchemaValidator.setDocumentHandler(null);
      }

      return;
    }
    throw new IllegalArgumentException(
        JAXPValidationMessageFormatter.formatMessage(
            fComponentManager.getLocale(),
            "SourceResultMismatch",
            new Object[] {source.getClass().getName(), result.getClass().getName()}));
  }
예제 #21
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;
  }
예제 #22
0
  private void validateSignature(SOAPMessage soapMessage) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    SOAPPart soapPart = soapMessage.getSOAPPart();
    Source source = null;
    try {

      source = soapPart.getContent();
    } catch (Exception e) {
    }

    Node root = null;
    Document doc = null;
    DocumentBuilder db = null;
    if (source instanceof DOMSource) {
      root = ((DOMSource) source).getNode();
      if (root instanceof Document) {
        doc = (Document) root;
      }
    } else if (source instanceof SAXSource) {
      InputSource inSource = ((SAXSource) source).getInputSource();
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      db = dbf.newDocumentBuilder();
      doc = db.parse(inSource);
      root = (Node) doc.getDocumentElement();
    } else { // if (source instanceof JAXMStreamSource){
      StreamSource streamSource = (StreamSource) source;
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      db = dbf.newDocumentBuilder();
      doc = db.parse(streamSource.getInputStream());
      root = (Node) doc.getDocumentElement();
      root = root.getParentNode();
    }
    /////////////////////////////////////////////
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
      throw new Exception("Cannot find Signature element");
      // System.out.println("Cannot find Signature element");
    }

    KeyValueKeySelector kvks = new KeyValueKeySelector();
    DOMValidateContext valContext =
        new DOMValidateContext(kvks, nl.item(0)); // (LoadPublicKey("", "RSA"),nl.item(0));
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
    XMLSignature signature = factory.unmarshalXMLSignature(valContext);
    if (signature.validate(valContext)) valid = 1;
    else valid = 0;
    if (DEBUG_) System.out.println("WSupdate:HS: valid=" + valid);
    try {
      md.update(signature.getKeySelectorResult().getKey().getEncoded());
      String PK_WS = getHexString(md.digest());
      if (PK_WS.equals(PK_Hex)) valid = 1;
      else valid = 0;
      if (DEBUG_)
        System.out.println(
            "Signature validation by comparing URL digest PK and empadded PK (1 or 0) " + valid);
      if (DEBUG_) System.out.println("Public Key from SOAP: " + PK_WS);
      md.reset();
      if (DEBUG_) System.out.println("Public Key from DB: " + PK_Hex);
      // md.update(LoadPublicKey("", "RSA").getEncoded());
      // System.out.println("Public Key from File: " + getHexString(md.digest()));
    } catch (Exception e) {
      System.out.print(e);
    }

    //  PublicKey pub = keypair.getPublic();

    /////////////////////////////////////////////
    //		Element envelope = getFirstChildElement(root);
    //        Element header = getFirstChildElement(envelope);
    //		Element sigElement = getFirstChildElement(header);
    //        DOMValidateContext valContext = new DOMValidateContext(LoadPublicKey("","RSA"),
    // sigElement);
    //        valContext.setIdAttributeNS(getNextSiblingElement(header),
    //        "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
    //  if(sig.validate(valContext)) valid=1 ; else valid=0;

    ////////////////////////////////////////////

  }
예제 #23
0
  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();
    }
  }
예제 #24
0
  /**
   * @throws org.exist.xquery.XPathException
   * @see BasicFunction#eval(Sequence[], Sequence)
   */
  public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    // Check input parameters
    if (args.length != 2) {
      return Sequence.EMPTY_SEQUENCE;
    }

    ValidationReport report = new ValidationReport();
    StreamSource instance = null;
    StreamSource grammars[] = null;

    try {
      report.start();

      // Get inputstream for instance document
      instance = Shared.getStreamSource(args[0].itemAt(0), context);

      // Validate using resource speciefied in second parameter
      grammars = Shared.getStreamSource(args[1], context);

      for (StreamSource grammar : grammars) {
        String grammarUrl = grammar.getSystemId();
        if (grammarUrl != null && !grammarUrl.endsWith(".xsd")) {
          throw new XPathException("Only XML schemas (.xsd) are supported.");
        }
      }

      // Prepare
      String schemaLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
      SchemaFactory factory = SchemaFactory.newInstance(schemaLang);

      // Create grammar
      Schema schema = factory.newSchema(grammars);

      // Setup validator
      Validator validator = schema.newValidator();
      validator.setErrorHandler(report);

      // Perform validation
      validator.validate(instance);

    } catch (MalformedURLException ex) {
      LOG.error(ex.getMessage());
      report.setException(ex);

    } catch (ExistIOException ex) {
      LOG.error(ex.getCause());
      report.setException(ex);

    } catch (Throwable ex) {
      LOG.error(ex);
      report.setException(ex);

    } finally {
      report.stop();

      Shared.closeStreamSource(instance);
      Shared.closeStreamSources(grammars);
    }

    // Create response
    if (isCalledAs("jaxv")) {
      Sequence result = new ValueSequence();
      result.add(new BooleanValue(report.isValid()));
      return result;

    } else /* isCalledAs("jaxv-report") */ {
      MemTreeBuilder builder = context.getDocumentBuilder();
      NodeImpl result = Shared.writeReport(report, builder);
      return result;
    }
  }
예제 #25
0
  private Map getPropertiesFromJSON() throws JAXBException {
    Map props = new HashMap(getProperties());

    if (props != null) {

      Object bindingFilesObject = props.get(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY);
      if (bindingFilesObject != null) {
        JAXBContext jaxbContext = CompilerHelper.getXmlBindingsModelContext();
        // unmarshal XML
        Unmarshaller u = jaxbContext.createUnmarshaller();
        Marshaller jsonMarshaller = jaxbContext.createMarshaller();
        // Marshal bindings to JSON (with no root)
        jsonMarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        jsonMarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
        if (bindingFilesObject instanceof Map) {
          Map<String, Object> bindingFiles = (Map<String, Object>) bindingFilesObject;

          Iterator<String> keyIter = bindingFiles.keySet().iterator();
          while (keyIter.hasNext()) {
            String nextKey = keyIter.next();
            Object nextBindings = bindingFiles.get(nextKey);
            ;
            if (nextBindings instanceof List) {
              List nextList = (List) bindingFiles.get(nextKey);
              for (int i = 0; i < nextList.size(); i++) {
                Object o = nextList.get(i);
                if (o instanceof Source) {
                  Source nextSource = (Source) o;
                  if (nextSource instanceof StreamSource) {
                    StreamSource ss = (StreamSource) nextSource;
                    StreamSource ss2 = new StreamSource(ss.getInputStream());
                    Object unmarshalledFromXML = u.unmarshal(ss2);
                    StringWriter sw = new StringWriter();
                    StreamResult newResult = new StreamResult(sw);
                    jsonMarshaller.marshal(unmarshalledFromXML, newResult);
                    StreamSource newSource = new StreamSource(new StringReader(sw.toString()));
                    nextList.set(i, newSource);
                  }
                }
              }
            } else if (nextBindings instanceof Source) {
              Object unmarshalledFromXML = u.unmarshal((Source) nextBindings);

              StringWriter sw = new StringWriter();
              StreamResult newResult = new StreamResult(sw);
              jsonMarshaller.marshal(unmarshalledFromXML, newResult);
              StreamSource newSource = new StreamSource(new StringReader(sw.toString()));
              bindingFiles.put(nextKey, newSource);
            }
          }
        } else if (bindingFilesObject instanceof List) {
          List bindingFilesList = (List) bindingFilesObject;
          for (int i = 0; i < bindingFilesList.size(); i++) {
            Object next = bindingFilesList.get(i);
            Object unmarshalledFromXML = getXmlBindings(next);
            StringWriter sw = new StringWriter();
            StreamResult newResult = new StreamResult(sw);
            jsonMarshaller.marshal(unmarshalledFromXML, newResult);
            StreamSource newSource = new StreamSource(new StringReader(sw.toString()));
            bindingFilesList.set(i, newSource);
          }
          props.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, bindingFilesList);
        } else {
          Object unmarshalledFromXML = getXmlBindings(bindingFilesObject);
          StringWriter sw = new StringWriter();
          StreamResult newResult = new StreamResult(sw);
          jsonMarshaller.marshal(unmarshalledFromXML, newResult);
          StreamSource newSource = new StreamSource(new StringReader(sw.toString()));
          props.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, newSource);
        }
      }
    }
    return props;
  }
예제 #26
0
  public void apply(File xmlSourceDirectory, File targetDirectory, DocErrorReporter reporter)
      throws DocTransletException {

    PrintStream err = System.err;

    try {
      URL mainResourceURL =
          classLoader == null
              ? ClassLoader.getSystemResource(mainResourceFilename)
              : classLoader.getResource(mainResourceFilename);

      if (null == mainResourceURL) {
        throw new DocTransletException("Cannot find resource '" + mainResourceFilename + "'");
      }

      Map parameters = new HashMap();
      parameters.put("gjdoc.xmldoclet.version", Driver.XMLDOCLET_VERSION);

      parameters.put("gjdoc.option.nonavbar", xsltBoolean(options.nonavbar));
      parameters.put("gjdoc.option.noindex", xsltBoolean(options.noindex));
      parameters.put("gjdoc.option.notree", xsltBoolean(options.notree));
      parameters.put("gjdoc.option.nocomment", xsltBoolean(options.nocomment));
      parameters.put("gjdoc.option.nohelp", xsltBoolean(options.nohelp));
      parameters.put("gjdoc.option.splitindex", xsltBoolean(options.splitindex));
      parameters.put("gjdoc.option.linksource", xsltBoolean(options.linksource));
      parameters.put("gjdoc.option.nodeprecatedlist", xsltBoolean(options.nodeprecatedlist));
      parameters.put("gjdoc.option.uses", xsltBoolean(options.uses));
      parameters.put("gjdoc.option.windowtitle", options.windowtitle);
      parameters.put("gjdoc.option.helpfile", options.helpfile);
      parameters.put("gjdoc.option.stylesheetfile", options.stylesheetfile);
      parameters.put("gjdoc.option.header", options.header);
      parameters.put("gjdoc.option.footer", options.footer);
      parameters.put("gjdoc.option.bottom", options.bottom);
      parameters.put("gjdoc.option.doctitle", options.doctitle);

      List outputFileList = getOutputFileList(mainResourceURL, xmlSourceDirectory, parameters);

      reporter.printNotice("Running DocTranslet...");

      TransformerFactory transformerFactory = TransformerFactory.newInstance();

      transformerFactory.setErrorListener(this);

      boolean isLibxmlJ =
          transformerFactory
              .getClass()
              .getName()
              .equals("gnu.xml.libxmlj.transform.TransformerFactoryImpl");

      for (Iterator it = outputFileList.iterator(); it.hasNext(); ) {

        if (isLibxmlJ) {
          System.gc();
          Runtime.getRuntime().runFinalization();
        }

        OutputFileInfo fileInfo = (OutputFileInfo) it.next();

        File targetFile = new File(targetDirectory, fileInfo.getName());
        File packageTargetDir = getParentFile(targetFile);

        if (!packageTargetDir.exists() && !packageTargetDir.mkdirs()) {
          throw new DocTransletException(
              "Target directory " + packageTargetDir + " does not exist and cannot be created.");
        }

        if (options.linksource) {
          File sourceTargetDirectory = new File(targetDirectory, "src-html");
          File sourceTargetFile = new File(sourceTargetDirectory, fileInfo.getName());
          File sourcePackageTargetDir = getParentFile(sourceTargetFile);

          if (!sourcePackageTargetDir.exists() && !sourcePackageTargetDir.mkdirs()) {
            throw new DocTransletException(
                "Target directory " + packageTargetDir + " does not exist and cannot be created.");
          }
        }

        if (options.uses) {
          File usesTargetDirectory = new File(targetDirectory, "class-use");
          File usesTargetFile = new File(usesTargetDirectory, fileInfo.getName());
          File usesPackageTargetDir = getParentFile(usesTargetFile);

          if (!usesPackageTargetDir.exists() && !usesPackageTargetDir.mkdirs()) {
            throw new DocTransletException(
                "Target directory " + packageTargetDir + " does not exist and cannot be created.");
          }
        }

        if (null != fileInfo.getSource()) {

          reporter.printNotice("Copying " + fileInfo.getComment() + "...");
          InputStream in = new URL(mainResourceURL, fileInfo.getSource()).openStream();
          FileOutputStream out = new FileOutputStream(targetFile.getAbsolutePath());
          IOToolkit.copyStream(in, out);
          in.close();
          out.close();
        } else {

          reporter.printNotice("Generating " + fileInfo.getComment() + "...");

          String pathToRoot = "";
          for (File file = getParentFile(targetFile);
              !equalsFile(file, targetDirectory);
              file = getParentFile(file)) {
            pathToRoot += "../";
          }

          StreamResult out = new StreamResult(targetFile.getAbsolutePath());

          StreamSource in =
              new StreamSource(new File(xmlSourceDirectory, "index.xml").getAbsolutePath());
          URL resource = new URL(mainResourceURL, fileInfo.getSheet());

          StreamSource xsltSource = new StreamSource(resource.toExternalForm());

          if (null != fileInfo.getInfo()) {
            parameters.put("gjdoc.outputfile.info", fileInfo.getInfo());
          }
          parameters.put("gjdoc.pathtoroot", pathToRoot);

          Transformer transformer;
          transformer = (Transformer) transformerMap.get(xsltSource.getSystemId());
          if (null == transformer) {
            transformer = transformerFactory.newTransformer(xsltSource);
            if (cacheXSLTSheets) {
              transformerMap.put(xsltSource.getSystemId(), transformer);
            }
          }

          transformer.clearParameters();
          for (Iterator pit = parameters.keySet().iterator(); pit.hasNext(); ) {
            String key = (String) pit.next();
            String value = (String) parameters.get(key);
            transformer.setParameter(key, value);
          }

          transformer.setErrorListener(this);
          DocErrorReporterOutputStream errorReporterOut =
              new DocErrorReporterOutputStream(reporter);
          System.setErr(new PrintStream(errorReporterOut));

          transformer.transform(in, out);
          errorReporterOut.flush();
        }
      }
    } catch (MalformedURLException e) {
      throw new DocTransletException(e);
    } catch (TransformerFactoryConfigurationError e) {
      throw new DocTransletException(e);
    } catch (TransformerException e) {
      throw new DocTransletException(e.getMessageAndLocation(), e);
    } catch (IOException e) {
      throw new DocTransletException(e);
    } finally {
      System.setErr(err);
    }
  }