コード例 #1
0
ファイル: AxiomUtils.java プロジェクト: NVolcz/spring-ws
  /**
   * Converts a given {@link Document} to an AXIOM {@link org.apache.axiom.soap.SOAPEnvelope}.
   *
   * @param document the document to be converted
   * @return the converted envelope
   * @throws IllegalArgumentException in case of errors
   * @see org.apache.rampart.util.Axis2Util.getSOAPEnvelopeFromDOMDocument(Document, boolean)
   */
  public static SOAPEnvelope toEnvelope(Document document) {
    try {
      DOMImplementation implementation = document.getImplementation();
      Assert.isInstanceOf(DOMImplementationLS.class, implementation);

      DOMImplementationLS loadSaveImplementation = (DOMImplementationLS) implementation;
      LSOutput output = loadSaveImplementation.createLSOutput();
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      output.setByteStream(bos);

      LSSerializer serializer = loadSaveImplementation.createLSSerializer();
      serializer.write(document, output);

      ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

      XMLInputFactory inputFactory = StAXUtils.getXMLInputFactory();

      StAXSOAPModelBuilder stAXSOAPModelBuilder =
          new StAXSOAPModelBuilder(inputFactory.createXMLStreamReader(bis), null);
      SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope();

      // Necessary to build a correct Axiom tree, see SWS-483
      envelope.serialize(new NullOutputStream());

      return envelope;
    } catch (Exception ex) {
      IllegalArgumentException iaex =
          new IllegalArgumentException("Error in converting Document to SOAP Envelope");
      iaex.initCause(ex);
      throw iaex;
    }
  }
