Java Code Examples for org.jdom.input.SAXBuilder#build()

The following examples show how to use org.jdom.input.SAXBuilder#build() . 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: ApplicationIcons.java    From jbt with Apache License 2.0 6 votes vote down vote up
private static List<Exception> parseStandardNodesFile(FileInputStream file) {
	List<Exception> exceptions = new Vector<Exception>();

	SAXBuilder builder = new SAXBuilder();
	try {
		Document doc = builder.build(file);

		Element root = doc.getRootElement();

		parseElement(root);
	} catch (Exception e) {
		exceptions.add(e);
	}

	return exceptions;
}
 
Example 2
Source File: Xxe_jdom.java    From openrasp-testcases with MIT License 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String data = req.getParameter("data");
    String tmp = "";
    if (data != null) {
        try {
            SAXBuilder saxBuilder = new SAXBuilder();
            Document document = saxBuilder.build(new InputSource(new StringReader(data)));
            Element rootElement = document.getRootElement();
            tmp = rootElement.getChildText("foo");
            resp.getWriter().println(tmp);
        } catch (Exception e) {
            resp.getWriter().println(e);
        }
    }
}
 
Example 3
Source File: MaskFormActions.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
private void importMasksFromBmdx(File file) {
    try {
        final SAXBuilder saxBuilder = new SAXBuilder();
        final Document document = saxBuilder.build(file);
        final Element rootElement = document.getRootElement();
        @SuppressWarnings({"unchecked"})
        final List<Element> children = rootElement.getChildren(DimapProductConstants.TAG_BITMASK_DEFINITION);
        final Product product = getMaskForm().getProduct();
        for (Element element : children) {
            Mask mask = Mask.BandMathsType.createFromBitmaskDef(element,
                                                                product.getSceneRasterWidth(),
                                                                product.getSceneRasterHeight());
            product.getMaskGroup().add(mask);
        }
    } catch (Exception e) {
        showErrorDialog(String.format("Failed to import mask(s): %s", e.getMessage()));
    }
}
 
Example 4
Source File: CharsetInfo.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void readConfigFile() {
	ResourceFile xmlFile = Application.findDataFileInAnyModule("charset_info.xml");
	try (InputStream xmlInputStream = xmlFile.getInputStream()) {
		SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
		Document doc = sax.build(xmlInputStream);
		Element root = doc.getRootElement();
		for (Element child : (List<Element>) root.getChildren("charset")) {
			try {
				String name = child.getAttributeValue("name");
				if (name == null || name.trim().isEmpty()) {
					throw new IOException("Bad charset definition in " + xmlFile);
				}
				if (!Charset.isSupported(name)) {
					Msg.warn(this,
						"Unsupported charset defined in " + xmlFile.getName() + ": " + name);
				}

				int charSize = XmlUtilities.parseBoundedIntAttr(child, "charSize", 1, 8);

				addCharset(name, charSize);
			}
			catch (NumberFormatException nfe) {
				throw new IOException("Invalid charset definition in " + xmlFile);
			}
		}
	}
	catch (JDOMException | IOException e) {
		Msg.showError(this, null, "Error reading charset data", e.getMessage(), e);
	}

}
 
Example 5
Source File: MessageNotifierConfigDOM.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the Xml element from a given text.
 * @param xmlText The text containing an Xml.
 * @return The Xml element from a given text.
 * @throws ApsSystemException In case of parsing exceptions.
 */
protected Element getRootElement(String xmlText) throws ApsSystemException {
	SAXBuilder builder = new SAXBuilder();
	builder.setValidation(false);
	StringReader reader = new StringReader(xmlText);
	Element root = null;
	try {
		Document doc = builder.build(reader);
		root = doc.getRootElement();
	} catch (Throwable t) {
		ApsSystemUtils.getLogger().error("Error parsing xml: " + t.getMessage());
		throw new ApsSystemException("Error parsing xml", t);
	}
	return root;
}
 
