org.jdom.input.SAXBuilder Java Examples

The following examples show how to use org.jdom.input.SAXBuilder. 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: JDOMParser.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
public Object parseXML(InputStream stream) {
    if (!isNamespaceAware()) {
        throw new JXPathException("JDOM parser configuration error. JDOM "
                + "does not support the namespaceAware=false setting.");
    }

    try {
        SAXBuilder builder = new SAXBuilder();
        builder.setExpandEntities(isExpandEntityReferences());
        builder.setIgnoringElementContentWhitespace(
                isIgnoringElementContentWhitespace());
        builder.setValidation(isValidating());
        return builder.build(stream);
    }
    catch (Exception ex) {
        throw new JXPathException("JDOM parser error", ex);
    }
}
 
Example #2
Source File: SimpleLanguageTranslator.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Perform minimal parsing of translatorSpecFile and return new instance of
 * a SimpleLanguageTranslator.
 * 
 * @param translatorSpecFile
 * @return new SimpleLanguageTranslator instance which has not been
 *         validated.
 * @throws IOException
 * @throws JDOMException
 * @throws SAXException
 * @see #isValid
 */
static SimpleLanguageTranslator getSimpleLanguageTranslator(ResourceFile translatorSpecFile)
		throws SAXException, JDOMException, IOException {

	InputStream is = new BufferedInputStream(translatorSpecFile.getInputStream());
	try {
		SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
		Document document = sax.build(is);
		Element root = document.getRootElement();
		return getSimpleLanguageTranslator(translatorSpecFile.getAbsolutePath(), root);

	}
	finally {
		try {
			is.close();
		}
		catch (IOException e1) {
			// ignore
		}
	}
}
 
Example #3
Source File: DWARFRegisterMappingsManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the DWARF register mapping information file specified in the
 * specified language's LDEF file and returns a new
 * {@link DWARFRegisterMappings} object containing the data read from that
 * file.
 * <p>
 * Throws {@link IOException} if the lang does not have a mapping or it is
 * invalid.
 * <p>
 * 
 * @param lang {@link Language} to read the matching DWARF register mappings
 *            for
 * @return a new {@link DWARFRegisterMappings} instance, created from
 *         information read from the {@link #DWARF_REGISTER_MAPPING_NAME}
 *         xml file referenced in the language's LDEF, never null.
 * @throws IOException if there is no DWARF register mapping file associated
 *             with the specified {@link Language} or if there was an error
 *             in the register mapping data.
 */
public static DWARFRegisterMappings readMappingForLang(Language lang) throws IOException {
	ResourceFile dwarfFile = getDWARFRegisterMappingFileFor(lang);
	if (!dwarfFile.exists()) {
		throw new IOException("Missing DWARF register mapping file " + dwarfFile +
			" for language " + lang.getLanguageID().getIdAsString());
	}

	SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
	try (InputStream fis = dwarfFile.getInputStream()) {
		Document doc = sax.build(fis);
		Element rootElem = doc.getRootElement();
		return readMappingFrom(rootElem, lang);
	}
	catch (JDOMException | IOException e) {
		Msg.error(DWARFRegisterMappingsManager.class,
			"Bad DWARF register mapping file " + dwarfFile, e);
		throw new IOException("Failed to read DWARF register mapping file " + dwarfFile, e);
	}
}
 
Example #4
Source File: NodesLoader.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(null, root);
	} catch (Exception e) {
		exceptions.add(e);
	}

	return exceptions;
}
 
