Exemple #1
0
 /**
  * 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 "";
   }
 }
Exemple #2
0
 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);
 }
 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);
    }
  }
Exemple #5
0
  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);
    }
  }
  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");
    }
  }
Exemple #7
0
 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();
 }
Exemple #8
0
  /**
   * 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.");
    }
  }
Exemple #9
0
  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;
    }
  }
Exemple #10
0
  /**
   * 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);
  }
  /**
   * 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);
    }
  }
  @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());
  }
  /**
   * 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);
    }
  }