コード例 #2
0
  /**
   * Serialize the Auth. Request
   *
   * @param xmlObject
   * @return serialized auth. req
   */
  protected String marshall(XMLObject xmlObject) throws SSOAgentException {

    try {
      System.setProperty(
          "javax.xml.parsers.DocumentBuilderFactory",
          "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
      MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
      Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
      Element element = marshaller.marshall(xmlObject);
      ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
      DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
      DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
      LSSerializer writer = impl.createLSSerializer();
      LSOutput output = impl.createLSOutput();
      output.setByteStream(byteArrayOutputStrm);
      writer.write(element, output);
      return new String(byteArrayOutputStrm.toByteArray(), Charset.forName("UTF-8"));
    } catch (ClassNotFoundException e) {
      throw new SSOAgentException("Error in marshalling SAML2 Assertion", e);
    } catch (InstantiationException e) {
      throw new SSOAgentException("Error in marshalling SAML2 Assertion", e);
    } catch (MarshallingException e) {
      throw new SSOAgentException("Error in marshalling SAML2 Assertion", e);
    } catch (IllegalAccessException e) {
      throw new SSOAgentException("Error in marshalling SAML2 Assertion", e);
    }
  }
コード例 #3
0
  protected String buildXMLResultString(ResultSequence rs) throws Exception {
    DOMImplementationLS domLS =
        (DOMImplementationLS) domDoc.getImplementation().getFeature("LS", "3.0");
    LSOutput outputText = domLS.createLSOutput();
    LSSerializer serializer = domLS.createLSSerializer();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    outputText.setByteStream(outputStream);

    String actual = new String();
    Iterator iterator = rs.iterator();
    boolean queueSpace = false;
    while (iterator.hasNext()) {
      AnyType aat = (AnyType) iterator.next();
      if (aat instanceof NodeType) {
        NodeType nodeType = (NodeType) aat;
        Node node = nodeType.node_value();
        serializer.write(node, outputText);
        queueSpace = false;
      } else {
        if (queueSpace) outputText.getByteStream().write(32);
        outputText.getByteStream().write(aat.getStringValue().getBytes("UTF-8"));
        queueSpace = true;
      }
    }

    actual = outputStream.toString("UTF-8");
    actual = actual.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
    actual = actual.replace("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>", "");
    outputStream.close();
    return actual.trim();
  }
コード例 #4
0
ファイル: XMLUtils.java プロジェクト: njmfhgc/xwiki-commons
 /**
  * Serialize a DOM Node into a string, with an optional XML declaration at the start.
  *
  * @param node the node to export
  * @param withXmlDeclaration whether to output the XML declaration or not
  * @return the serialized node, or an empty string if the serialization fails or the node is
  *     {@code null}
  */
 public static String serialize(Node node, boolean withXmlDeclaration) {
   if (node == null) {
     return "";
   }
   try {
     LSOutput output = LS_IMPL.createLSOutput();
     StringWriter result = new StringWriter();
     output.setCharacterStream(result);
     LSSerializer serializer = LS_IMPL.createLSSerializer();
     serializer.getDomConfig().setParameter("xml-declaration", withXmlDeclaration);
     serializer.setNewLine("\n");
     String encoding = "UTF-8";
     if (node instanceof Document) {
       encoding = ((Document) node).getXmlEncoding();
     } else if (node.getOwnerDocument() != null) {
       encoding = node.getOwnerDocument().getXmlEncoding();
     }
     output.setEncoding(encoding);
     serializer.write(node, output);
     return result.toString();
   } catch (Exception ex) {
     LOGGER.warn("Failed to serialize node to XML String: [{}]", ex.getMessage());
     return "";
   }
 }
コード例 #5
0
 /**
  * Serializes the specified SAML 2.0 based XML content representation to its corresponding actual
  * XML syntax representation.
  *
  * @param xmlObject the SAML 2.0 based XML content object
  * @return a {@link String} representation of the actual XML representation of the SAML 2.0 based
  *     XML content representation
  * @throws SSOException if an error occurs during the marshalling process
  */
 public static String marshall(XMLObject xmlObject) throws SSOException {
   try {
     //  Explicitly sets the special XML parser library to be used, in the global variables
     System.setProperty(
         "javax.xml.parsers.DocumentBuilderFactory",
         "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
     MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();
     Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
     Element element = marshaller.marshall(xmlObject);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
     DOMImplementationLS implementation =
         (DOMImplementationLS) registry.getDOMImplementation("LS");
     LSSerializer writer = implementation.createLSSerializer();
     LSOutput output = implementation.createLSOutput();
     output.setByteStream(byteArrayOutputStream);
     writer.write(element, output);
     return new String(byteArrayOutputStream.toByteArray(), Charset.forName("UTF-8"));
   } catch (ClassNotFoundException
       | InstantiationException
       | MarshallingException
       | IllegalAccessException e) {
     throw new SSOException("Error in marshalling SAML2 Assertion", e);
   }
 }
コード例 #6
0
ファイル: GetCapsOutputter.java プロジェクト: CowanSM/ncSOS
 public void writeOutput(Writer writer) {
   // output our document to the writer
   LSSerializer xmlSerializer = impl.createLSSerializer();
   LSOutput xmlOut = impl.createLSOutput();
   xmlSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
   xmlOut.setCharacterStream(writer);
   xmlSerializer.write(document, xmlOut);
 }
コード例 #7
0
 public String toString() {
   DOMImplementationLS domLoadSave = (DOMImplementationLS) d.getImplementation();
   LSOutput output = domLoadSave.createLSOutput();
   StringWriter sw = new StringWriter();
   output.setCharacterStream(sw);
   LSSerializer lss = domLoadSave.createLSSerializer();
   lss.write(d, output);
   return sw.toString();
 }
  @Override
  public void serialize(final Node content, final Writer writer) {
    try {
      lazyInit();

      final LSSerializer serializer = DOM_IMPL.createLSSerializer();

      final LSOutput lso = DOM_IMPL.createLSOutput();
      lso.setCharacterStream(writer);

      serializer.write(content, lso);
    } catch (Exception e) {
      throw new IllegalArgumentException("While serializing DOM element", e);
    }
  }
コード例 #9
0
ファイル: XMLUtils.java プロジェクト: firstone/latic
  public static void writeXML(Document doc, Writer stream) throws ESException {
    try {
      DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
      DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS");

      LSSerializer writer = impl.createLSSerializer();
      writer.getDomConfig().setParameter("format-pretty-print", true);
      LSOutput out = impl.createLSOutput();

      out.setCharacterStream(stream);
      writer.write(doc, out);
    } catch (Exception e) {
      throw new ESException(e);
    }
  }
コード例 #10
0
  public void connectXML(String port, String user, String pass)
      throws ParserConfigurationException {
    String filename = "connect.xml";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element body = doc.createElement("Connect");
    doc.appendChild(body);

    Element e = doc.createElement("Port");
    Text t = doc.createTextNode(port);
    e.appendChild(t);
    body.appendChild(e);

    Element e1 = doc.createElement("User");
    Text t1 = doc.createTextNode(user);
    e1.appendChild(t1);
    body.appendChild(e1);

    Element e2 = doc.createElement("Pass");
    Text t2 = doc.createTextNode(pass);
    e2.appendChild(t2);
    body.appendChild(e2);

    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer ser = implLS.createLSSerializer();
    LSOutput lsOutput = implLS.createLSOutput();
    lsOutput.setEncoding("UTF-8");
    // System.out.println(lsOutput.toString());
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    ser.write(doc, lsOutput);
    String result = stringWriter.toString();
    System.out.println(result);
    // System.out.println(ser.write(doc,lsOutput));
    try {
      print(filename, result);
      System.out.println("Print Success");
      File file = new File(filename);
      System.out.println(file.getCanonicalPath());
    } catch (IOException e3) {
      // TODO Auto-generated catch block
      e3.printStackTrace();
      System.out.println("print failed");
    }
  }
コード例 #11
0
ファイル: XMLUtils.java プロジェクト: nagyistoce/hapi-fhir
 public static String serialize(Document document, boolean prettyPrint) {
   DOMImplementationLS impl = getDOMImpl();
   LSSerializer serializer = impl.createLSSerializer();
   // document.normalizeDocument();
   DOMConfiguration config = serializer.getDomConfig();
   if (prettyPrint && config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
     config.setParameter("format-pretty-print", true);
   }
   config.setParameter("xml-declaration", true);
   LSOutput output = impl.createLSOutput();
   output.setEncoding("UTF-8");
   Writer writer = new StringWriter();
   output.setCharacterStream(writer);
   serializer.write(document, output);
   return writer.toString();
 }
コード例 #12
0
ファイル: XmlUtil.java プロジェクト: natecollins/REPOX
  /**
   * Converts a dom element to a String
   *
   * @param node
   * @return the dom as a String
   */
  public static String writeDomToString(Element node) {
    DOMImplementation domImplementation = node.getOwnerDocument().getImplementation();
    if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
      DOMImplementationLS domImplementationLS =
          (DOMImplementationLS) domImplementation.getFeature("LS", "3.0");
      LSSerializer lsSerializer = domImplementationLS.createLSSerializer();

      LSOutput lsOutput = domImplementationLS.createLSOutput();
      lsOutput.setEncoding("UTF-8");

      StringWriter stringWriter = new StringWriter();
      lsOutput.setCharacterStream(stringWriter);
      lsSerializer.write(node, lsOutput);
      return stringWriter.toString();
    } else {
      throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
    }
  }
コード例 #13
0
ファイル: Util.java プロジェクト: GayashanNA/carbon-utils
  /**
   * Serializing a SAML2 object into a String
   *
   * @param xmlObject object that needs to serialized.
   * @return serialized object
   * @throws Exception
   */
  public static String marshall(XMLObject xmlObject) throws Exception {
    try {
      doBootstrap();
      System.setProperty(
          "javax.xml.parsers.DocumentBuilderFactory",
          "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

      MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
      Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
      Element element = marshaller.marshall(xmlObject);

      ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
      DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
      DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
      LSSerializer writer = impl.createLSSerializer();
      LSOutput output = impl.createLSOutput();
      output.setByteStream(byteArrayOutputStrm);
      writer.write(element, output);
      return byteArrayOutputStrm.toString();
    } catch (Exception e) {
      throw new Exception("Error Serializing the SAML Response", e);
    }
  }
コード例 #14
0
ファイル: SCXMLVisitorImpl.java プロジェクト: remen/squirrel
  private String beautify(String unformattedXml) {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      InputSource is = new InputSource(new StringReader(unformattedXml));
      Document doc = db.parse(is);

      DOMImplementationRegistry domReg = DOMImplementationRegistry.newInstance();
      DOMImplementationLS lsImpl = (DOMImplementationLS) domReg.getDOMImplementation("LS");
      LSSerializer lsSerializer = lsImpl.createLSSerializer();
      lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
      LSOutput output = lsImpl.createLSOutput();
      output.setEncoding("UTF-8");

      StringWriter destination = new StringWriter();
      output.setCharacterStream(destination);
      lsSerializer.write(doc, output);
      return destination.toString();
    } catch (Exception e) {
      // format failed, return unformatted xml
      return unformattedXml;
    }
  }
コード例 #15
0
ファイル: EsbUtils.java プロジェクト: ww102111/tools
  /**
   * Utility method for rendering an {@link Element} into a {@link Writer}.
   *
   * @param element {@link Element} to be rendered.
   * @param writer {@link Writer} instance.
   * @param omitXmlDeclaration whether to omit the XML declaration from output.
   * @throws Exception if an error occurs during serialization.
   */
  public static void renderElement(Element element, Writer writer, boolean omitXmlDeclaration)
      throws Exception {
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

    LSSerializer lsSerializer = impl.createLSSerializer();
    {
      DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
      if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) {
        domConfiguration.setParameter("format-pretty-print", Boolean.TRUE);
      }

      if (omitXmlDeclaration
          && domConfiguration.canSetParameter("xml-declaration", Boolean.FALSE)) {
        domConfiguration.setParameter("xml-declaration", Boolean.FALSE);
      }
    }

    LSOutput lsOutput = impl.createLSOutput();
    lsOutput.setEncoding("UTF-8");
    lsOutput.setCharacterStream(writer);

    lsSerializer.write(element, lsOutput);
  }
