nu.xom.Builder Java Examples

The following examples show how to use nu.xom.Builder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XMLUtil.java    From rest-client with Apache License 2.0 8 votes vote down vote up
@Deprecated
public static String indentXML(final String in)
        throws XMLException, IOException {
    try {
        Builder parser = new Builder();
        Document doc = parser.build(in, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Serializer serializer = new Serializer(baos);
        serializer.setIndent(4);
        serializer.setMaxLength(69);
        serializer.write(doc);
        return new String(baos.toByteArray());
    } catch (ParsingException ex) {
        // LOG.log(Level.SEVERE, null, ex);
        throw new XMLException("XML indentation failed.", ex);
    }
}
 
Example #2
Source File: JunkUtils.java    From http4e with Apache License 2.0 6 votes vote down vote up
public static String prettyXml(String xml, String firstLine){
      try {
         
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         Serializer serializer = new Serializer(out);
         serializer.setIndent(2);
         if(firstLine != null){
            serializer.write(new Builder().build(firstLine + xml, ""));            
         } else {
            serializer.write(new Builder().build(xml, ""));
         }
         String ret =  out.toString("UTF-8");
         if(firstLine != null){
            return ret.substring(firstLine.length() , ret.length()).trim();
         } else {
            return ret;            
         }
      } catch (Exception e) {
//         ExceptionHandler.handle(e);
         return xml;
      }
   }
 
Example #3
Source File: SettingsManager.java    From ciscorouter with MIT License 6 votes vote down vote up
/**
 * Constructs the class. Requires settings.xml to be present to run
 */
public SettingsManager() {
    String currentDir = System.getProperty("user.dir");
    String settingDir = currentDir + "/settings/";
    File f = new File(settingDir + "settings.xml");
    if (f.exists() && !f.isDirectory()) {
        try {
            Builder parser = new Builder();
            Document doc   = parser.build(f);
            Element root   = doc.getRootElement();

            Element eUsername = root.getFirstChildElement("Username");
            username = eUsername.getValue();

            Element ePassword = root.getFirstChildElement("Password");
            password = ePassword.getValue();

            requiresAuth = true;
        } catch (ParsingException|IOException e) {
            e.printStackTrace();
        }
    }
    else {
        requiresAuth = false;
    }
}
 
Example #4
Source File: XomCreateXML.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * Create Document Type
 */
@Test
public void test06() throws Exception{
	Element greeting = new Element("greeting");
	Document doc = new Document(greeting);
	String temp = "<!DOCTYPE element [\n" 
	  + "<!ELEMENT greeting (#PCDATA)>\n"
	  + "]>\n"
	  + "<root />";
	Builder builder = new Builder();
	Document tempDoc = builder.build(temp, null);
	DocType doctype = tempDoc.getDocType();
	doctype.detach();
	doc.setDocType(doctype);
	
	System.out.println(doc.toXML()); 
	
}
 
Example #5
Source File: XmlEntity.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Use the CacheXmlGenerator to create XML from the entity associated with
 * the current cache.
 * 
 * @param element Name of the XML element to search for.
 * @param attributes
 *          Attributes of the element that should match, for example "name" or
 *          "id" and the value they should equal.
 * 
 * @return XML string representation of the entity.
 */
private final String loadXmlDefinition(final String element, final Map<String, String> attributes) {
  final Cache cache = CacheFactory.getAnyInstance();
  Document document = null;

  try {
    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);
    CacheXmlGenerator.generate(cache, printWriter, false, false, false);
    printWriter.close();

    // Remove the DOCTYPE line when getting the string to prevent
    // errors when trying to locate the DTD.
    String xml = stringWriter.toString().replaceFirst("<!DOCTYPE.*>", "");
    document = new Builder(false).build(xml, null);

  } catch (ValidityException vex) {
    cache.getLogger().error("Could not parse XML when creating XMLEntity", vex);

  } catch (ParsingException pex) {
    cache.getLogger().error("Could not parse XML when creating XMLEntity", pex);
    
  } catch (IOException ioex) {
    cache.getLogger().error("Could not parse XML when creating XMLEntity", ioex);
  }
  
  Nodes nodes = document.query(createQueryString(element, attributes));
  if (nodes.size() != 0) {
    return nodes.get(0).toXML();
  }
  
  cache.getLogger().warning("No XML definition could be found with name=" + element + " and attributes=" + attributes);
  return null;
}
 
Example #6
Source File: XmlEntity.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Use the CacheXmlGenerator to create XML from the entity associated with
 * the current cache.
 * 
 * @param element Name of the XML element to search for.
 * @param attributes
 *          Attributes of the element that should match, for example "name" or
 *          "id" and the value they should equal.
 * 
 * @return XML string representation of the entity.
 */