Example #5
Source File: BeastImporter.java    From beast-mcmc with GNU Lesser General Public License v2.1 6 votes vote down vote up
public BeastImporter(Reader reader) throws IOException, JDOMException, Importer.ImportException {
        SAXBuilder builder = new SAXBuilder();

        Document doc = builder.build(reader);
        root = doc.getRootElement();
        if (!root.getName().equalsIgnoreCase("beast")) {
            throw new Importer.ImportException("Unrecognized root element in XML file");
        }

        dateFormat = DateFormat.getDateInstance(java.text.DateFormat.SHORT, Locale.UK);
        dateFormat.setLenient(true);

        Calendar cal = Calendar.getInstance(Locale.getDefault());

        // set uses a zero based month (Jan = 0):
        cal.set(0000, 00, 01);
//        origin = cal.getTime();

        cal.setTimeInMillis(0);
        origin = cal.getTime();
    }
 
Example #6
Source File: MaskFormActions.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
private void importMasksFromXml(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_MASK);
        final Product product = getMaskForm().getProduct();
        for (final Element child : children) {
            final DimapPersistable persistable = DimapPersistence.getPersistable(child);
            if (persistable != null) {
                final Mask mask = (Mask) persistable.createObjectFromXml(child, product, null);
                addMaskToProductIfPossible(mask, product);
            }
        }
    } catch (Exception e) {
        showErrorDialog(String.format("Failed to import mask(s): %s", e.getMessage()));
    }
}
 
Example #7
Source File: TraceVisualizationTest.java    From microrts with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String []args) throws Exception {
 boolean zip = false;
 
 Trace t;
 if(zip){
  ZipInputStream zipIs=new ZipInputStream(new FileInputStream(args[0]));
  zipIs.getNextEntry();
  t = new Trace(new SAXBuilder().build(zipIs).getRootElement());
 }else{ 
  t = new Trace(new SAXBuilder().build(args[0]).getRootElement());
 }
 
 JFrame tv = TraceVisualizer.newWindow("Demo", 800, 600, t, 1);
 tv.show();
        
        System.out.println("Trace winner: " + t.winner());
}
 
Example #8
Source File: StandAloneApplication.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Element getDefaultToolElement() {
	try {
		InputStream instream = ResourceManager.getResourceAsStream(DEFAULT_TOOL_NAME);
		if (instream == null) {
			return null;
		}

		SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
		Element root = sax.build(instream).getRootElement();
		return root;
	}
	catch (Exception e) {
		Msg.showError(getClass(), null, "Error Reading Tool",
			"Could not read tool: " + DEFAULT_TOOL_NAME, e);
	}
	return null;
}
 
Example #9
Source File: ToolActionManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Create the Template object and add it to the tool chest.
 */
private void addToolTemplate(InputStream instream, String path) {
	try {
		SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false);
		Element root = sax.build(instream).getRootElement();

		ToolTemplate template = new GhidraToolTemplate(root, path);
		if (plugin.getActiveProject().getLocalToolChest().addToolTemplate(template)) {
			Msg.info(this,
				"Successfully added " + template.getName() + " to project tool chest.");
		}
		else {
			Msg.warn(this, "Could not add " + template.getName() + " to project tool chest.");
		}
	}
	catch (Exception e) {
		Msg.showError(getClass(), tool.getToolFrame(), "Error Reading Tool",
			"Could not read tool: " + e, e);
	}
}
 
Example #10
Source File: BeastImporter.java    From beast-mcmc with GNU Lesser General Public License v2.1 6 votes vote down vote up
public BeastImporter(Reader reader) throws IOException, JDOMException, Importer.ImportException {
        SAXBuilder builder = new SAXBuilder();

        Document doc = builder.build(reader);
        root = doc.getRootElement();
        if (!root.getName().equalsIgnoreCase("beast")) {
            throw new Importer.ImportException("Unrecognized root element in XML file");
        }

        dateFormat = DateFormat.getDateInstance(java.text.DateFormat.SHORT, Locale.UK);
        dateFormat.setLenient(true);

        Calendar cal = Calendar.getInstance(Locale.getDefault());

        // set uses a zero based month (Jan = 0):
        cal.set(0000, 00, 01);
//        origin = cal.getTime();

        cal.setTimeInMillis(0);
        origin = cal.getTime();
    }
 
