org.jdom2.Element Java Examples

The following examples show how to use org.jdom2.Element. 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: SpawnModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #2
Source File: XMLUtils.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
	}
}
 
Example #3
Source File: RSS20Generator.java    From rome with Apache License 2.0 6 votes vote down vote up
@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());

}
 
Example #4
Source File: XMLUtils.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
	}
}
 
Example #5
Source File: IOProcessorImpl.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
@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;
        }
    });
}
 
Example #6
Source File: DigitalSignature.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
	}
}
 
Example #7
Source File: MCRFileStoreTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #8
Source File: TestExampleNamesUnique.java    From Digital with GNU General Public License v3.0 6 votes vote down vote up
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));
        }
    }
}
 
Example #9
Source File: MCRNodeBuilderTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@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());
}
 
Example #10
Source File: Ncdump.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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);
}
 
Example #11
Source File: PersonConfig.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: N2oSelectXmlReaderV1.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: MCRCategoryTransformer.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: MediaModuleParser.java    From rome with Apache License 2.0 6 votes vote down vote up
/**
 * @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()]);
}
 
Example #15
Source File: AbstractForm.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
@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) {
    }
}
 
Example #16
Source File: IOProcessorImpl.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Считать атрибуты другой схемы
 *
 * @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));
        }
    }
}
 
Example #17
Source File: ExceptionService.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example #18
Source File: TntBuilder.java    From CardinalPGM with MIT License 6 votes vote down vote up
@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;
}
 
Example #19
Source File: MCRRestAPIClassifications.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
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);
        }

    }
}
 
Example #20
Source File: MCRVersioningMetadataStoreTest.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void delete() throws Exception {
    System.out.println("TEST DELETE");
    Document xml1 = new Document(new Element("root"));
    int id = getVersStore().create(new MCRJDOMContent(xml1)).getID();
    assertTrue(getVersStore().exists(id));
    getVersStore().delete(id);
    assertFalse(getVersStore().exists(id));
}
 
Example #21
Source File: MCRMODSPagesHelper.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static Element buildExtentPages(String input) {
    String normalizedInput = input.trim();
    normalizedInput = HYPHEN_NORMALIZER.normalize(normalizedInput);
    Element extent = EXTENT_PAGES_BUILDER.buildExtent(normalizedInput);
    END_PAGE_COMPLETER.completeEndPage(extent);
    return extent;
}
 
Example #22
Source File: N2oInputTextPersister.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public Element persist(N2oInputText n2oInputText, Namespace namespace) {
    Element inputTextElement = new Element(getElementName(), getNamespacePrefix(), getNamespaceUri());
    setControl(inputTextElement, n2oInputText);
    setField(inputTextElement, n2oInputText);
    if (n2oInputText.getLength() != null)
        inputTextElement.setAttribute("length", n2oInputText.getLength().toString());
    PersisterJdomUtil.setAttribute(inputTextElement, "max", n2oInputText.getMax());
    PersisterJdomUtil.setAttribute(inputTextElement, "min", n2oInputText.getMin());
    PersisterJdomUtil.setAttribute(inputTextElement, "step", n2oInputText.getStep());
    return inputTextElement;
}
 
Example #23
Source File: N2oBadgeXmlReader.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public N2oBadgeCell read(Element element) {
    if(element == null) return null;
    String text = ReaderJdomUtil.getAttributeString(element, "text");
    Position position = ReaderJdomUtil.getAttributeEnum(element, "position", Position.class);
    N2oSwitch n2oSwitch = new SwitchReader().read(element);
    N2oBadgeCell badge = new N2oBadgeCell();
    badge.setPosition(position);
    badge.setText(text);
    badge.setN2oSwitch(n2oSwitch);
    badge.setNamespaceUri(element.getNamespaceURI());
    return badge;
}
 
Example #24
Source File: LegacyFilterDefinitionParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
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());
}
 
Example #25
Source File: RSS091UserlandParser.java    From rome with Apache License 2.0 5 votes vote down vote up
/**
 * It looks for the 'image' elements under the 'channel' elemment.
 */
@Override
protected Element getImage(final Element rssRoot) {

    final Element eChannel = rssRoot.getChild("channel", getRSSNamespace());

    if (eChannel != null) {
        return eChannel.getChild("image", getRSSNamespace());
    } else {
        return null;
    }

}
 
Example #26
Source File: ExceptionService.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String handleItemException(WorkItemRecord wir, String dataStr,
                                   RuleType ruleType) {
    String msg;
    YSpecificationID specID = new YSpecificationID(wir);
    Element data = augmentItemData(wir, dataStr);

    // get the exception handler for this task (if any)
    RdrPair pair = getExceptionHandler(specID, wir.getTaskID(), data, ruleType);

    // if pair is null there's no rules defined for this type of constraint
    if (pair == null) {
        msg = "No " + ruleType.toLongString() + " rules defined for workitem: " +
                wir.getTaskID();
    }
    else {
        if (! pair.hasNullConclusion()) {                // we have a handler
            msg = ruleType.toLongString() + " exception raised for work item: " +
                    wir.getID();
            raiseException(wir, pair, data, ruleType);
        }
        else {                      // there are rules but the item passes
            msg = "Workitem '" + wir.getID() + "' has passed " +
                    ruleType.toLongString() + " rules.";
        }
    }
    _log.info(msg);
    return StringUtil.wrap(msg, "result");
}
 
Example #27
Source File: N2oReferenceAccessPointReader.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public N2oReferenceAccessPoint read(Element element) {
    N2oReferenceAccessPoint res = new N2oReferenceAccessPoint();
    res.setObjectId(ReaderJdomUtil.getAttributeString(element, "object-id"));
    res.setNamespaceUri(getNamespaceUri());
    return res;
}
 
Example #28
Source File: N2oImageCellXmlReader.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public N2oImageCell read(Element element) {
    if (element == null)
        return null;
    N2oImageCell imageCell = new N2oImageCell();
    imageCell.setWidth(getAttributeString(element, "width"));
    imageCell.setShape(getAttributeEnum(element, "shape", ImageShape.class));
    return imageCell;
}
 
Example #29
Source File: SpawnParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private Filter parseFilter(Element el) throws InvalidXMLException {
    Filter filter = StaticFilter.ABSTAIN;
    final Node nodeTeam = Node.fromAttr(el, "team");
    if(nodeTeam != null) {
        filter = AllFilter.of(filter, new TeamFilter(teamParser.parseReference(nodeTeam)));
    }
    final Optional<Filter> prop = filters.property(el).optional();
    if(prop.isPresent()) {
        filter = AllFilter.of(filter, prop.get());
    }
    return filter;
}
 
Example #30
Source File: BaseWireFeedParser.java    From rome with Apache License 2.0 5 votes vote down vote up
protected String getAttributeValue(final Element e, final String attributeName) {
    final Attribute attr = getAttribute(e, attributeName);
    if (attr != null) {
        return attr.getValue();
    } else {
        return null;
    }
}