@Test
 public void buildARecordTest()
     throws SOAPException, IOException, SAXException, ParserConfigurationException,
         TransformerException {
   MessageFactory factory = MessageFactory.newInstance();
   SOAPMessage request = factory.createMessage();
   SOAPPart part = request.getSOAPPart();
   DOMSource domSource =
       new DOMSource(getDocumentBuilder().parse(new InputSource(new StringReader(REQUEST_MSG))));
   part.setContent(domSource);
   Dispatch<SOAPMessage> dispatch =
       testService.createDispatch(portQName, SOAPMessage.class, Service.Mode.MESSAGE);
   SOAPMessage response = null;
   try {
     response = dispatch.invoke(request);
   } catch (Exception e) {
     e.printStackTrace();
   }
   if (response != null) {
     Source src = response.getSOAPPart().getContent();
     DOMResult result = new DOMResult();
     getTransformer().transform(src, result);
     Document resultDoc = (Document) result.getNode();
     Document controlDoc = xmlParser.parse(new StringReader(TEST_RESPONSE));
     assertTrue(
         "control document not same as instance document",
         comparer.isNodeEqual(controlDoc, resultDoc));
   }
 }
Ejemplo n.º 2
0
 /**
  * Processes MathML data.
  *
  * @param element MathML data element
  * @param block parent block
  * @throws DocumentException if some error occurs
  */
 private void processMath(Element element, Block<Atom> block) throws DocumentException {
   try {
     element.setAttribute("xmlns:m", URI_M);
     element.setAttribute("xmlns:w", URI_W);
     ByteArrayOutputStream omml = new ByteArrayOutputStream();
     DomUtil.save(element, omml);
     Source xsl = new StreamSource(getClass().getResourceAsStream(XSL_OMML2MML));
     Source xml = new StreamSource(new ByteArrayInputStream(omml.toByteArray()));
     DOMResult mml = new DOMResult();
     XslUtil.transform(xml, xsl, mml);
     LayoutContextImpl context =
         new LayoutContextImpl(LayoutContextImpl.getDefaultLayoutContext());
     Float fontSize = (Float) context.getParameter(Parameter.MATHSIZE);
     final float factor = 1.5F;
     context.setParameter(Parameter.MATHSIZE, factor * fontSize);
     context.setParameter(Parameter.MFRAC_KEEP_SCRIPTLEVEL, Boolean.FALSE);
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     ConverterRegistry.getInstance()
         .getConverter("image/png")
         .convert(mml.getNode(), context, out);
     Image image = new Image();
     mathImageIndex++;
     final String imageName = "mml-" + mathImageIndex + ".png";
     image.setUrl(imageName);
     image.setAlt(imageName);
     image.setData(out.toByteArray());
     block.add(image);
   } catch (XmlException e) {
     throw new DocumentException(e);
   } catch (IOException e) {
     throw new DocumentException(e);
   }
 }
Ejemplo n.º 3
0
  // TODO - change the return type and the factory parameter to be Definitions and ObjectFactory,
  // and move to bpmn-schema
  public BpmnDefinitions correctFlowNodeRefs(
      final BpmnDefinitions definitions, final BpmnObjectFactory factory)
      throws JAXBException, TransformerException {

    JAXBContext context =
        JAXBContext.newInstance(
            factory.getClass(),
            com.processconfiguration.ObjectFactory.class,
            org.omg.spec.bpmn._20100524.di.ObjectFactory.class,
            org.omg.spec.bpmn._20100524.model.ObjectFactory.class,
            org.omg.spec.dd._20100524.dc.ObjectFactory.class,
            org.omg.spec.dd._20100524.di.ObjectFactory.class,
            com.signavio.ObjectFactory.class);

    // Marshal the BPMN into a DOM tree
    DOMResult intermediateResult = new DOMResult();
    Marshaller marshaller = context.createMarshaller();
    marshaller.marshal(factory.createDefinitions(definitions), intermediateResult);

    // Apply the XSLT transformation, generating a new DOM tree
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer =
        transformerFactory.newTransformer(
            new StreamSource(
                getClass().getClassLoader().getResourceAsStream("xsd/fix-flowNodeRef.xsl")));
    DOMSource finalSource = new DOMSource(intermediateResult.getNode());
    DOMResult finalResult = new DOMResult();
    transformer.transform(finalSource, finalResult);

    // Unmarshal back to JAXB
    Object def2 = context.createUnmarshaller().unmarshal(finalResult.getNode());
    return ((JAXBElement<BpmnDefinitions>) def2).getValue();
  }