Example #11
Source File: MarketUpdate.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public MarketUpdate ( String xml, boolean isNew ) {

    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try {
        Reader string_reader = new StringReader(xml);
        doc = builder.build(string_reader);
    } catch (Exception e) {
        System.out.println("Caught exception during XML parsing of a Trade");
        e.printStackTrace();
    }

    Element root_element = doc.getRootElement ();
    this.ccy          = getStringElement(root_element, "ccy");
    this.ValueDate        = getStringElement(root_element, "ValueDate");
    this.value          = getDoubleElement(root_element, "value");
    this.spot           = getDoubleElement(root_element, "spot");
    this.discount_factor    = getDoubleElement(root_element, "discount_factor");

    this.tickId         = getIntegerElement(root_element, "TickId" );
    //this.wanIdentity = wanIdentity;
    this.isNew = isNew;
  }
 
Example #12
Source File: RuleAttributeXmlExporter.java    From rice with Educational Community License v2.0 6 votes vote down vote up
private void exportRuleAttribute(Element parent, RuleAttribute ruleAttribute) {
    Element attributeElement = renderer.renderElement(parent, RULE_ATTRIBUTE);
    renderer.renderTextElement(attributeElement, NAME, ruleAttribute.getName());
    renderer.renderTextElement(attributeElement, CLASS_NAME, ruleAttribute.getResourceDescriptor());
    renderer.renderTextElement(attributeElement, LABEL, ruleAttribute.getLabel());
    renderer.renderTextElement(attributeElement, DESCRIPTION, ruleAttribute.getDescription());
    renderer.renderTextElement(attributeElement, TYPE, ruleAttribute.getType());
    renderer.renderTextElement(attributeElement, APPLICATION_ID, ruleAttribute.getApplicationId());
    if (!org.apache.commons.lang.StringUtils.isEmpty(ruleAttribute.getXmlConfigData())) {
        try {
            Document configDoc = new SAXBuilder().build(new StringReader(ruleAttribute.getXmlConfigData()));
            XmlHelper.propagateNamespace(configDoc.getRootElement(), RULE_ATTRIBUTE_NAMESPACE);
            attributeElement.addContent(configDoc.getRootElement().detach());
        } catch (Exception e) {
        	LOG.error("Error parsing attribute XML configuration.", e);
            throw new WorkflowRuntimeException("Error parsing attribute XML configuration.");
        }
    }
}
 
Example #13
Source File: SAXBuilder_JDOMTest.java    From learnjavabug with MIT License 6 votes vote down vote up
public static void main(String[] args) throws JDOMException, IOException {
    //todo 存在xxe漏洞
    SAXBuilder saxBuilder = new SAXBuilder();

    //todo 修复方式1
//    SAXBuilder saxBuilder = new SAXBuilder(true);

    //todo 修复方式2
//    SAXBuilder saxBuilder = new SAXBuilder();
//    saxBuilder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
//    saxBuilder.setFeature("http://xml.org/sax/features/external-general-entities", false);
//    saxBuilder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
//    saxBuilder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Payloads.FEEDBACK.getBytes());
    Document document = saxBuilder.build(byteArrayInputStream);
    Element element = document.getRootElement();
    List<Content> contents = element.getContent();
    for (Content content : contents) {
      System.out.println(content.getValue());
    }
  }
 
Example #14
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 #15
Source File: AnnotationSchema.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Creates an AnnotationSchema object from an XSchema file
  * @param anXSchemaInputStream the Input Stream containing the XSchema file
  */
public void fromXSchema(InputStream anXSchemaInputStream)
            throws ResourceInstantiationException {
  org.jdom.Document jDom = null;
  SAXBuilder saxBuilder = new SAXBuilder(false);
  try {
  try{
    jDom = saxBuilder.build(anXSchemaInputStream);
  }catch(JDOMException je){
    throw new ResourceInstantiationException(je);
  }
  } catch (java.io.IOException ex) {
    throw new ResourceInstantiationException(ex);
  }
  workWithJDom(jDom);
}
 