Example 6
Source File: PmdProfileImporter.java    From sonar-p3c-pmd with MIT License 5 votes vote down vote up
protected PmdRuleset parsePmdRuleset(Reader pmdConfigurationFile, ValidationMessages messages) {
  try {
    SAXBuilder parser = new SAXBuilder();
    Document dom = parser.build(pmdConfigurationFile);
    Element eltResultset = dom.getRootElement();
    Namespace namespace = eltResultset.getNamespace();
    PmdRuleset pmdResultset = new PmdRuleset();
    for (Element eltRule : getChildren(eltResultset, "rule", namespace)) {
      PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue("ref"));
      pmdRule.setClazz(eltRule.getAttributeValue("class"));
      pmdRule.setName(eltRule.getAttributeValue("name"));
      pmdRule.setMessage(eltRule.getAttributeValue("message"));
      parsePmdPriority(eltRule, pmdRule, namespace);
      parsePmdProperties(eltRule, pmdRule, namespace);
      pmdResultset.addRule(pmdRule);
    }
    return pmdResultset;
  } catch (Exception e) {
    String errorMessage = "The PMD configuration file is not valid";
    messages.addErrorText(errorMessage + " : " + e.getMessage());
    LOG.error(errorMessage, e);
    return new PmdRuleset();
  }
}
 
Example 7
Source File: ShortcutDefDOM.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void decodeDOM(String xmlText) throws ApsSystemException {
	SAXBuilder builder = new SAXBuilder();
	builder.setValidation(false);
	StringReader reader = new StringReader(xmlText);
	try {
		this._doc = builder.build(reader);
	} catch (Throwable t) {
		_logger.error("Error while parsing. xml: {} ", xmlText,t);
		throw new ApsSystemException("Error detected while parsing the XML", t);
	}
}
 
Example 8
Source File: SimpleLanguageTranslatorTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private SimpleLanguageTranslator readSimpleLanguageTranslator(String translatorXML)
		throws Exception {
	Reader r = new StringReader(translatorXML);
	SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
	Document document = sax.build(r);
	Element root = document.getRootElement();
	return SimpleLanguageTranslator.getSimpleLanguageTranslator("test-XML", root);
}
 
Example 9
Source File: SeoPageExtraConfigDOM.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Document decodeComplexParameterDOM(String xml) {
    Document doc = null;
    SAXBuilder builder = new SAXBuilder();
    builder.setValidation(false);
    StringReader reader = new StringReader(xml);
    try {
        doc = builder.build(reader);
    } catch (Throwable t) {
        _logger.error("Error while parsing xml: {}", xml, t);
    }
    return doc;
}
 
Example 10
Source File: AbstractSamlObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Construct document from xml string.
 *
 * @param xmlString the xml string
 * @return the document
 */
public static Document constructDocumentFromXml(final String xmlString) {
    try {
        final SAXBuilder builder = new SAXBuilder();
        builder.setFeature("http://xml.org/sax/features/external-general-entities", false);
        builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        return builder
                .build(new ByteArrayInputStream(xmlString.getBytes(Charset.defaultCharset())));
    } catch (final Exception e) {
        return null;
    }
}
 
Example 11
Source File: PageExtraConfigDOM.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Document decodeDOM(String xml) throws ApsSystemException {
	Document doc = null;
	SAXBuilder builder = new SAXBuilder();
	builder.setValidation(false);
	StringReader reader = new StringReader(xml);
	try {
		doc = builder.build(reader);
	} catch (Throwable t) {
		_logger.error("Error while parsing xml: {} ", xml, t);
		throw new ApsSystemException("Error detected while parsing the XML", t);
	}
	return doc;
}
 
Example 12
Source File: GuestDefinition.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new VM definition from a libvirt XML description.
 *
 * @param xmlDef libvirt XML domain definition
 * @param vmInfo output of virt.vm_info to be merged with the XML guest definition
 * @return parsed definition or {@code null}
 */
@SuppressWarnings("unchecked")
public static GuestDefinition parse(String xmlDef, Optional<VmInfoJson> vmInfo) {
    GuestDefinition def = null;
    SAXBuilder builder = new SAXBuilder();
    builder.setValidation(false);

    try {
        Document doc = builder.build(new StringReader(xmlDef));
        def = new GuestDefinition();

        Element domainElement = doc.getRootElement();
        def.type = domainElement.getAttributeValue("type");
        def.setName(domainElement.getChildText("name"));
        def.uuid = domainElement.getChildText("uuid");
        def.setMemory(parseMemory(domainElement.getChild("currentMemory")));
        def.setMaxMemory(parseMemory(domainElement.getChild("memory")));

        def.vcpu = GuestVcpuDef.parse(domainElement.getChild("vcpu"));
        def.os = GuestOsDef.parse(domainElement.getChild("os"));

        Element devices = domainElement.getChild("devices");
        def.graphics = GuestGraphicsDef.parse(devices.getChild("graphics"));

        def.interfaces = ((List<Element>)devices.getChildren("interface")).stream()
                .map(node -> GuestInterfaceDef.parse(node)).collect(Collectors.toList());
        def.disks = ((List<Element>)devices.getChildren("disk")).stream()
                .map(node -> GuestDiskDef.parse(node, vmInfo)).collect(Collectors.toList());
    }
    catch (Exception e) {
        LOG.error("failed to parse libvirt XML definition: " + e.getMessage());
    }

    return def;
}
 
