org.jdom.Document Java Examples

The following examples show how to use org.jdom.Document. 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: 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 #2
Source File: JDOMUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static Element parseDocument(final File f) {
  try {
    final SAXBuilder builder = new SAXBuilder();
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    final Document doc = builder.build(f);
    if (doc == null) {
      return null;
    }

    final Element root = doc.getRootElement();
    return root;
  } catch (final IOException ioe) {
    LOGGER.warn("parse error", ioe);
    return null;
  } catch (final JDOMException jdome) {
    LOGGER.warn("parse error", jdome);
    return null;
  }
}
 
Example #3
Source File: TomcatUsers.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
@Override
public void setupProvider(BlurConfiguration config) throws IOException, JDOMException {
  roleMapper = new RoleMapper(config);
  String usersFile = config.get("blur.console.authentication.provider.tomcat.usersfile");
  SAXBuilder builder = new SAXBuilder();
  Reader in = new FileReader(usersFile);
  Document doc = builder.build(in);
  Element root = doc.getRootElement();
  List<Element> xmlUsers = root.getChildren("user");
  for (Element user : xmlUsers) {
    String username = user.getAttribute("username").getValue();
    String password = user.getAttribute("password").getValue();
    String roles = user.getAttribute("roles").getValue();
    Collection<String> splitRoles = Arrays.asList(roles.split(","));
    users.put(username, new TomcatUser(username, password, roleMapper.mapRoles(splitRoles)));
  }
}
 
Example #4
Source File: JDOMUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static Element readElementFromString(final String xmlData) {
  try {
    final StringReader sr = new StringReader(xmlData);
    final SAXBuilder builder = new SAXBuilder();
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    final Document doc = builder.build(sr);

    if (doc == null) {
      return null;
    }

    final Element root = doc.getRootElement();
    return root;
  } catch (final IOException ioe) {
    LOGGER.info("read error", ioe);
    return null;
  } catch (final JDOMException jdome) {
    LOGGER.info("read error", jdome);
    return null;
  }
}
 
Example #5
Source File: JDOMUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static Element parseDocument(final URL docUrl) {
  try {
    final SAXBuilder builder = new SAXBuilder();
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    builder.setValidation(false);

    final Document doc = builder.build(docUrl);
    if (doc == null) {
      return null;
    }

    final Element root = doc.getRootElement();
    return root;
  } catch (final IOException ioe) {
    LOGGER.warn("parse error", ioe);
    return null;
  } catch (final JDOMException jdome) {
    LOGGER.warn("parse error", jdome);
    return null;
  }
}
 
Example #6
Source File: SCORM12_DocumentHandler.java    From olat with Apache License 2.0 6 votes vote down vote up
protected static boolean canHandle(final Document doc) throws DocumentHandlerException {
    // The first thing we do is to see if there is a root Namespace in the Document
    final Namespace nameSpace = XMLUtils.getDocumentNamespace(doc);

    // No Namespace, sorry we don't know what it is!
    if (nameSpace == null || nameSpace.equals(Namespace.NO_NAMESPACE)) {
        throw new DocumentHandlerException("No Namespace in Document so cannot determine what it is!");
    }

    // Does it have the correct root Namespace?
    if (SUPPORTED_NAMESPACES.containsKey(nameSpace) == false) {
        return false;
    }

    // Now find out if it is a SCORM Document and if so whether we support it
    // We'll search all elements for the ADL Namespace
    final Namespace nsSCORM = getSCORM_Namespace(doc);
    if (nsSCORM == null) {
        return false;
    }

    // Do we support this version of SCORM?
    return SUPPORTED_SCORM_NAMESPACES.containsKey(nsSCORM);
}
 
Example #7
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 #8
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 #9
Source File: JDOMNodePointer.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
/**
 * Get relative position of this among all siblings.
 * @return 1..n
 */
private int getRelativePositionOfElement() {
    Object parent = ((Element) node).getParent();
    if (parent == null) {
        return 1;
    }
    List children;
    if (parent instanceof Element) {
        children = ((Element) parent).getContent();
    }
    else {
        children = ((Document) parent).getContent();
    }
    int count = 0;
    for (int i = 0; i < children.size(); i++) {
        Object child = children.get(i);
        if (child instanceof Element) {
            count++;
        }
        if (child == node) {
            break;
        }
    }
    return count;
}
 