Example #16
Source File: CreoleRegisterImpl.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Default constructor. Sets up directory files parser. <B>NOTE:</B> only
 * Factory should call this method.
 */
public CreoleRegisterImpl() throws GateException {

  // initialise the various maps

  lrTypes = new HashSet<String>();
  prTypes = new HashSet<String>();
  vrTypes = new LinkedList<String>();
  toolTypes = new HashSet<String>();
  applicationTypes = new HashSet<String>();

  plugins = new LinkedHashSet<Plugin>();

  // construct a SAX parser for parsing the CREOLE directory files
  jdomBuilder = new SAXBuilder(false);
  jdomBuilder.setXMLFilter(new CreoleXmlUpperCaseFilter());

  // read plugin name mappings file
  readPluginNamesMappings();

}
 
Example #17
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 #18
Source File: MarketUpdate.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public MarketUpdate ( String xml, boolean isNew ) {

    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try {
        Reader string_reader = new StringReader(xml);
        doc = builder.build(string_reader);
    } catch (Exception e) {
        System.out.println("Caught exception during XML parsing of a Trade");
        e.printStackTrace();
    }

    Element root_element = doc.getRootElement ();
    this.ccy          = getStringElement(root_element, "ccy");
    this.ValueDate        = getStringElement(root_element, "ValueDate");
    this.value          = getDoubleElement(root_element, "value");
    this.spot           = getDoubleElement(root_element, "spot");
    this.discount_factor    = getDoubleElement(root_element, "discount_factor");

    this.tickId         = getIntegerElement(root_element, "TickId" );
    //this.wanIdentity = wanIdentity;
    this.isNew = isNew;
  }
 
Example #19
Source File: FeatureSpecification.java    From gateplugin-LearningFramework with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Constructor from URL
 * @param configFileURL URL of feature config XML file
 */
public FeatureSpecification(URL configFileURL) {
  url = configFileURL;

  SAXBuilder saxBuilder = new SAXBuilder(false);
  try {
    try {
      jdomDocConf = saxBuilder.build(configFileURL);
      parseConfigXml();
    } catch (JDOMException jde) {
      throw new GateRuntimeException(jde);
    }
  } catch (java.io.IOException ex) {
    throw new GateRuntimeException("Error parsing config file URL " + url, ex);
  }
}
 
Example #20
Source File: PermissionXmlParser.java    From jivejdon with Apache License 2.0 6 votes vote down vote up
private Document buildDocument(String configFileName) {
	Debug.logVerbose(" locate configure file  :" + configFileName, module);
	try {
		InputStream xmlStream = fileLocator.getConfPathXmlStream(configFileName);
		if (xmlStream == null) {
			Debug.logVerbose("can't locate file:" + configFileName, module);
			return null;
		} else {
			Debug.logVerbose(" configure file found :" + xmlStream, module);
		}

		SAXBuilder builder = new SAXBuilder();
		builder.setEntityResolver(new DTDEntityResolver());
		Document doc = builder.build(xmlStream);
		Debug.logVerbose(" got mapping file ", module);
		return doc;
	} catch (Exception e) {
		Debug.logError(" JDOMException error: " + e, module);
		return null;
	}
}
 
Example #21
Source File: IndexCreator.java    From icure-backend with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void createIndex() throws JDOMException, IOException, MappingException, ClassNotFoundException {
	buildAnalyzerMap();
	SAXBuilder builder = new SAXBuilder();
	Document doc = builder.build(config);
	Element root = doc.getRootElement();
	SessionFactory sf = createSessionFactory(root.getAttributeValue("url"),
			root.getAttributeValue("login"),
			root.getAttributeValue("passwd"),
			root.getAttributeValue("dialect"),
			root.getAttributeValue("driverClass"),
			root.getAttributeValue("mappedClasses"));
	Directory indexDir = FSDirectory.open(new File(output));

	Version lucene47 = Version.LUCENE_47;
	IndexWriter writer = new IndexWriter(indexDir,new IndexWriterConfig(lucene47,new StandardAnalyzer(lucene47)));
	for (Element classToIndex:(Collection<Element>)root.getChildren("index-class")) {
		processClass(classToIndex,writer,sf);
	}
	log.info("Closing index");
	writer.close();
	log.info("All done!");
}
 