Example 13
Source File: XMLUtils.java    From payment with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map parseToMap(String strxml, String encoding) throws JDOMException, IOException {
	//strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

	if(null == strxml || "".equals(strxml)) {
		return null;
	}
	
	if(encoding == null || encoding.isEmpty())
		encoding = "UTF-8";
	Map m = new HashMap();
	
	InputStream in = new ByteArrayInputStream(strxml.getBytes(encoding));
	SAXBuilder builder = new SAXBuilder();
	Document doc = builder.build(in);
	Element root = doc.getRootElement();
	List list = root.getChildren();
	for (Object aList : list) {
		org.jdom.Element e = (org.jdom.Element) aList;
		String k = e.getName();
		String v;
		List children = e.getChildren();
		if (children.isEmpty()) {
			v = e.getTextNormalize();
		} else {
			v = getChildrenText(children);
		}

		m.put(k, v);
	}

	in.close();
	
	return m;
}
 
Example 14
Source File: XMLProperties.java    From jivejdon with Apache License 2.0 5 votes vote down vote up
public XMLProperties(Reader reader) {
	try {
		SAXBuilder builder = new SAXBuilder();
		// Strip formatting
		DataUnformatFilter format = new DataUnformatFilter();
		builder.setXMLFilter(format);
		doc = builder.build(reader);
	} catch (Exception e) {
		System.err.println("Error creating XML parser in " + "PropertyManager.java"  + " fileName=" + reader.toString());
		e.printStackTrace();
	}
}
 
Example 15
Source File: YahooPlaceFinderGeocoderService.java    From geomajas-project-server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Call the Yahoo! PlaceFinder service for a result.
 * 
 * @param q
 *            search string
 * @param maxRows
 *            max number of rows in result, or 0 for all
 * @param locale
 *            locale for strings
 * @return list of found results
 * @throws Exception
 *             oops
 * @see <a
 *      href="http://developer.yahoo.com/boss/geo/docs/free_YQL.html#table_pf">Yahoo!
 *      Boss Geo PlaceFinder</a>
 */
public List<GetLocationResult> search(String q, int maxRows, Locale locale)
		throws Exception {
	List<GetLocationResult> searchResult = new ArrayList<GetLocationResult>();

	String url = URLEncoder.encode(q, "UTF8");
	url = "q=select%20*%20from%20geo.placefinder%20where%20text%3D%22"
			+ url + "%22";
	if (maxRows > 0) {
		url = url + "&count=" + maxRows;
	}
	url = url + "&flags=GX";
	if (null != locale) {
		url = url + "&locale=" + locale;
	}
	if (appId != null) {
		url = url + "&appid=" + appId;
	}

	InputStream inputStream = connect(url);
	if (null != inputStream) {
		SAXBuilder parser = new SAXBuilder();
		Document doc = parser.build(inputStream);

		Element root = doc.getRootElement();

		// check code for exception
		String message = root.getChildText("Error");
		// Integer errorCode = Integer.parseInt(message);
		if (message != null && Integer.parseInt(message) != 0) {
			throw new Exception(root.getChildText("ErrorMessage"));
		}
		Element results = root.getChild("results");
		for (Object obj : results.getChildren("Result")) {
			Element toponymElement = (Element) obj;
			GetLocationResult location = getLocationFromElement(toponymElement);
			searchResult.add(location);
		}
	}
	return searchResult;
}
 
Example 16
Source File: NodesLoader.java    From jbt with Apache License 2.0 4 votes vote down vote up
/**
 * Loads the actions and sensors from a MMPM domain file. Creates a new
 * ConceptualNodesTree whose root category is the short name of the file.
 * The root category contains two sub categories, one for actions (which
 * includes all the actions loaded from the file), and another one for
 * conditions (which contains all the boolean sensors loaded form the file).
 * The tree can be accessed through {@link #getNonStandardNodesTree(String)}
 * , and its nodes can be accessed through {@link #getNode(String, String)}.
 */