Example #10
Source File: JDOMUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static Element parseDocument(final InputStream is) {
  try {
    final SAXBuilder builder = new SAXBuilder();
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    final Document doc = builder.build(is);
    if (doc == null) {
      return null;
    }

    final Element root = doc.getRootElement();
    return root;
  } catch (final IOException ioe) {
    LOGGER.warn("parse error", ioe);
    return null;
  } catch (final JDOMException jdome) {
    LOGGER.warn("parse error", jdome);
    return null;
  }
}
 
Example #11
Source File: FileEditorManagerTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void openFiles(String s) throws IOException, JDOMException, InterruptedException, ExecutionException {
  Document document = JDOMUtil.loadDocument(s);
  Element rootElement = document.getRootElement();
  ExpandMacroToPathMap map = new ExpandMacroToPathMap();
  map.addMacroExpand(PathMacroUtil.PROJECT_DIR_MACRO_NAME, getTestDataPath());
  map.substitute(rootElement, true, true);

  myManager.loadState(rootElement);

  UIAccess uiAccess = UIAccess.get();
  Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
    @Override
    public void run() {
      myManager.getMainSplitters().openFiles(uiAccess);
    }
  });
  future.get();
}
 
Example #12
Source File: DefaultKeymap.java    From consulo with Apache License 2.0 6 votes vote down vote up
public DefaultKeymap() {
  for(BundledKeymapEP bundledKeymapEP : BundledKeymapEP.EP_NAME.getExtensions()) {
      try {
        InputStream inputStream = bundledKeymapEP.getLoaderForClass().getResourceAsStream(bundledKeymapEP.file + ".xml");
        if(inputStream == null) {
          LOG.warn("Keymap: " + bundledKeymapEP.file + " not found in " + bundledKeymapEP.getPluginDescriptor().getPluginId().getIdString());
          continue;
        }
        Document document = JDOMUtil.loadDocument(inputStream);

        loadKeymapsFromElement(document.getRootElement());
      }
      catch (Exception e) {
        LOG.error(e);
      }
  }
}
 
Example #13
Source File: CreoleRegisterImpl.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void processFullCreoleXmlTree(Plugin plugin,
    Document jdomDoc, CreoleAnnotationHandler annotationHandler)
    throws GateException, IOException, JDOMException {
  // now we can process any annotations on the new classes
  // and augment the XML definition
  annotationHandler.processAnnotations(jdomDoc);

  // debugging
  if(DEBUG) {
    XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
    xmlOut.output(jdomDoc, System.out);
  }

  // finally, parse the augmented definition with the normal parser
  DefaultHandler handler =
      new CreoleXmlHandler(this, plugin);
  SAXOutputter outputter =
      new SAXOutputter(handler, handler, handler, handler);
  outputter.output(jdomDoc);
  if(DEBUG) {
    Out.prln("done parsing " + plugin);
  }
}
 
Example #14
Source File: CreoleAnnotationHandler.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Fetches the directory information for this handler's creole plugin and adds
 * additional RESOURCE elements to the given JDOM document so that it contains
 * a RESOURCE for every resource type defined in the plugin's directory info.
 * 
 * @param jdomDoc
 *          JDOM document which should be the parsed creole.xml that this
 *          handler was configured for.
 */
public void createResourceElementsForDirInfo(Document jdomDoc)
    throws MalformedURLException {
  Element jdomElt = jdomDoc.getRootElement();
  //URL directoryUrl = new URL(creoleFileUrl, ".");
  //DirectoryInfo dirInfo = Gate.getDirectoryInfo(directoryUrl,jdomDoc);
  //if(dirInfo != null) {
    Map<String, Element> resourceElements = new HashMap<String, Element>();
    findResourceElements(resourceElements, jdomElt);
    for(ResourceInfo resInfo : plugin
        .getResourceInfoList()) {
      if(!resourceElements.containsKey(resInfo.getResourceClassName())) {
        // no existing RESOURCE element for this resource type (so it
        // was
        // auto-discovered from a <JAR SCAN="true">), so add a minimal
        // RESOURCE element which will be filled in by the annotation
        // processor.
        jdomElt.addContent(new Element("RESOURCE").addContent(new Element(
            "CLASS").setText(resInfo.getResourceClassName())));
      }
    }
  //}

}
 
Example #15
Source File: MarketLoader.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * NB: duration will be exposed as microseconds
 * <br />the output of this log will include:
  * <br />the time the write of this row was started, the tickId of this market update, and the duration the write took
 *
 */
private void bracketLog(long writeStartTime, long duration, String xml) {
  Document doc = null;
  duration = duration / 1000l;
  try {
    Reader string_reader = new StringReader(xml);
    doc = builder.build(string_reader);
  } catch (Exception e) {
    System.out.println("Caught exception during XML parsing");
    e.printStackTrace();
  }
  root_element = doc.getRootElement();
  String id = getStringElement(root_element, "TickId");
  String timeStamp = formatter.format(new java.util.Date(writeStartTime));
  //logger.info(timeStamp + "," + id + "," + duration);
}
 
Example #16
Source File: RuleRoutingAttribute.java    From rice with Educational Community License v2.0 6 votes vote down vote up
public List<RuleRoutingAttribute> parseDocContent(DocumentContent docContent) {
    try {
        Document doc2 = (Document) XmlHelper.buildJDocument(new StringReader(docContent.getDocContent()));
        
        List<RuleRoutingAttribute> doctypeAttributes = new ArrayList<RuleRoutingAttribute>();
        Collection<Element> ruleRoutings = XmlHelper.findElements(doc2.getRootElement(), "docTypeName");
        List<String> usedDTs = new ArrayList<String>();
        for (Iterator<Element> iter = ruleRoutings.iterator(); iter.hasNext();) {
            Element ruleRoutingElement = (Element) iter.next();

            //Element docTypeElement = ruleRoutingElement.getChild("doctype");
            Element docTypeElement = ruleRoutingElement;
            String elTxt = docTypeElement.getText();
            if (docTypeElement != null && !usedDTs.contains(elTxt)) {
            	usedDTs.add(elTxt);
                doctypeAttributes.add(new RuleRoutingAttribute(elTxt));
            }
        }

        return doctypeAttributes;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
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 #18
Source File: TelegramSettingsManager.java    From teamcity-telegram-plugin with Apache License 2.0 6 votes vote down vote up
private synchronized void reloadConfiguration() throws JDOMException, IOException {
  LOG.info("Loading configuration file: " + configFile);
  Document document = JDOMUtil.loadDocument(configFile.toFile());

  Element root = document.getRootElement();

  TelegramSettings newSettings = new TelegramSettings();
  newSettings.setBotToken(unscramble(root.getAttributeValue(BOT_TOKEN_ATTR)));
  newSettings.setPaused(Boolean.parseBoolean(root.getAttributeValue(PAUSE_ATTR)));
  newSettings.setUseProxy(Boolean.parseBoolean(root.getAttributeValue(USE_PROXY_ATTR)));
  newSettings.setProxyServer(root.getAttributeValue(PROXY_SERVER_ATTR));
  newSettings.setProxyPort(restoreInteger(root.getAttributeValue(PROXY_PORT_ATTR)));
  newSettings.setProxyUsername(root.getAttributeValue(PROXY_PASSWORD_ATTR));
  newSettings.setProxyPassword(unscramble(root.getAttributeValue(PROXY_PASSWORD_ATTR)));

  settings = newSettings;
  botManager.reloadIfNeeded(settings);
}
 
Example #19
Source File: UserShortcutConfigDOM.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected static String createUserConfigXml(String[] config) throws ApsSystemException {
	XMLOutputter out = new XMLOutputter();
	Document document = new Document();
	try {
		Element rootElement = new Element(ROOT_ELEMENT_NAME);
		document.setRootElement(rootElement);
		for (int i = 0; i < config.length; i++) {
			String shortcut = config[i];
			if (null != shortcut) {
				Element element = new Element(BOX_ELEMENT_NAME);
				element.setAttribute(POS_ATTRIBUTE_NAME, String.valueOf(i));
				element.setText(shortcut);
				rootElement.addContent(element);
			}
		}
	} catch (Throwable t) {
		_logger.error("Error parsing user config", t);
		//ApsSystemUtils.logThrowable(t, UserShortcutConfigDOM.class, "extractUserShortcutConfig");
		throw new ApsSystemException("Error parsing user config", t);
	}
	Format format = Format.getPrettyFormat();
	format.setIndent("\t");
	out.setFormat(format);
	return out.outputString(document);
}
 
Example #20
Source File: XmlExporterServiceImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public byte[] export(ExportDataSet dataSet) {
    if (dataSet == null) {
        throw new IllegalArgumentException("Xml Exporter cannot handle NULL data.");
    }
    Element rootElement = new Element(DATA_ELEMENT, WORKFLOW_NAMESPACE);
    rootElement.addNamespaceDeclaration(SCHEMA_NAMESPACE);
    rootElement.setAttribute(SCHEMA_LOCATION_ATTR, WORKFLOW_SCHEMA_LOCATION, SCHEMA_NAMESPACE);
    Document document = new Document(rootElement);
    boolean shouldPrettyPrint = true;
    for (XmlExporter exporter : xmlImpexRegistry.getExporters()) {
    	Element exportedElement = exporter.export(dataSet);
    	if (exportedElement != null) {
    		if (!exporter.supportPrettyPrint()) {
    			shouldPrettyPrint = false;
    		}
    		appendIfNotEmpty(rootElement, exportedElement);
    	}
    }

    // TODO: KULRICE-4420 - this needs cleanup
    Format f;
    if (!shouldPrettyPrint) {
        f = Format.getRawFormat();
        f.setExpandEmptyElements(false);
        f.setTextMode(Format.TextMode.PRESERVE);
    } else {
        f = Format.getPrettyFormat();
    }
    XMLOutputter outputer = new XMLOutputter(f);
    StringWriter writer = new StringWriter();
    try {
        outputer.output(document, writer);
    } catch (IOException e) {
        throw new WorkflowRuntimeException("Could not write XML data export.", e);
    }
    return writer.toString().getBytes();
}
 
Example #21
Source File: ScoDocument.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Method to clear a sco back to its original state - this would happen if the sco set lesson_status to "failed"
 * 
 * @return a new JDOM doc
 */
public Document formatCleanScoModel() {
    final CMI_DataModel cleanData = new CMI_DataModel(_userId, _userName, _max_time_allowed, _time_limit_action, _data_from_lms, _mastery_score, _lesson_mode,
            _credit_mode);
    cleanData.buildFreshModel();
    final Document theModel = cleanData.getModel();
    cleanData.setDocument(theModel);
    return cleanData.getDocument();
}
 
Example #22
Source File: SCORM12_DocumentHandler.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @param doc
 * @return The SCORM Namespace if this doc a SCORM Document - we look for the ADL Namespaces or null if not found in the Document
 */
protected static Namespace getSCORM_Namespace(final Document doc) {
    // We'll search all elements for the ADL Namespace
    boolean found = XMLUtils.containsNamespace(doc, ADLCP_NAMESPACE_12);
    if (found) {
        return ADLCP_NAMESPACE_12;
    }

    found = XMLUtils.containsNamespace(doc, ADLCP_NAMESPACE_13);
    if (found) {
        return ADLCP_NAMESPACE_13;
    }

    return null;
}
 
Example #23
Source File: JdomUtils.java    From redis-game-transaction with Apache License 2.0 5 votes vote down vote up
public static Element getRootElemet(URL xmlPath) {
    SAXBuilder builder = new SAXBuilder();
    builder.setValidation(false);
    Document doc = null;
    try {
        doc = builder.build(xmlPath);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return doc.getRootElement();
}
 
Example #24
Source File: CreoleRegisterImpl.java    From gate-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Parse a directory file (represented as an open stream), adding resource
 * data objects to the CREOLE register as they occur. If the resource is from
 * a URL then that location is passed (otherwise null).
 */
protected void parseDirectory(Plugin plugin, Document jdomDoc,
    URL directoryUrl, URL creoleFileUrl) throws GateException {
  // create a handler for the directory file and parse it;
  // this will create ResourceData entries in the register
  try {

    CreoleAnnotationHandler annotationHandler =
        new CreoleAnnotationHandler(plugin);

    GateClassLoader gcl = Gate.getClassLoader()
        .getDisposableClassLoader(plugin.getBaseURI().toString());

    // Add any JARs from the creole.xml to the GATE ClassLoader
    annotationHandler.addJarsToClassLoader(gcl, jdomDoc);

    // Make sure there is a RESOURCE element for every resource type the
    // directory defines
    annotationHandler.createResourceElementsForDirInfo(jdomDoc);

    processFullCreoleXmlTree(plugin, jdomDoc,
        annotationHandler);
  } catch(URISyntaxException | IOException e) {
    throw (new GateException(e));
  } catch(JDOMException je) {
    if(DEBUG) je.printStackTrace(Err.getPrintWriter());
    throw (new GateException(je));
  }

}
 
Example #25
Source File: MessageNotifierConfigDOM.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create an xml containing the notifier configuration.
 * @param config The jpmail configuration.
 * @return The xml containing the configuration.
 * @throws ApsSystemException In case of errors.
 */
public String createConfigXml(Map<String, MessageTypeNotifierConfig> config) throws ApsSystemException {
	Element root = new Element(ROOT);
	for (MessageTypeNotifierConfig messageTypeConfig : config.values()) {
		Element configElement = this.createConfigElement(messageTypeConfig);
		root.addContent(configElement);
	}
	Document doc = new Document(root);
	String xml = new XMLOutputter().outputString(doc);
	return xml;
}
 
Example #26
Source File: EntityTypeDOM.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public List<SmallEntityType> extractSmallEntityTypes(String xml) throws ApsSystemException {
	List<SmallEntityType> list = new ArrayList<>();
	Document document = this.decodeDOM(xml);
	List<Element> entityElements = document.getRootElement().getChildren();
	for (int i = 0; i < entityElements.size(); i++) {
		Element entityElem = entityElements.get(i);
		String typeCode = this.extractXmlAttribute(entityElem, "typecode", true);
		String typeDescr = this.extractXmlAttribute(entityElem, "typedescr", true);
		list.add(new SmallEntityType(typeCode, typeDescr));
	}
	return list;
}
 
Example #27
Source File: SamlUtils.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public static String signSamlResponse(final String samlResponse,
        final PrivateKey privateKey, final PublicKey publicKey) {
    final Document doc = constructDocumentFromXmlString(samlResponse);

    if (doc != null) {
        final Element signedElement = signSamlElement(doc.getRootElement(),
                privateKey, publicKey);
        doc.setRootElement((Element) signedElement.detach());
        return new XMLOutputter().outputString(doc);
    }
    throw new RuntimeException("Error signing SAML Response: Null document");
}
 
Example #28
Source File: SlackNotificationSettingsTest.java    From tcSlackBuildNotifier with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void test_WebookConfig() throws JDOMException, IOException{
	SAXBuilder builder = new SAXBuilder();
	List<SlackNotificationConfig> configs = new ArrayList<SlackNotificationConfig>();
	builder.setIgnoringElementContentWhitespace(true);
		Document doc = builder.build("src/test/resources/testdoc2.xml");
		Element root = doc.getRootElement();
		if(root.getChild("slackNotifications") != null){
			Element child = root.getChild("slackNotifications");
			if ((child.getAttribute("enabled") != null) && (child.getAttribute("enabled").equals("true"))){
				List<Element> namedChildren = child.getChildren("slackNotification");
				for(Iterator<Element> i = namedChildren.iterator(); i.hasNext();)
	            {
					Element e = i.next();
					SlackNotificationConfig whConfig = new SlackNotificationConfig(e);
					configs.add(whConfig);
	            }
			}
		}

	
	for (SlackNotificationConfig c : configs){
		SlackNotification wh = new SlackNotificationImpl(c.getChannel());
		wh.setEnabled(c.getEnabled());
		//slackNotification.addParams(c.getParams());
		System.out.println(wh.getChannel());
		System.out.println(wh.isEnabled().toString());

	}
}
 
Example #29
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 #30
Source File: ApsEntityDOM.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void buildDOM() {
	this._doc = new Document();
	this._root = new Element(this._rootElementName);
	for (int i = 0; i < TAGS.length; i++) {
		Element tag = new Element(TAGS[i]);
		_root.addContent(tag);
	}
	_doc.setRootElement(_root);
}