Example #22
Source File: StaticWithJdomTest.java    From powermock-examples-maven with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void test() throws Exception {

    PowerMock.mockStatic(StaticClass.class);
    EasyMock.expect(StaticClass.staticMethod()).andReturn(2).anyTimes();
    PowerMock.replay(StaticClass.class);

    int i = StaticClass.staticMethod();

    String xml = "<xml>" + i + "</xml>";
    SAXBuilder b = new SAXBuilder();

    Document d = b.build(new StringReader(xml));
    Assert.assertTrue(d.getRootElement().getText().equals("2"));
    PowerMock.verify(StaticClass.class);
}
 
Example #23
Source File: IndexCreator.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void createIndex() throws JDOMException, IOException, MappingException, ClassNotFoundException {
	buildAnalyzerMap();
	SAXBuilder builder = new SAXBuilder();
	Document doc = builder.build(config);
	Element root = doc.getRootElement();
	SessionFactory sf = createSessionFactory(root.getAttributeValue("url"),
			root.getAttributeValue("login"),
			root.getAttributeValue("passwd"),
			root.getAttributeValue("dialect"),
			root.getAttributeValue("driverClass"),
			root.getAttributeValue("mappedClasses"));
	Directory indexDir = FSDirectory.open(new File(output));

	Version lucene47 = Version.LUCENE_47;
	IndexWriter writer = new IndexWriter(indexDir,new IndexWriterConfig(lucene47,new StandardAnalyzer(lucene47)));
	for (Element classToIndex:(Collection<Element>)root.getChildren("index-class")) {
		processClass(classToIndex,writer,sf);
	}
	log.info("Closing index");
	writer.close();
	log.info("All done!");
}
 
Example #24
Source File: RealmVerifierTest.java    From openid4java with Apache License 2.0 5 votes vote down vote up
public void testXmlFile() throws IOException, JDOMException
{
    InputStream in = new BufferedInputStream(
            new FileInputStream(_testDataPath + "/server/" + TEST_DATA_FILE));

    assertNotNull("XML data file could not be loaded: " + TEST_DATA_FILE, in);

    SAXBuilder saxBuilder = new SAXBuilder();
    Document document = saxBuilder.build(in);
    Element testSuite = document.getRootElement();
    List tests = testSuite.getChildren("test");
    for (int i = 0; i < tests.size(); i++)
    {
        Element test = (Element) tests.get(i);

        String result = test.getAttributeValue("result");
        String realm = test.getAttributeValue("realm");
        String returnTo = test.getAttributeValue("returnTo");
        String message = test.getAttributeValue("message");

        Integer resultCode = (Integer) _resultCodes.get(result);

        if (message == null)
            assertEquals(resultCode.intValue(), _realmVerifier.match(realm, returnTo));
        else
            assertEquals(message, resultCode.intValue(), _realmVerifier.match(realm, returnTo));
    }
}
 