public static ConceptualNodesTree loadNonStandardNodes(String fileName) throws IOException {
	FileInputStream fileStream = new FileInputStream(fileName);
	SAXBuilder builder = new SAXBuilder();
	ConceptualNodesTree tree = new ConceptualNodesTree();
	File file = new File(fileName);

	try {
		Document doc = builder.build(fileStream);

		ParsedDomain parsedDomain = new ParsedDomain();
		parsedDomain.init(doc.getRootElement(), null);

		List<ParsedAction> actions = parsedDomain.getActionSet().getAction();

		List<ParsedMethod> conditions = parsedDomain.getSensorSet().getMethods();

		for (ParsedAction action : actions) {
			ConceptualBTNode xmlAction = loadNonStandardAction(action);
			nonStandardNodes.put(
					new Pair<String, String>(xmlAction.getType(), action.getName()), xmlAction);
			tree.insertNode(
					file.getName() + ConceptualNodesTree.CATEGORY_SEPARATOR + "Actions",
					new ConceptualBTNodeItem(xmlAction));
		}

		for (ParsedMethod condition : conditions) {
			if (condition.getReturnedType() == ActionParameterType.BOOLEAN) {
				ConceptualBTNode xmlCondition = loadNonStandardCondition(condition);
				nonStandardNodes.put(
						new Pair<String, String>(xmlCondition.getType(), condition.getName()),
						xmlCondition);
				tree.insertNode(file.getName() + ConceptualNodesTree.CATEGORY_SEPARATOR
						+ "Conditions", new ConceptualBTNodeItem(xmlCondition));
			}
		}

		nonStandardTrees.put(fileName, tree);
		return tree;
	} catch (Exception e) {
		throw new IOException(e.getMessage(), e);
	}
}
 
Example 17
Source File: Plugin.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Document getCreoleXML() throws Exception {
  SAXBuilder builder = new SAXBuilder(false);
  URL creoleFileURL = new URL(getBaseURL(), "creole.xml");
  return builder.build(creoleFileURL);
}
 
Example 18
Source File: ConfigLoaderUtil.java    From tcSlackBuildNotifier with MIT License 4 votes vote down vote up
public static Element getFullConfigElement(File file) throws JDOMException, IOException{
	SAXBuilder builder = new SAXBuilder();
	builder.setIgnoringElementContentWhitespace(true);
	Document doc = builder.build(file);
	return doc.getRootElement();
}
 
Example 19
Source File: DocumentStorage.java    From ghidra with Apache License 2.0 4 votes vote down vote up
public Document parseDocument(InputStream s) throws JDOMException, IOException {
	SAXBuilder builder = XmlUtilities.createSecureSAXBuilder(false, false);
	Document document = builder.build(s);
	doclist.push_back(document);
	return document;
}
 
Example 20
Source File: StartupActionScriptManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static List<ActionCommand> loadStartActions(Logger logger) throws IOException {
  List<ActionCommand> actionCommands = loadObsoleteActionScriptFile(logger);
  if (!actionCommands.isEmpty()) {
    return actionCommands;
  }

  File file = new File(getStartXmlFilePath());

  if (file.exists()) {
    try {
      SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);

      Document document = builder.build(file);

      Element rootElement = document.getRootElement();
      List<ActionCommand> list = new ArrayList<ActionCommand>();

      for (Element element : rootElement.getChildren()) {
        String name = element.getName();
        if (DeleteCommand.action.equals(name)) {
          String path = element.getAttributeValue("source");
          list.add(new DeleteCommand(new File(path)));
        }
        else if (UnzipCommand.action.equals(name)) {
          String sourceValue = element.getAttributeValue("source");
          String descriptionValue = element.getAttributeValue("description");
          String filter = element.getAttributeValue("filter");
          FilenameFilter filenameFilter = null;
          if ("import".equals(filter)) {
            Set<String> names = new HashSet<String>();
            for (Element child : element.getChildren()) {
              names.add(child.getTextTrim());
            }
            filenameFilter = new ImportSettingsFilenameFilter(names);
          }

          list.add(new UnzipCommand(new File(sourceValue), new File(descriptionValue), filenameFilter));
        }
      }

      return list;
    }
    catch (Exception e) {
      logger.error(e);
      return Collections.emptyList();
    }
  }
  else {
    logger.warn("No " + ourStartXmlFileName + " file");
    return Collections.emptyList();
  }
}