private final String loadXmlDefinition(final String element, final Map<String, String> attributes) {
  final Cache cache = CacheFactory.getAnyInstance();
  Document document = null;

  try {
    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);
    CacheXmlGenerator.generate(cache, printWriter, false, false, false);
    printWriter.close();

    // Remove the DOCTYPE line when getting the string to prevent
    // errors when trying to locate the DTD.
    String xml = stringWriter.toString().replaceFirst("<!DOCTYPE.*>", "");
    document = new Builder(false).build(xml, null);

  } catch (ValidityException vex) {
    cache.getLogger().error("Could not parse XML when creating XMLEntity", vex);

  } catch (ParsingException pex) {
    cache.getLogger().error("Could not parse XML when creating XMLEntity", pex);
    
  } catch (IOException ioex) {
    cache.getLogger().error("Could not parse XML when creating XMLEntity", ioex);
  }
  
  Nodes nodes = document.query(createQueryString(element, attributes));
  if (nodes.size() != 0) {
    return nodes.get(0).toXML();
  }
  
  cache.getLogger().warning("No XML definition could be found with name=" + element + " and attributes=" + attributes);
  return null;
}
 
Example #7
Source File: XmlPersistenceRead.java    From rest-client with Apache License 2.0 5 votes vote down vote up
protected Document getDocumentFromFile(final File f)
        throws IOException, XMLException {
    try {
        Builder parser = new Builder();
        Document doc = parser.build(f);
        return doc;
    }
    catch (ParsingException | IOException ex) {
        throw new XMLException(ex.getMessage(), ex);
    }
}
 
Example #8
Source File: ResponseCommand.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void verify(CommandCall commandCall, Evaluator evaluator, ResultRecorder resultRecorder) {
  ValidationResult validationResult;
  if (!StringUtils.isBlank(verificationMethod)) {
    evaluator.setVariable("#nl_knaw_huygens_httpcommand_result", requestCommand.getActualResult());
    evaluator.setVariable("#nl_knaw_huygens_httpcommand_expectation", expectation);
    validationResult = (ValidationResult) evaluator.evaluate(
      verificationMethod + "(#nl_knaw_huygens_httpcommand_expectation, #nl_knaw_huygens_httpcommand_result)"
    );
    evaluator.setVariable("#nl_knaw_huygens_httpcommand_result", null);
    evaluator.setVariable("#nl_knaw_huygens_httpcommand_expectation", null);
  } else {
    validationResult = defaultValidator.validate(expectation, requestCommand.getActualResult());
  }

  Element caption = null;
  if (addCaptions) {
    caption = new Element("div").addAttribute("class", "responseCaption").appendText("Response:");
  }

  Element resultElement = replaceWithEmptyElement(commandCall.getElement(), name, namespace, caption);
  addClass(resultElement, "responseContent");

  try {
    Builder builder = new Builder();
    Document document = builder.build(new StringReader(validationResult.getMessage()));
    //new Element() creates a deepcopy not attached to the doc
    nu.xom.Element rootElement = new nu.xom.Element(document.getRootElement());
    resultElement.appendChild(new Element(rootElement));
    resultRecorder.record(validationResult.isSucceeded() ? Result.SUCCESS : Result.FAILURE);
  } catch (ParsingException | IOException e) {
    resultRecorder.record(Result.FAILURE);
    if (e instanceof ParsingException) {
      resultElement.appendText(
        "Error at line " + ((ParsingException) e).getLineNumber() +
          ", column: " + ((ParsingException) e).getColumnNumber());
      resultElement.appendText(validationResult.getMessage());
    }
  }
}
 
Example #9
Source File: XomDriver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @deprecated As of 1.4.9, use {@link #XomDriver()} and overload {@link #createBuilder()} instead
 */
public XomDriver(Builder builder) {
    this(builder, new XmlFriendlyNameCoder());
}
 
Example #10
Source File: XomDriver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @since 1.4
 * @deprecated As of 1.4.9, use {@link #XomDriver(NameCoder)} and overload {@link #createBuilder()} instead
 */
public XomDriver(Builder builder, NameCoder nameCoder) {
    super(nameCoder);
    this.builder = builder;
}
 
Example #11
Source File: XomDriver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @deprecated As of 1.4.9, overload {@link #createBuilder()} instead
 */
protected Builder getBuilder() {
    return this.builder;
}
 
Example #12
Source File: XomDriver.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * @since 1.2
 * @deprecated As of 1.4, use {@link #XomDriver(NameCoder)} and overload {@link #createBuilder()} instead
 */
public XomDriver(Builder builder, XmlFriendlyReplacer replacer) {
    this(builder, (NameCoder)replacer);
}
 
Example #13
Source File: XomDriver.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Create the Builder instance.
 *
 * A XOM builder is a wrapper around a {@link org.xml.sax.XMLReader}
 * instance which is not thread-safe by definition. Therefore each reader
 * should use its own builder instance to avoid concurrency problems.
 *
 * Overload this method to configure the generated builder instances e.g.
 * to activate validation.
 *
 * @return the new builder
 * @since 1.4.9
 */
protected Builder createBuilder() {
    final Builder builder = getBuilder();
    return builder != null ? builder : new Builder();
}