Example #25
Source File: TestPretrainedBayesianModel.java    From microrts with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {   
        UnitTypeTable utt = new UnitTypeTable();
        FeatureGenerator fg = new FeatureGeneratorSimple();
        
//        test(new BayesianModelByUnitTypeWithDefaultModel(new SAXBuilder().build(
//             "data/bayesianmodels/pretrained/ActionInterdependenceModel-WR.xml").getRootElement(), utt,
//             new ActionInterdependenceModel(null, 0, 0, 0, utt, fg)), 
//             "data/bayesianmodels/trainingdata/learning-traces-500","AI0", utt, fg);
        test(new BayesianModelByUnitTypeWithDefaultModel(new SAXBuilder().build(
             "data/bayesianmodels/pretrained/ActionInterdependenceModel-WR.xml").getRootElement(), utt,
             new ActionInterdependenceModel(null, 0, 0, 0, utt, fg, ""), "AIM_WR"), 
             "data/bayesianmodels/trainingdata/learning-traces-500","AI0", utt, fg);
    }
 
Example #26
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 #27
Source File: Trade.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public Trade(String xml) throws JDOMException, IOException  {
  // actually parse the xml here
  SAXBuilder builder = new SAXBuilder();
  Document doc = null;
  try {
      Reader string_reader = new StringReader(xml);
      doc = builder.build(string_reader);
  } catch (Exception e) {
      System.out.println("Caught exception during XML parsing of a Trade");
      e.printStackTrace();
  }

  Element root_element = doc.getRootElement ();

  TradeId                 = getIntegerElement(root_element, "TradeId");
  Trader                  = getStringElement(root_element, "Trader").trim();
  Entity                  = getStringElement(root_element, "Entity").trim();
  Currency                = getStringElement(root_element, "Currency");
  Amount                  = getDoubleElement(root_element, "Amount");
  ContractRate            = getDoubleElement(root_element, "ContractRate");
  CtrCurrency             = getStringElement(root_element, "CtrCurrency");
  //TODO The trade file is missing this property, we will need to get an update.  Use 1 for now.
  //BaseUSEquiv             = getDoubleElement(root_element, "BaseUSEquiv");
  BaseUSEquiv = 1;
  CcyDollarDiscountFactor = getDoubleElement(root_element, "CcyDollarDiscountFactor");
  CcySpotRate             = getDoubleElement(root_element, "CcySpotRate");
  TradeDate               = getStringElement(root_element, "TradeDate");
  ValueDate               = getStringElement(root_element, "ValueDate");
  counterparty      = getStringElement(root_element, "CounterParty" ).trim();

  ctr_amt = Amount*ContractRate*-1;
  ctr_us_equiv = 1.0/(ContractRate/BaseUSEquiv);
  if("USD".equals(CtrCurrency))ctr_spot = 1.0;
  else ctr_spot = 1.0/(ContractRate/CcySpotRate);
}
 
Example #28
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 #29
Source File: ClassPathXmlApplicationContext.java    From tastjava with MIT License 5 votes vote down vote up
public ClassPathXmlApplicationContext() throws Exception {
    SAXBuilder builder = new SAXBuilder();

    String basedir = this.getClass().getClassLoader().getResource("/").getPath();

    File xmlFile = new File(basedir + "beans.xml");
    // 构造文档对象
    Document document = builder.build(xmlFile);
    // 获取根元素
    Element root = document.getRootElement();
    // 取到根元素所有元素
    List list = root.getChildren();

    setBeans(list);
}
 
Example #30
Source File: XMLUtil.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
 * @param strxml
 * @return
 * @throws JDOMException
 * @throws IOException
 */
public static Map doXMLParse(String strxml) throws JDOMException, IOException {
	strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

	if(null == strxml || "".equals(strxml)) {
		return null;
	}
	
	Map m = new HashMap();
	
	InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
	SAXBuilder builder = new SAXBuilder();
	Document doc = builder.build(in);
	Element root = doc.getRootElement();
	List list = root.getChildren();
	Iterator it = list.iterator();
	while(it.hasNext()) {
		Element e = (Element) it.next();
		String k = e.getName();
		String v = "";
		List children = e.getChildren();
		if(children.isEmpty()) {
			v = e.getTextNormalize();
		} else {
			v = XMLUtil.getChildrenText(children);
		}
		
		m.put(k, v);
	}
	
	//关闭流
	in.close();
	
	return m;
}