Ejemplo n.º 4
0
  /**
   * Serialize this instance to a steam.
   *
   * <p>Default deserialization is pretty-printed but not schema-validated.
   *
   * @param out the stream for writing
   * @param validate whether to perform schema validation
   * @throws JAXBException if the steam can't be written to
   */
  public void marshal(final OutputStream out, final Boolean validate) throws JAXBException {
    try {
      // Create an empty DOM
      DOMResult intermediateResult = new DOMResult();

      // Marshal from JAXB to DOM
      Marshaller marshaller = /*BPMN_CONTEXT*/ newContext().createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      if (validate) {
        marshaller.setSchema(getBpmnSchema() /*BPMN_SCHEMA*/);
      }
      marshaller.marshal(new BpmnObjectFactory().createDefinitions(this), intermediateResult);

      // Apply the XSLT transformation, from DOM to the output stream
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer =
          transformerFactory.newTransformer(
              new StreamSource(
                  new java.io.StringBufferInputStream(
                      fixNamespacesXslt[0] + getTargetNamespace() + fixNamespacesXslt[1])));
      DOMSource finalSource = new DOMSource(intermediateResult.getNode());
      StreamResult finalResult = new StreamResult(out);
      transformer.transform(finalSource, finalResult);
    } catch (TransformerException e) {
      throw new JAXBException("Dodgy wrapped exception", e);
    } // TODO - create transformer elsewhere
  }
  @Override
  public boolean handleMessage(LogicalMessageContext logicalMessageContext) {
    try {
      boolean outboundMessage =
          (boolean) logicalMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

      if (!outboundMessage) {
        return true;
      }

      LogicalMessage logicalMessage = logicalMessageContext.getMessage();

      Transformer transformer =
          _transformerFactory.newTransformer(new StreamSource(_url.openStream()));

      DOMResult domResult = new DOMResult();

      transformer.transform(logicalMessage.getPayload(), domResult);

      logicalMessage.setPayload(new DOMSource(domResult.getNode()));

      return true;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 protected Document wbxmlStream2Doc(InputStream in, boolean event) throws Exception {
   XMLStreamReader xmlStreamReader = null;
   XMLEventReader xmlEventReader = null;
   try {
     if (event) {
       xmlEventReader = inFact.createXMLEventReader(in);
     } else {
       xmlStreamReader = inFact.createXMLStreamReader(in);
     }
     Transformer xformer = TransformerFactory.newInstance().newTransformer();
     StAXSource staxSource =
         event ? new StAXSource(xmlEventReader) : new StAXSource(xmlStreamReader);
     DOMResult domResult = new DOMResult();
     xformer.transform(staxSource, domResult);
     Document doc = (Document) domResult.getNode();
     doc.normalize();
     return doc;
   } finally {
     if (xmlStreamReader != null) {
       try {
         xmlStreamReader.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventReader != null) {
       try {
         xmlEventReader.close();
       } catch (Exception e) {
       }
     }
   }
 }
 public boolean handleMessage(LogicalMessageContext messageContext) {
   Boolean outbound = (Boolean) messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
   if (!outbound) {
     try {
       LogicalMessage msg = messageContext.getMessage();
       Source inhoud = msg.getPayload();
       TransformerFactory factory = TransformerFactory.newInstance();
       Transformer tf =
           factory.newTransformer(
               new StreamSource(
                   this.getClass().getClassLoader().getResourceAsStream("ws/nieuweversie.xsl")));
       DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
       DocumentBuilder builder = dFactory.newDocumentBuilder();
       Document document = builder.newDocument();
       DOMResult aangepast = new DOMResult(document);
       tf.transform(inhoud, aangepast);
       msg.setPayload(new DOMSource(aangepast.getNode()));
     } catch (TransformerConfigurationException | ParserConfigurationException ex) {
       Logger.getLogger(EquationServiceLogicalHandler.class.getName()).log(Level.SEVERE, null, ex);
     } catch (TransformerException ex) {
       Logger.getLogger(EquationServiceLogicalHandler.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
   return true;
 }
Ejemplo n.º 8
0
 private static Document copyDoc(Document doc) throws TransformerException {
   TransformerFactory tfactory = TransformerFactory.newInstance();
   Transformer tx = tfactory.newTransformer();
   DOMSource source = new DOMSource(doc);
   DOMResult result = new DOMResult();
   tx.transform(source, result);
   return (Document) result.getNode();
 }
Ejemplo n.º 9
0
 private DOMSource toDOMSource(Source source) throws Exception {
   if (source instanceof DOMSource) {
     return (DOMSource) source;
   }
   Transformer trans = TransformerFactory.newInstance().newTransformer();
   DOMResult result = new DOMResult();
   trans.transform(source, result);
   return new DOMSource(result.getNode());
 }
 protected Document object2Doc(Object o) throws Exception {
   if (jc == null) {
     jc = JAXBContext.newInstance(o.getClass());
   }
   Marshaller marshaller = jc.createMarshaller();
   DOMResult res = new DOMResult();
   marshaller.marshal(o, res);
   return (Document) res.getNode();
 }
  public static void main(String[] args) {
    long startTime = System.currentTimeMillis();

    ODTXHTMLConverter converter = ODTXHTMLConverter.getInstance();

    IEntryInputStreamProvider inProvider =
        new IEntryInputStreamProvider() {

          public InputStream getEntryInputStream(String entryName) {
            if (entryName.equals("content.xml")) {
              return HelloWorldODT2XHTMLTest.class.getResourceAsStream("HelloWorld.content.xml");
            }
            if (entryName.equals("styles.xml")) {
              return HelloWorldODT2XHTMLTest.class.getResourceAsStream("HelloWorld.styles.xml");
            }
            if (entryName.equals("meta.xml")) {
              return HelloWorldODT2XHTMLTest.class.getResourceAsStream("HelloWorld.meta.xml");
            }
            return null;
          }
        };

    // OutputStream outputStream = new StringBuilderOutputStream();
    DOMResult result = new DOMResult();
    try {
      converter.convert2XHTML(inProvider, result, null);
      System.err.println(XMLUtils.toString(result.getNode()));
    } catch (XDocConverterException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    System.out.println(System.currentTimeMillis() - startTime + "(ms)");

    // startTime = System.currentTimeMillis() ;
    // inputStream = ODTXSLFOConverterTest.class
    // .getResourceAsStream("HelloWorld.content.xml");
    // // OutputStream outputStream = new StringBuilderOutputStream();
    // result = new DOMResult();
    // try {
    // converter.convert2FO(new StreamSource(inputStream), result);
    // System.err.println(XMLUtils.toString(result.getNode()));
    // } catch (XDocConverterException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // } catch (IOException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    //
    // System.out.println(System.currentTimeMillis() - startTime + "(ms)");

  }
Ejemplo n.º 12
0
 /**
  * Transform a dom4j document into a W3C DOM document
  *
  * @param document dom4j document
  * @return W3C DOM document
  * @throws TransformerException
  */
 public static org.w3c.dom.Document dom4jToDomDocument(Document document)
     throws TransformerException {
   final Transformer identity = getIdentityTransformer();
   final DOMResult domResult = new DOMResult();
   identity.transform(new DocumentSource(document), domResult);
   final Node resultNode = domResult.getNode();
   return (resultNode instanceof org.w3c.dom.Document)
       ? ((org.w3c.dom.Document) resultNode)
       : resultNode.getOwnerDocument();
 }
 @Test
 public void testSourceAsPayload() throws Exception {
   Object transformed = transformer.doTransform(buildMessage(new StringSource(docAsString)));
   assertEquals("Wrong return type for source payload", DOMResult.class, transformed.getClass());
   DOMResult result = (DOMResult) transformed;
   assertXMLEqual(
       "Document incorrect after transformation",
       XmlTestUtil.getDocumentForString(outputAsString),
       (Document) result.getNode());
 }
Ejemplo n.º 14
0
  /**
   * Encodes an object directly to a dom.
   *
   * <p>Note that this method should be used for testing or convenience since it does not stream and
   * loads the entire encoded result into memory.
   */
  public Document encodeAsDOM(Object object, QName name)
      throws IOException, SAXException, TransformerException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    encode(object, name, out);

    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    DOMResult result = new DOMResult();
    Transformer tx = TransformerFactory.newInstance().newTransformer();
    tx.transform(new StreamSource(in), result);
    return (Document) result.getNode();
  }
Ejemplo n.º 15
0
 private Node getDOM(Source source) {
   try {
     Transformer trans = TransformerFactory.newInstance().newTransformer();
     DOMResult dr = new DOMResult();
     trans.transform(source, dr);
     return dr.getNode();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
Ejemplo n.º 16
0
 public static Node getNodeFromSource(Source source)
     throws ProcessingException, ConfigurationException {
   try {
     Transformer transformer = TransformerUtil.getTransformer();
     DOMResult result = new DOMResult();
     TransformerUtil.transform(transformer, source, result);
     return result.getNode();
   } catch (ParsingException pe) {
     throw logger.processingError(pe);
   }
 }
 public static Document getDocumentFromSource(Source source)
     throws ProcessingException, ConfigurationException {
   try {
     Transformer transformer = TransformerUtil.getTransformer();
     DOMResult result = new DOMResult();
     transformer.transform(source, result);
     return (Document) result.getNode();
   } catch (TransformerException te) {
     throw new ProcessingException(te);
   }
 }
Ejemplo n.º 18
0
  /**
   * parse XML/HTML String to a XML DOM representation
   *
   * @param xml XML InputSource
   * @param isHtml is a HTML or XML Object
   * @return parsed Document
   * @throws SAXException
   * @throws IOException
   * @throws ParserConfigurationException
   */
  public static final Document parse(InputSource xml, InputSource validator, boolean isHtml)
      throws SAXException, IOException {

    if (!isHtml) {
      // try to load org.apache.xerces.jaxp.DocumentBuilderFactoryImpl, oracle impl sucks
      DocumentBuilderFactory factory = null;
      try {
        factory = new DocumentBuilderFactoryImpl();
      } catch (Throwable t) {
        factory = DocumentBuilderFactory.newInstance();
      }

      // print.o(factory);
      if (validator == null) {
        XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_EXTERNAL, Boolean.FALSE);
        XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_GRAMMAR, Boolean.FALSE);
      } else {
        XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA, Boolean.TRUE);
        XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA_FULL_CHECKING, Boolean.TRUE);
      }

      factory.setNamespaceAware(true);
      factory.setValidating(validator != null);

      try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new XMLEntityResolverDefaultHandler(validator));
        builder.setErrorHandler(new ThrowingErrorHandler(true, true, false));
        return builder.parse(xml);
      } catch (ParserConfigurationException e) {
        throw new SAXException(e);
      }

      /*DOMParser parser = new DOMParser();
      print.out("parse");
      parser.setEntityResolver(new XMLEntityResolverDefaultHandler(validator));
      parser.parse(xml);
      return parser.getDocument();*/
    }

    XMLReader reader = new Parser();
    reader.setFeature(Parser.namespacesFeature, true);
    reader.setFeature(Parser.namespacePrefixesFeature, true);

    try {
      Transformer transformer = TransformerFactory.newInstance().newTransformer();

      DOMResult result = new DOMResult();
      transformer.transform(new SAXSource(reader, xml), result);
      return XMLUtil.getDocument(result.getNode());
    } catch (Exception e) {
      throw new SAXException(e);
    }
  }
  @Override
  public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
    // In case no input for rpc is defined, we can simply construct the payload here
    final QName rpcQName = rpc.getLastComponent();
    Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;

    // Determine whether a base netconf operation is being invoked and also check if the device
    // exposed model for base netconf
    // If no, use pre built base netconf operations model
    final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseRpc(rpcQName);
    if (needToUseBaseCtx) {
      currentMappedRpcs = MAPPED_BASE_RPCS;
    }

    Preconditions.checkNotNull(
        currentMappedRpcs.get(rpcQName),
        "Unknown rpc %s, available rpcs: %s",
        rpcQName,
        currentMappedRpcs.keySet());
    if (currentMappedRpcs.get(rpcQName).getInput() == null) {
      return new NetconfMessage(
          prepareDomResultForRpcRequest(rpcQName).getNode().getOwnerDocument());
    }

    Preconditions.checkNotNull(
        payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
    Preconditions.checkArgument(
        payload instanceof ContainerNode,
        "Transforming an rpc with input: %s, payload has to be a container, but was: %s",
        rpcQName,
        payload);

    // Set the path to the input of rpc for the node stream writer
    rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
    final DOMResult result = prepareDomResultForRpcRequest(rpcQName);

    try {
      // If the schema context for netconf device does not contain model for base netconf
      // operations, use default pre build context with just the base model
      // This way operations like lock/unlock are supported even if the source for base model was
      // not provided
      writeNormalizedRpc(
          ((ContainerNode) payload),
          result,
          rpc,
          needToUseBaseCtx ? BASE_NETCONF_CTX : schemaContext);
    } catch (final XMLStreamException | IOException | IllegalStateException e) {
      throw new IllegalStateException("Unable to serialize " + rpc, e);
    }

    final Document node = result.getNode().getOwnerDocument();

    return new NetconfMessage(node);
  }
Ejemplo n.º 20
0
 private Document getLibrariesList(Socket servSct) throws Exception {
   try {
     BufferedReader reader = new BufferedReader(new InputStreamReader(servSct.getInputStream()));
     StringReader sr = new StringReader(reader.readLine());
     StreamSource src = new StreamSource(sr);
     DOMResult res = new DOMResult();
     TransformerFactory.newInstance().newTransformer().transform(src, res);
     return (Document) res.getNode();
   } catch (Exception e) {
     throw new Exception("Failed getting libraries list.", e);
   }
 }
Ejemplo n.º 21
0
  /**
   * 指定されたURLから、フィードのURLを検索する。
   *
   * @param url フィードURL検索先
   * @return 検索結果リスト。見つからなかった場合は空のArrayListを返却する。
   * @throws FeedParseException HTML解析中にエラーが発生した場合
   */
  public ArrayList<FeedSource> findFeedUrl(String strUrl) throws FeedParseException {
    ArrayList<FeedSource> feedList = new ArrayList<FeedSource>();
    HttpURLConnection connection = null;
    InputStream is = null;
    try {
      // 指定されたURLに接続する。
      connection = connectURL(strUrl);
      is = connection.getInputStream();

      String enc = connection.getContentEncoding();
      if (enc == null) {
        // content-encodingヘッダが設定されて無い場合はとりあえずutf-8を設定。
        enc = "utf-8";
      }

      // 接続したサイトのソースを取得し、パースする。
      DOMResult result = parseDOM(is, enc);

      // linkタグを取得する。
      Document doc = (Document) result.getNode();
      String docEnc = getDocumentEncoding(doc);

      if (docEnc != null && !enc.equals(docEnc)) {
        // Documentの文字コードが事前に設定したものと違う場合は、
        // 文字コードを変更し、再接続する。
        dispose(connection, is);
        connection = connectURL(strUrl);
        is = connection.getInputStream();

        result = parseDOM(is, docEnc);
        doc = (Document) result.getNode();
      }
      NodeList childs = doc.getElementsByTagName(TAG_NAME_LINK);

      for (int i = 0; i < childs.getLength(); i++) {
        Element element = (Element) childs.item(i);

        if (isRssAutoDiscovery(element)) {
          FeedSource entity = setFeedSource(element);
          FeedParseFacade facade = new FeedParseFacade();
          entity.setVersion(facade.getRssVersion(entity.getFeedUrl()));
          feedList.add(entity);
        }
      }

    } catch (Exception e) {
      throw new FeedParseException(e);
    } finally {
      // 後始末
      dispose(connection, is);
    }
    return feedList;
  }
 protected Document transformDocument(Document documentPayload, Transformer transformer)
     throws TransformerException {
   DOMSource source = new DOMSource(documentPayload);
   Result result = resultFactory.createResult(documentPayload);
   if (!DOMResult.class.isAssignableFrom(result.getClass())) {
     throw new MessagingException(
         "Document to Document conversion requires a DOMResult-producing ResultFactory implementation.");
   }
   DOMResult domResult = (DOMResult) result;
   transformer.transform(source, domResult);
   return (Document) domResult.getNode();
 }
 @Test
 public void testStringAsPayloadUseResultFactoryTrue() throws Exception {
   transformer.setAlwaysUseResultFactory(true);
   Object transformed = transformer.doTransform(buildMessage(docAsString));
   assertEquals(
       "Wrong return type for useFactories true", DOMResult.class, transformed.getClass());
   DOMResult result = (DOMResult) transformed;
   assertXMLEqual(
       "Document incorrect after transformation",
       XmlTestUtil.getDocumentForString(outputAsString),
       (Document) result.getNode());
 }
Ejemplo n.º 24
0
  @Test
  public void testGetFlightsXml()
      throws AirlineException, DatatypeConfigurationException, TransformerException {
    GetFlightsRequest request = JAXB.unmarshal(getStream("request1.xml"), GetFlightsRequest.class);

    GetFlightsResponse response = endpoint.getFlights(request);

    DOMResult domResponse = new DOMResult();
    JAXB.marshal(response, domResponse);

    XMLUnit.setIgnoreWhitespace(true);
    XMLAssert.assertXMLEqual(getDocument("response1.xml"), (Document) domResponse.getNode());
  }
Ejemplo n.º 25
0
  /**
   * Show a query producing a DOM as its output. The DOM is then serialized using an identity
   * transform
   */
  public static void exampleToDOM() throws TransformerException {
    final Configuration config = new Configuration();
    final StaticQueryContext sqc = config.newStaticQueryContext();
    final XQueryExpression exp =
        sqc.compileQuery("<a xmlns='http://a/uri' xmlns:a='another.uri'>text</a>");

    final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
    DOMResult result = new DOMResult();
    exp.run(dynamicContext, result, new Properties());

    // now serialize the DOM

    Transformer identity = TransformerFactory.newInstance().newTransformer();
    identity.transform(new DOMSource(result.getNode()), new StreamResult(System.out));
  }
Ejemplo n.º 26
0
 private void buildHierarchyDOM() {
   TransformerFactory factory = TransformerFactory.newInstance();
   StreamSource src =
       new StreamSource(
           this.getServletContext()
               .getResourceAsStream("/WEB-INF/classes/gpt/search/browse/ownerHierarchy.xml"));
   log.info("initializing src from stream " + src);
   try {
     Transformer t = factory.newTransformer();
     dom = new DOMResult();
     t.transform(src, dom);
     // now go thru tree, setting up the query attribute for each node
     Node tree = dom.getNode();
     NodeList children = tree.getChildNodes();
     log.info("dom tree contains " + children.getLength() + " nodes");
     for (int i = 0; i < children.getLength(); i++) {
       Node child = children.item(i);
       if (child.getNodeType() == Node.ELEMENT_NODE) {
         Element e = (Element) child;
         String query = computeQuery(e);
         e.setAttribute("query", query);
       }
     }
   } catch (Exception e) {
     log.severe("Could not init ownerHierarchy because exception thrown:");
     StringWriter sw = new StringWriter();
     e.printStackTrace(new PrintWriter(sw));
     log.severe(sw.toString());
   }
 }
Ejemplo n.º 27
0
 /**
  * This method deserializes the supplied document.
  *
  * @param doc The XML document
  * @return The DOM node, or null if an error occurred
  */
 protected static Node deserializeString(String doc) {
   try {
     StringReader reader = new StringReader(doc);
     StreamSource source = new StreamSource(reader);
     DOMResult result = new DOMResult();
     TransformerFactory tf = TransformerFactory.newInstance();
     Transformer transformer = tf.newTransformer();
     transformer.setOutputProperty(OutputKeys.ENCODING, DEFAULT_ENCODING);
     transformer.setOutputProperty(OutputKeys.INDENT, DEFAULT_INDENT);
     transformer.transform(source, result);
     return result.getNode();
   } catch (Throwable e) {
     log.log(Level.SEVERE, "Failed to serialize node", e);
   }
   return null;
 }
Ejemplo n.º 28
0
 /*
  * If the element contains an attribute 'makeOnly' with a value of 'true',
  * create a child element before any existing children which will display a node
  * which will display only the elements records.
  * Compute the query attribute, which is the appended result of all of the children
  * appended to this element name. If noQuery=true. then do not generate a query term
  * for this element.
  */
 String computeQuery(Element e) {
   String query = "";
   if (!(e.getAttribute("noQuery").equalsIgnoreCase("true"))) {
     query = e.getAttribute("name");
   }
   String makeOnly = e.getAttribute("makeOnly");
   boolean madeOnly = false;
   NodeList children = e.getChildNodes();
   for (int i = 0; i < children.getLength(); i++) {
     Node child = children.item(i);
     if (child.getNodeType() == Node.ELEMENT_NODE) {
       if (makeOnly.equalsIgnoreCase("true") && !madeOnly) {
         // need to make an ...-Only node and populate it
         String onlyTagName = e.getTagName() + "-Only";
         Element only = ((Document) dom.getNode()).createElement(onlyTagName);
         only.setAttribute("name", e.getAttribute("name") + "-Only");
         only.setAttribute("query", e.getAttribute("name"));
         e.insertBefore(only, child);
         i++;
         madeOnly = true;
       }
       if (query.length() > 0) {
         query += ",";
       }
       query += computeQuery((Element) child);
     }
   }
   log.info("setting query for " + e.getNodeName() + "   " + query);
   e.setAttribute("query", query);
   return query;
 }
Ejemplo n.º 29
0
  public void marshal(Object obj, Result result) throws JAXBException {
    // XMLSerializable so = Util.toXMLSerializable(obj);
    XMLSerializable so = context.getGrammarInfo().castToXMLSerializable(obj);

    if (so == null) throw new MarshalException(Messages.format(Messages.NOT_MARSHALLABLE));

    if (result instanceof SAXResult) {
      write(so, ((SAXResult) result).getHandler());
      return;
    }
    if (result instanceof DOMResult) {
      Node node = ((DOMResult) result).getNode();

      if (node == null) {
        try {
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          dbf.setNamespaceAware(true);
          DocumentBuilder db = dbf.newDocumentBuilder();
          Document doc = db.newDocument();
          ((DOMResult) result).setNode(doc);
          write(so, new SAX2DOMEx(doc));
        } catch (ParserConfigurationException pce) {
          throw new JAXBAssertionError(pce);
        }
      } else {
        write(so, new SAX2DOMEx(node));
      }

      return;
    }
    if (result instanceof StreamResult) {
      StreamResult sr = (StreamResult) result;
      XMLWriter w = null;

      if (sr.getWriter() != null) w = createWriter(sr.getWriter());
      else if (sr.getOutputStream() != null) w = createWriter(sr.getOutputStream());
      else if (sr.getSystemId() != null) {
        String fileURL = sr.getSystemId();

        if (fileURL.startsWith("file:///")) {
          if (fileURL.substring(8).indexOf(":") > 0) fileURL = fileURL.substring(8);
          else fileURL = fileURL.substring(7);
        } // otherwise assume that it's a file name

        try {
          w = createWriter(new FileOutputStream(fileURL));
        } catch (IOException e) {
          throw new MarshalException(e);
        }
      }

      if (w == null) throw new IllegalArgumentException();

      write(so, w);
      return;
    }

    // unsupported parameter type
    throw new MarshalException(Messages.format(Messages.UNSUPPORTED_RESULT));
  }
Ejemplo n.º 30
0
  /**
   * Explore handling of Jaxb classes which specify an @XmlElement with a super class. How do
   * subclasses get treated with this?
   */
  @Test
  public void ConvActionRequestJaxbSubclassHandlingTest() throws Exception {
    testFolderActionSelector fas = new testFolderActionSelector();
    fas.setId("ids");
    fas.setOp("op");
    fas.setL("folder");
    fas.setRecursive(true);
    fas.setUrl("http://url");
    testConvActionRequest car = new testConvActionRequest();
    car.setAction(fas);

    Class<?> ctxClasses[] = new Class<?>[] {testConvActionRequest.class};
    JAXBContext jaxb = JAXBContext.newInstance(ctxClasses);
    Marshaller marshaller = jaxb.createMarshaller();
    DOMResult domRes = new DOMResult();
    // Specifying namespace in QName seems to cause problems,
    // however, correct namespace seems to get there, presumably
    // from package-info
    JAXBElement<testConvActionRequest> jbe =
        new JAXBElement<testConvActionRequest>(
            new QName("ConvActionRequest"), testConvActionRequest.class, car);
    marshaller.marshal(jbe, domRes);
    // marshaller.marshal(car, domRes);
    Node docNode = domRes.getNode();
    String eXml = domToString((org.w3c.dom.Document) docNode);
    LOG.info("ConvActionRequestJaxbSubclassHandling: marshalled XML=" + eXml);
    Assert.assertTrue(
        "Xml should contain recursive attribute", eXml.contains("recursive=\"true\""));
    Unmarshaller unmarshaller = jaxb.createUnmarshaller();
    org.w3c.dom.Document doc = toW3cDom(eXml);
    jbe = unmarshaller.unmarshal(doc, testConvActionRequest.class);
    car = jbe.getValue();
    testActionSelector as = car.getAction();
    Assert.assertEquals("Folder attribute value", "folder", as.getL());
    if (as instanceof testFolderActionSelector) {
      fas = (testFolderActionSelector) as;
      Assert.assertEquals("Url attribute value", "http://url", fas.getUrl());
    } else if (as instanceof testNoteActionSelector) {
      Assert.fail("got a NoteActionSelector");
    } else if (as instanceof testContactActionSelector) {
      Assert.fail("got a ContactActionSelector");
    } else {
      Assert.fail("Failed to get back a FolderActionSelector");
    }
  }