コード例 #16
0
  /**
   * Create the xml files for communities
   *
   * @param f
   * @param communities
   * @throws IOException
   */
  public void generateCommunityXMLFile(File f, Collection<Community> communities)
      throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    try {
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "communities", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
      fos = new FileOutputStream(f);

      try {
        outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
      } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
      }
      writer = new BufferedWriter(outputStreamWriter);
      lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
      throw new IllegalStateException(e);
    }

    // create XML for the communities
    for (Community c : communities) {
      Element community = doc.createElement("community");
      Element id = doc.createElement("id");
      Text data = doc.createTextNode(c.id.toString());
      id.appendChild(data);
      community.appendChild(id);

      Element name = doc.createElement("name");
      data = doc.createTextNode(c.name);
      name.appendChild(data);
      community.appendChild(name);

      Element introductoryText = doc.createElement("introductory_text");
      data = doc.createTextNode(c.introductoryText);
      introductoryText.appendChild(data);
      community.appendChild(introductoryText);

      Element sideBarText = doc.createElement("side_bar_text");
      data = doc.createTextNode(c.sideBarText);
      sideBarText.appendChild(data);
      community.appendChild(sideBarText);

      Element copyright = doc.createElement("copyright");
      data = doc.createTextNode(c.copyright);
      copyright.appendChild(data);
      community.appendChild(copyright);

      Element logoFileName = null;
      if (c.logoFileInfo != null) {
        logoFileName = doc.createElement("logo_file_name");
        data = doc.createTextNode(c.logoFileInfo.newFileName);
        logoFileName.appendChild(data);
        community.appendChild(logoFileName);
      }

      root.appendChild(community);

      if (c.links != null && c.links.size() > 0) {
        Element links = doc.createElement("links");

        // add the links
        for (Link l : c.links) {
          Element link = doc.createElement("link");
          Element linkName = doc.createElement("name");
          data = doc.createTextNode(l.name);
          linkName.appendChild(data);

          Element linkUrl = doc.createElement("url");
          data = doc.createTextNode(l.value);
          linkUrl.appendChild(data);

          link.appendChild(linkName);
          link.appendChild(linkUrl);
          links.appendChild(link);
        }
        community.appendChild(links);
      }

      if (c.groupPermissions != null && c.groupPermissions.size() > 0) {
        Element groupPermissions = doc.createElement("group_permissions");

        // add the links
        for (GroupPermission p : c.groupPermissions) {
          Element groupPermission = doc.createElement("group_permission");

          Element permissionAction = doc.createElement("action_id");
          data = doc.createTextNode(p.action + "");
          permissionAction.appendChild(data);
          groupPermission.appendChild(permissionAction);

          Element groupId = doc.createElement("group_id");
          data = doc.createTextNode(p.groupId.toString());
          groupId.appendChild(data);
          groupPermission.appendChild(groupId);

          groupPermissions.appendChild(groupPermission);
        }
        community.appendChild(groupPermissions);
      }

      if (c.epersonPermissions != null && c.epersonPermissions.size() > 0) {
        Element epersonPermissions = doc.createElement("eperson_permissions");

        // add the links
        for (EpersonPermission p : c.epersonPermissions) {
          Element epersonPermission = doc.createElement("eperson_permission");

          Element permissionAction = doc.createElement("action_id");
          data = doc.createTextNode(p.action + "");
          permissionAction.appendChild(data);
          epersonPermission.appendChild(permissionAction);

          Element epersonId = doc.createElement("eperson_id");
          data = doc.createTextNode(p.epersonId.toString());
          epersonId.appendChild(data);
          epersonPermission.appendChild(epersonId);

          epersonPermissions.appendChild(epersonPermission);
        }
        community.appendChild(epersonPermissions);
      }
    }
    serializer.write(root, lsOut);

    try {
      fos.close();
      writer.close();
      outputStreamWriter.close();
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }
コード例 #17
0
  @Test
  public void writeAtomViaLowerlevelLibs()
      throws ParserConfigurationException, ClassNotFoundException, InstantiationException,
          IllegalAccessException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element entry = doc.createElement("entry");
    entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom");
    entry.setAttribute("xmlns:m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
    entry.setAttribute("xmlns:d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
    entry.setAttribute("xmlns:gml", "http://www.opengis.net/gml");
    entry.setAttribute("xmlns:georss", "http://www.georss.org/georss");
    doc.appendChild(entry);

    final Element category = doc.createElement("category");
    category.setAttribute("term", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");
    category.setAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme");
    entry.appendChild(category);

    final Element properties = doc.createElement("m:properties");
    entry.appendChild(properties);

    final Element name = doc.createElement("d:Name");
    name.setAttribute("m:type", "Edm.String");
    name.appendChild(doc.createTextNode("A name"));
    properties.appendChild(name);

    final Element customerId = doc.createElement("d:CustomerId");
    customerId.setAttribute("m:type", "Edm.Int32");
    customerId.appendChild(doc.createTextNode("0"));
    properties.appendChild(customerId);

    final Element bci = doc.createElement("d:BackupContactInfo");
    bci.setAttribute(
        "m:type", "Collection(Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails)");
    properties.appendChild(bci);

    final Element topelement = doc.createElement("d:element");
    topelement.setAttribute(
        "m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails");
    bci.appendChild(topelement);

    final Element altNames = doc.createElement("d:AlternativeNames");
    altNames.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(altNames);

    final Element element1 = doc.createElement("d:element");
    element1.setAttribute("m:type", "Edm.String");
    element1.appendChild(doc.createTextNode("myname"));
    altNames.appendChild(element1);

    final Element emailBag = doc.createElement("d:EmailBag");
    emailBag.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(emailBag);

    final Element element2 = doc.createElement("d:element");
    element2.setAttribute("m:type", "Edm.String");
    element2.appendChild(doc.createTextNode("*****@*****.**"));
    emailBag.appendChild(element2);

    final Element contactAlias = doc.createElement("d:ContactAlias");
    contactAlias.setAttribute(
        "m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    topelement.appendChild(contactAlias);

    final Element altNames2 = doc.createElement("d:AlternativeNames");
    altNames2.setAttribute("m:type", "Collection(Edm.String)");
    contactAlias.appendChild(altNames2);

    final Element element3 = doc.createElement("d:element");
    element3.setAttribute("m:type", "Edm.String");
    element3.appendChild(doc.createTextNode("myAlternativeName"));
    altNames2.appendChild(element3);

    final StringWriter writer = new StringWriter();

    final DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
    final DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS");
    final LSSerializer serializer = impl.createLSSerializer();
    final LSOutput lso = impl.createLSOutput();
    lso.setCharacterStream(writer);
    serializer.write(doc, lso);

    assertFalse(writer.toString().isEmpty());
  }
コード例 #18
0
  /**
   * Create the xml file for the set of collections.
   *
   * @param xmlFile - file to write the xml to
   * @param contributor types - set of contributor types to export
   * @throws IOException - if writing to the file fails.
   */
  public void createXmlFile(File xmlFile, Collection<ContributorType> contributorTypes)
      throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    String path = FilenameUtils.getPath(xmlFile.getCanonicalPath());
    if (!path.equals("")) {
      File pathOnly = new File(FilenameUtils.getFullPath(xmlFile.getCanonicalPath()));
      FileUtils.forceMkdir(pathOnly);
    }

    if (!xmlFile.exists()) {
      if (!xmlFile.createNewFile()) {
        throw new IllegalStateException("could not create file");
      }
    }

    try {
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "contributor_types", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
      fos = new FileOutputStream(xmlFile);

      try {
        outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
      } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
      }
      writer = new BufferedWriter(outputStreamWriter);
      lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
      throw new IllegalStateException(e);
    }

    // create XML for the child collections
    for (ContributorType ct : contributorTypes) {
      Element contributorType = doc.createElement("contributor_type");

      this.addIdElement(contributorType, ct.getId().toString(), doc);
      this.addNameElement(contributorType, ct.getName(), doc);
      this.addDescription(contributorType, ct.getDescription(), doc);
      this.addSystemCode(contributorType, ct.getUniqueSystemCode(), doc);
    }
    serializer.write(root, lsOut);

    try {
      fos.close();
      writer.close();
      outputStreamWriter.close();
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }