下面列出了javax.naming.OperationNotSupportedException#org.jdom2.Element 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Updates the case-level data params with the output data of a
* completing worklet, then copies the updates to the engine stored caseData
* @param runner the HandlerRunner containing the exception handling process
* @param wlData the worklet's output data params
*/
private void updateCaseData(ExletRunner runner, Element wlData) {
try {
// get engine copy of case data
Element in = getCaseData(runner.getCaseID());
// update data values as required
Element updated = _wService.updateDataList(in, wlData);
// and copy that back to the engine
_wService.getEngineClient().updateCaseData(runner.getCaseID(), updated);
}
catch (IOException ioe) {
_log.error("IO Exception calling interface X");
}
}
@Override
protected void populateChannel(final Channel channel, final Element eChannel) {
super.populateChannel(channel, eChannel);
final String generator = channel.getGenerator();
if (generator != null) {
eChannel.addContent(generateSimpleElement("generator", generator));
}
final int ttl = channel.getTtl();
if (ttl > -1) {
eChannel.addContent(generateSimpleElement("ttl", String.valueOf(ttl)));
}
final List<Category> categories = channel.getCategories();
for (final Category category : categories) {
eChannel.addContent(generateCategoryElement(category));
}
generateForeignMarkup(eChannel, channel.getForeignMarkup());
}
public static Long getLongValue(Element element, boolean withValidation)
{
try
{
return Long.parseLong(element.getText());
}
catch (Exception e)
{
// logger.error("'" + element.getName() + "' must be long, " +
// e.getMessage());
addErrorValue(element, withValidation, "msgIntegerError");
// logger.error("-----------element '" + element.getName() + "' = " +
// Utils.object2String(element));
return null;
}
}
public static Integer getIntegerValue(Element element, boolean withValidation)
{
try
{
return Integer.parseInt(element.getText());
}
catch (Exception e)
{
// logger.error("'" + element.getName() + "' must be integer, " +
// e.getMessage());
addErrorValue(element, withValidation, "msgIntegerError");
// logger.error("-----------element '" + element.getName() + "' = " +
// Utils.object2String(element));
return null;
}
}
@Override
public <T> void child(Element element, String sequences, String childName,
Supplier<T> getter, Consumer<T> setter,
Class<T> elementClass, ElementIO<T> io) {
child(element, sequences, childName, getter, setter, new TypedElementIO<T>() {
@Override
public Class<T> getElementClass() {
return elementClass;
}
@Override
public void io(Element e, T t, IOProcessor p) {
io.io(e, t, p);
}
@Override
public String getElementName() {
return childName;
}
});
}
public String ProgMain(Element Document){
try{
System.out.println("Beginning of XmlSignature:");
//Call the function to sign the document
byte[] signeddata = SignedData(Document).getEncoded();
if (signeddata == null || signeddata.length == 0) return null;
else
{
System.out.println("End of Xml Signature");
// Convert the signed data in a BASE64 string to make it a valid content
// for Yawl
Base64 enCoder = new Base64();
String base64OfSignatureValue = new String(enCoder.encode(signeddata));
System.out.println(base64OfSignatureValue);
return base64OfSignatureValue;
}
} catch (Exception e) {e.printStackTrace();
return null;
}
}
private void sortChildren(Element parent) throws Exception {
@SuppressWarnings("unchecked")
List<Element> children = parent.getChildren();
if (children == null || children.size() == 0) {
return;
}
ArrayList<Element> copy = new ArrayList<>();
copy.addAll(children);
copy.sort((a, b) -> {
String sa = a.getName() + "/" + a.getAttributeValue("name");
String sb = b.getName() + "/" + b.getAttributeValue("name");
return sa.compareTo(sb);
});
parent.removeContent();
parent.addContent(copy);
for (Element child : copy) {
sortChildren(child);
}
}
public void testExamples() throws Exception {
File basedir = new File(Resources.getRoot(), "../../../");
File sourceFilename = new File(basedir, "distribution/Assembly.xml");
HashMap<String, File> names = new HashMap<>();
Element assembly = new SAXBuilder().build(sourceFilename).getRootElement();
for (Element fs : assembly.getChild("fileSets", null).getChildren("fileSet", null)) {
String outDir = fs.getChild("outputDirectory", null).getText();
if (outDir.startsWith("/examples/")) {
String srcDir = fs.getChild("directory", null).getText();
srcDir = srcDir.replace("${basedir}", basedir.getPath());
new FileScanner(f -> {
String name = f.getName();
File present = names.get(name);
if (present != null) {
throw new IOException("name not unique\n" + present.getPath() + "\n" + f.getPath());
}
names.put(name, f);
}).noOutput().scan(new File(srcDir));
}
}
}
@Test
public void testExpressionsToIgnore() throws JaxenException, JDOMException {
Element built = new MCRNodeBuilder().buildElement("element[2]", null, null);
assertNotNull(built);
assertEquals("element", built.getName());
built = new MCRNodeBuilder().buildElement("element[contains(.,'foo')]", null, null);
assertNotNull(built);
assertEquals("element", built.getName());
built = new MCRNodeBuilder().buildElement("foo|bar", null, null);
assertNull(built);
Attribute attribute = new MCRNodeBuilder().buildAttribute("@lang[preceding::*/foo='bar']", "value", null);
assertNotNull(attribute);
assertEquals("lang", attribute.getName());
assertEquals("value", attribute.getValue());
built = new MCRNodeBuilder().buildElement("parent/child/following::node/foo='bar'", null, null);
assertNotNull(built);
assertEquals("child", built.getName());
assertNotNull(built.getParentElement());
assertEquals("parent", built.getParentElement().getName());
assertEquals(0, built.getChildren().size());
assertEquals("", built.getText());
}
/**
* Write the NcML representation for a file.
* Note that ucar.nc2.dataset.NcMLWriter has a JDOM implementation, for complete NcML.
* This method implements only the "core" NcML for plain ole netcdf files.
*
* @param ncfile write NcML for this file
* @param showValues do you want the variable values printed?
* @param url use this for the url attribute; if null use getLocation(). // ??
*/
private static String writeNcML(NetcdfFile ncfile, WantValues showValues, @Nullable String url) {
Preconditions.checkNotNull(ncfile);
Preconditions.checkNotNull(showValues);
Predicate<? super Variable> writeVarsPred;
switch (showValues) {
case none:
writeVarsPred = NcmlWriter.writeNoVariablesPredicate;
break;
case coordsOnly:
writeVarsPred = NcmlWriter.writeCoordinateVariablesPredicate;
break;
case all:
writeVarsPred = NcmlWriter.writeAllVariablesPredicate;
break;
default:
String message =
String.format("CAN'T HAPPEN: showValues (%s) != null and checked all possible enum values.", showValues);
throw new AssertionError(message);
}
NcmlWriter ncmlWriter = new NcmlWriter(null, null, writeVarsPred);
Element netcdfElement = ncmlWriter.makeNetcdfElement(ncfile, url);
return ncmlWriter.writeToString(netcdfElement);
}
/**
* Считать атрибуты другой схемы
*
* @param element элемент
* @param namespace схема, атрибуты которой нужно считать
* @param map мапа, в которую считать атрибуты схемы
*/
@Override
public void otherAttributes(Element element, Namespace namespace, Map<String, String> map) {
if (r) {
for (Object o : element.getAttributes()) {
Attribute attribute = (Attribute) o;
if (attribute.getNamespace().equals(namespace)) {
map.put(attribute.getName(), attribute.getValue());
}
}
} else {
for (Map.Entry<String, String> entry : map.entrySet()) {
element.setAttribute(new Attribute(entry.getKey(), entry.getValue(), namespace));
}
}
}
/**
* Gets the average percentage for a particular MBTI personality type for
* settlers.
*
* @param personalityType the MBTI personality type
* @return percentage
* @throws Exception if personality type could not be found.
*/
public double getPersonalityTypePercentage(String personalityType) {
double result = 0D;
Element personalityTypeList = personDoc.getRootElement().getChild(PERSONALITY_TYPES);
List<Element> personalityTypes = personalityTypeList.getChildren(MBTI);
for (Element mbtiElement : personalityTypes) {
String type = mbtiElement.getAttributeValue(TYPE);
if (type.equals(personalityType)) {
result = Double.parseDouble(mbtiElement.getAttributeValue(PERCENTAGE));
break;
}
}
return result;
}
@Override
public N2oSelect read(Element element, Namespace namespace) {
N2oSelect select = new N2oSelect();
select.setType(getAttributeEnum(element, "type", ListType.class));
Element showModalElement = element.getChild("show-modal", namespace);
if (showModalElement != null)
select.setShowModal(ShowModalFromClassifierReaderV1.getInstance().read(showModalElement));
select.setSearchAsYouType(getAttributeBoolean(element, "search-as-you-type", "search-are-you-type"));
select.setSearch(getAttributeBoolean(element, "search"));
select.setWordWrap(getAttributeBoolean(element, "word-wrap"));
boolean quick = select.getQueryId() != null;
boolean advance = select.getShowModal() != null;
N2oClassifier.Mode mode = quick && !advance ? N2oClassifier.Mode.quick
: advance && !quick ? N2oClassifier.Mode.advance
: N2oClassifier.Mode.combined;
select.setMode(mode);
return (N2oSelect) getQueryFieldDefinition(element, select);
}
static Document getDocument(MCRCategory cl, Map<MCRCategoryID, Number> countMap) {
Document cd = new Document(new Element("mycoreclass"));
cd.getRootElement().setAttribute("noNamespaceSchemaLocation", "MCRClassification.xsd", XSI_NAMESPACE);
cd.getRootElement().setAttribute("ID", cl.getId().getRootID());
cd.getRootElement().addNamespaceDeclaration(XLINK_NAMESPACE);
MCRCategory root = cl.isClassification() ? cl : cl.getRoot();
if (root.getURI() != null) {
cd.getRootElement().addContent(getElement(root.getURI()));
}
for (MCRLabel label : root.getLabels()) {
cd.getRootElement().addContent(MCRLabelTransformer.getElement(label));
}
Element categories = new Element("categories");
cd.getRootElement().addContent(categories);
if (cl.isClassification()) {
for (MCRCategory category : cl.getChildren()) {
categories.addContent(getElement(category, countMap));
}
} else {
categories.addContent(getElement(cl, countMap));
}
return cd;
}
/**
* @param e element to parse
* @param locale locale for parsing
* @return array of media:group elements
*/
private MediaGroup[] parseGroup(final Element e, final Locale locale) {
final List<Element> groups = e.getChildren("group", getNS());
final ArrayList<MediaGroup> values = new ArrayList<MediaGroup>();
for (int i = 0; groups != null && i < groups.size(); i++) {
final Element group = groups.get(i);
final MediaGroup g = new MediaGroup(parseContent(group, locale));
for (int j = 0; j < g.getContents().length; j++) {
if (g.getContents()[j].isDefaultContent()) {
g.setDefaultContentIndex(new Integer(j));
break;
}
}
g.setMetadata(parseMetadata(group, locale));
values.add(g);
}
return values.toArray(new MediaGroup[values.size()]);
}
@Override
public final void loadFromXml(Element e) {
try {
setFormName(URLDecoder.decode(e.getChild("name").getTextTrim(), "UTF-8"));
Element elem = e.getChild("pos");
setXPos(Double.parseDouble(elem.getAttributeValue("x")));
setYPos(Double.parseDouble(elem.getAttributeValue("y")));
elem = e.getChild("textColor");
setTextColor(new Color(Integer.parseInt(elem.getAttributeValue("r")),
Integer.parseInt(elem.getAttributeValue("g")),
Integer.parseInt(elem.getAttributeValue("b"))));
setTextAlpha(Float.parseFloat(elem.getAttributeValue("a")));
setTextSize(Integer.parseInt(e.getChild("textSize").getTextTrim()));
setTextSize(Integer.parseInt(e.getChildText("textSize")));
formFromXml(e.getChild("extra"));
} catch (IOException ignored) {
}
}
private void filterNonEmpty(String classId, Element e) {
SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient();
Element[] categories = e.getChildren("category").toArray(Element[]::new);
for (Element cat : categories) {
SolrQuery solrQquery = new SolrQuery();
solrQquery.setQuery(
"category:\"" + MCRSolrUtils.escapeSearchValue(classId + ":" + cat.getAttributeValue("ID")) + "\"");
solrQquery.setRows(0);
try {
QueryResponse response = solrClient.query(solrQquery);
SolrDocumentList solrResults = response.getResults();
if (solrResults.getNumFound() == 0) {
cat.detach();
} else {
filterNonEmpty(classId, cat);
}
} catch (SolrServerException | IOException exc) {
LOGGER.error(exc);
}
}
}
@Override
public ModuleCollection<Tnt> load(Match match) {
ModuleCollection<Tnt> results = new ModuleCollection<>();
if (match.getDocument().getRootElement().getChild("tnt") != null) {
for (Element element : match.getDocument().getRootElement().getChildren("tnt")) {
boolean instantIgnite = Numbers.parseBoolean(element.getChildText("instantignite"), false);
boolean blockDamage = Numbers.parseBoolean(element.getChildText("blockdamage"), true);
double yield = Numbers.limitDouble(0, 1, Numbers.parseDouble(element.getChildText("yield"), 0.3));
double power = Numbers.parseDouble(element.getChildText("power"), 4.0);
double fuse = element.getChild("fuse") != null ? Strings.timeStringToSeconds(element.getChildText("fuse")) : 4;
int limit = Numbers.parseInt(element.getChildText("dispenser-tnt-limit"),16);
double multiplier = Numbers.parseDouble(element.getChildText("dispenser-tnt-multiplier"), 0.25);
results.add(new Tnt(instantIgnite, blockDamage, yield, power, fuse, limit, multiplier));
}
} else results.add(new Tnt(false, true, 0.3, 4.0, 4, 16, 0.25));
return results;
}
protected static RespawnOptions parseRespawnOptions(Document doc) throws InvalidXMLException {
Duration delay = MINIMUM_RESPAWN_DELAY;
boolean auto = doc.getRootElement().getChild("autorespawn") != null; // Legacy support
boolean blackout = false;
boolean spectate = false;
boolean bedSpawn = false;
Component message = null;
for (Element elRespawn : doc.getRootElement().getChildren("respawn")) {
delay = XMLUtils.parseDuration(elRespawn.getAttribute("delay"), delay);
auto = XMLUtils.parseBoolean(elRespawn.getAttribute("auto"), auto);
blackout = XMLUtils.parseBoolean(elRespawn.getAttribute("blackout"), blackout);
spectate = XMLUtils.parseBoolean(elRespawn.getAttribute("spectate"), spectate);
bedSpawn = XMLUtils.parseBoolean(elRespawn.getAttribute("bed"), bedSpawn);
message = XMLUtils.parseFormattedText(elRespawn, "message", message);
if (TimeUtils.isShorterThan(delay, MINIMUM_RESPAWN_DELAY)) delay = MINIMUM_RESPAWN_DELAY;
}
return new RespawnOptions(delay, auto, blackout, spectate, bedSpawn, message);
}
protected List<? extends Filter> parseParents(Element el) throws InvalidXMLException {
return Node.tryAttr(el, "parents")
.map(attr -> Stream.of(attr.getValueNormalize().split("\\s"))
.map(rethrowFunction(name -> filterParser.parseReference(attr, name)))
.collect(tc.oc.commons.core.stream.Collectors.toImmutableList()))
.orElse(ImmutableList.of());
}
@Override
public N2oRole read(Element element) {
N2oRole n2oRole = new N2oRole();
n2oRole.setId(ReaderJdomUtil.getAttributeString(element, "id"));
n2oRole.setName(ReaderJdomUtil.getAttributeString(element, "name"));
AccessPoint[] accessPoints = ReaderJdomUtil.getChildren(element, null, readerFactory,
SimpleAccessSchemaReaderV1.DEFAULT_ACCESSPOINT_LIB, AccessPoint.class);
n2oRole.setAccessPoints(accessPoints);
return n2oRole;
}
/**
* Builds an absolute XPath expression for a given element or attribute within a JDOM XML structure.
* In case any ancestor element in context is not the first one, the XPath will also contain a position predicate.
* For all namespaces commonly used in MyCoRe, their namespace prefixes will be used.
*
* @param object a JDOM element or attribute
* @return absolute XPath of that object. In case there is a root Document, it will begin with a "/".
*/
public static String buildXPath(Object object) {
if (object instanceof Element) {
return buildXPath((Element) object);
} else if (object instanceof Attribute) {
return buildXPath((Attribute) object);
} else {
return "";
}
}
protected Attribute getAttribute(final Element e, final String attributeName) {
Attribute attribute = e.getAttribute(attributeName);
if (attribute == null) {
attribute = e.getAttribute(attributeName, namespace);
}
return attribute;
}
/**
* This method returns the searcresults (i.e. the entry-numbers of the found entries)
* of a certain search-request.
*
* @param nr the number of the searchrequest where we want to set the new results
* @param results the new results for the searchrequest {@code nr}
* @return
*/
public boolean setSearchResults(int nr, int[] results) {
// get the element
Element el = retrieveElement(nr);
// if we found an element, go on...
if ((el!=null)&&(results!=null)) {
// create string builder
StringBuilder sb = new StringBuilder("");
// go through all results
for (int r : results) {
// append them to stringbuilder
sb.append(String.valueOf(r));
sb.append(",");
}
// delete last comma
if (sb.length()>1) {
sb.setLength(sb.length()-1);
}
// get all results and split them into an array
el.getChild("results").setText(sb.toString());
// change modified state
setModified(true);
// everything is ok
return true;
}
// error occurred
return false;
}
public Element toXML() {
Element cond = new Element("condition");
cond.setAttribute("field", "group");
cond.setAttribute("operator", (not ? "!=" : "="));
cond.setAttribute("value", groupname);
return cond;
}
private IcdSystBlock createIcdSystBlock(
Element blockClassElement,
int level,
boolean last,
String lang) {
IcdSystBlock icdSystBlock = IcdSystBlock.Factory.newInstance();
icdSystBlock.setCode(getCode(blockClassElement));
icdSystBlock.setPreferredRubricLabel(getPreferredRubricLabel(blockClassElement, lang));
icdSystBlock.setLevel(level);
icdSystBlock.setLast(last);
icdSystBlock = icdSystBlockDao.create(icdSystBlock);
return icdSystBlock;
}
public static Boolean getElementBoolean(Element element, String elementName) {
Element child = element.getChild(elementName, element.getNamespace());
if (child != null) {
return Boolean.valueOf(getText(child));
}
return null;
}
void define(@Nullable Element source, F definition) throws InvalidXMLException {
checkState(!isDefined());
this.definition = checkNotNull(definition);
if(source != null) this.source = source;
// Find the lexical path of the source Element
if(this.source != null) {
this.path = XMLUtils.indexPath(this.source);
}
// Index by definition and source location
byDefinition.put(definition, this);
lexical.add(this);
}
public Element makeDimensionElement(Dimension dim) throws IllegalArgumentException {
if (!dim.isShared()) {
throw new IllegalArgumentException(
"Cannot create private dimension: " + "in NcML, <dimension> elements are always shared.");
}
Element dimElem = new Element("dimension", namespace);
dimElem.setAttribute("name", dim.getShortName());
dimElem.setAttribute("length", Integer.toString(dim.getLength()));
if (dim.isUnlimited())
dimElem.setAttribute("isUnlimited", "true");
return dimElem;
}
/**
* This method recursivly scans all elements of a desktop. If an
* entry-element which id-attribute matches the parameter
* {@code entrynumber} was found, this method returns {@code true}.
*
* @param e the element where we start scanning. for the first call, use
* {@link #getDesktopElement(int) getDesktopElement(int)} to retrieve the
* root-element for starting the recursive scan.
* @param entrynumber the number of the entry we are looking for. if any
* element's id-attribut matches this parameter, the element is return, else
* null
* @param found the initial value, should be {@code false} when initially
* called
* @return {@code true} when the entry with the number {@code entrynumber}
* was found, {@code false} otherwise.
*/
public boolean desktopHasElement(Element e, String entrynumber, boolean found) {
// if we don't have any element, return null
if (e == null) {
return false;
}
// get a list with all children of the element
List<Element> children = e.getChildren();
// create an iterator
Iterator<Element> it = children.iterator();
// go through all children
while (it.hasNext()) {
// get the child
e = it.next();
// else check whether we have child-elements - if so, re-call method
if (hasChildren(e)) {
found = desktopHasElement(e, entrynumber, found);
}
// check whether an entry was found in children
if (found) {
return true;
}
// check whether we have an entry-element that matched the requested id-number
if (e != null && e.getName().equals(ELEMENT_ENTRY)) {
// check whether attribute exists
String att = e.getAttributeValue("id");
// if so, and it machtes the requested id-number, add element to list
if (att != null && att.equals(entrynumber)) {
// save element
foundDesktopElement = e;
return true;
}
}
}
return found;
}