Java Code Examples for org.dom4j.Element#attribute()

The following examples show how to use org.dom4j.Element#attribute() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@SuppressWarnings("unchecked")
public Element getNodeByActionName(String actionName) {
    // 取得所有节点
    List<Node> nodeList = doc.selectNodes(DEFAULT_ACTION_PATH);
    // 遍历所有的Node节点
    System.out.println(nodeList.size());
    for (Node node : nodeList) {
        Element e = (Element) node;
        Attribute a = e.attribute("name");
        // 找到名字匹配的action
        if (a.getText().equals(actionName)) {
            return e;
        }
    }
    return null;
}
 
Example 2
Source Project: Openfire   File: StreamManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Receive and process acknowledgement packet from client
 * @param ack XEP-0198 acknowledgement <a /> stanza to process
 */
private void processClientAcknowledgement(Element ack) {
    if(isEnabled()) {
        if (ack.attribute("h") != null) {
            final long h = Long.valueOf(ack.attributeValue("h"));

            Log.debug( "Received acknowledgement from client: h={}", h );

            if (!validateClientAcknowledgement(h)) {
                Log.warn( "Closing client session. Client acknowledges stanzas that we didn't send! Client Ack h: {}, our last stanza: {}, affected session: {}", h, unacknowledgedServerStanzas.getLast().x, session );
                final StreamError error = new StreamError( StreamError.Condition.undefined_condition, "You acknowledged stanzas that we didn't send. Your Ack h: " + h + ", our last stanza: " + unacknowledgedServerStanzas.getLast().x );
                session.deliverRawText( error.toXML() );
                session.close();
                return;
            }

            processClientAcknowledgement(h);
        }
    }
}
 
Example 3
public Object get(Object owner) throws HibernateException {
	Element ownerElement = (Element) owner;
	
	Element element = ownerElement.element(elementName);
	
	if ( element==null ) {
		return null;
	}
	else {
		Attribute attribute = element.attribute(attributeName);
		if (attribute==null) {
			return null;
		}
		else {
			return super.propertyType.fromXMLNode(attribute, super.factory);
		}
	}
}
 
Example 4
Source Project: olat   File: MaterialParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
*/
  @Override
  public Object parse(final Element element) {
      // assert element.getName().equalsIgnoreCase("material");

      final List materials = element.elements();
      if (materials.size() == 0) {
          return null;
      }

      final Material material = new Material();
      // ATTRIBUTES
      final Attribute label = element.attribute("label");
      if (label != null) {
          material.setLable(label.getValue());
      }

      // ELEMENTS
      for (final Iterator i = materials.iterator(); i.hasNext();) {
          final QTIObject obj = (QTIObject) parserManager.parse((Element) i.next());
          if (obj != null) {
              material.getElements().add(obj);
          }
      }
      return material;
  }
 
Example 5
public void set(Object target, Object value, SessionFactoryImplementor factory) 
throws HibernateException {
	Element owner = ( Element ) target;
	Attribute attribute = owner.attribute(attributeName);
	if (value==null) {
		if (attribute!=null) attribute.detach();
	}
	else {
		if (attribute==null) {
			owner.addAttribute(attributeName, "null");
			attribute = owner.attribute(attributeName);
		}
		super.propertyType.setToXMLNode(attribute, value, factory);
	}
}
 
Example 6
private IdClass getIdClass(Element tree, XMLContext.Default defaults) {
	Element element = tree == null ? null : tree.element( "id-class" );
	if ( element != null ) {
		Attribute attr = element.attribute( "class" );
		if ( attr != null ) {
			AnnotationDescriptor ad = new AnnotationDescriptor( IdClass.class );
			Class clazz;
			try {
				clazz = classLoaderAccess.classForName( XMLContext.buildSafeClassName( attr.getValue(), defaults )
				);
			}
			catch ( ClassLoadingException e ) {
				throw new AnnotationException( "Unable to find id-class: " + attr.getValue(), e );
			}
			ad.setValue( "value", clazz );
			return AnnotationFactory.create( ad );
		}
		else {
			throw new AnnotationException( "id-class without class. " + SCHEMA_VALIDATION );
		}
	}
	else if ( defaults.canUseJavaAnnotations() ) {
		return getPhysicalAnnotation( IdClass.class );
	}
	else {
		return null;
	}
}
 
Example 7
private static void bindColumnsOrFormula(Element node, SimpleValue simpleValue, String path,
		boolean isNullable, Mappings mappings) {
	Attribute formulaNode = node.attribute( "formula" );
	if ( formulaNode != null ) {
		Formula f = new Formula();
		f.setFormula( formulaNode.getText() );
		simpleValue.addFormula( f );
	}
	else {
		bindColumns( node, simpleValue, isNullable, true, path, mappings );
	}
}
 
Example 8
Source Project: cuba   File: AbstractComponentLoader.java    License: Apache License 2.0 5 votes vote down vote up
protected void loadCaption(Component.HasCaption component, Element element) {
    if (element.attribute("caption") != null) {
        String caption = element.attributeValue("caption");

        caption = loadResourceString(caption);
        component.setCaption(caption);

        if (component instanceof HasHtmlCaption) {
            loadCaptionAsHtml((HasHtmlCaption) component, element);
        }
    }
}
 
Example 9
Source Project: cuba   File: AbstractComponentLoader.java    License: Apache License 2.0 5 votes vote down vote up
protected void loadDescription(Component.HasDescription component, Element element) {
    if (element.attribute("description") != null) {
        String description = element.attributeValue("description");

        description = loadResourceString(description);
        component.setDescription(description);

        if (component instanceof HasHtmlDescription) {
            loadDescriptionAsHtml((HasHtmlDescription) component, element);
        }
    }
}
 
Example 10
Source Project: Openfire   File: ElementUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the specified property is included in the XML hierarchy. A property could
 * have a value associated or not. If the property has an associated value then
 *
 * @param element the element to check
 * @param name the name of the property to find out.
 * @return true if the specified property is included in the XML hierarchy.
 */
public static boolean includesProperty(Element element, String name) {
    String[] propName = parsePropertyName(name);

    // Grab the attribute if there is one
    String lastName = propName[propName.length - 1];
    String attName = null;
    int attributeIndex = lastName.indexOf(':');
    if (attributeIndex >= 0) {
        propName[propName.length - 1] = lastName.substring(0, attributeIndex);
        attName = lastName.substring(attributeIndex + 1);
    }

    // Search for this property by traversing down the XML hierarchy.
    int i = propName[0].equals(element.getName()) ? 1 : 0;
    for (; i < propName.length; i++) {
        element = element.element(propName[i]);
        if (element == null) {
            break;
        }
    }

    if (element != null) {
        if (attName == null){
            // The property exists so return true
            return true;
        } else {
            // The property exists if the attribute exists in the element
            return element.attribute(attName) != null;
        }
    }
    else {
        // The property does not exist so return false
        return false;
    }
}
 
Example 11
Source Project: cuba   File: AbstractDataGridLoader.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
protected String loadCaption(Element element) {
    if (element.attribute("caption") != null) {
        String caption = element.attributeValue("caption");

        return loadResourceString(caption);
    }
    return null;
}
 
Example 12
private static void bindSimpleValueType(Element node, SimpleValue simpleValue, Mappings mappings)
		throws MappingException {
	String typeName = null;

	Properties parameters = new Properties();

	Attribute typeNode = node.attribute( "type" );
	if ( typeNode == null ) typeNode = node.attribute( "id-type" ); // for an any
	if ( typeNode != null ) typeName = typeNode.getValue();

	Element typeChild = node.element( "type" );
	if ( typeName == null && typeChild != null ) {
		typeName = typeChild.attribute( "name" ).getValue();
		Iterator typeParameters = typeChild.elementIterator( "param" );

		while ( typeParameters.hasNext() ) {
			Element paramElement = (Element) typeParameters.next();
			parameters.setProperty(
					paramElement.attributeValue( "name" ),
					paramElement.getTextTrim()
				);
		}
	}

	TypeDef typeDef = mappings.getTypeDef( typeName );
	if ( typeDef != null ) {
		typeName = typeDef.getTypeClass();
		// parameters on the property mapping should
		// override parameters in the typedef
		Properties allParameters = new Properties();
		allParameters.putAll( typeDef.getParameters() );
		allParameters.putAll( parameters );
		parameters = allParameters;
	}

	if ( !parameters.isEmpty() ) simpleValue.setTypeParameters( parameters );

	if ( typeName != null ) simpleValue.setTypeName( typeName );
}
 
Example 13
Source Project: olat   File: ImsCPFileResource.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Check for title and at least one resource.
 * 
 * @param unzippedDir
 * @return True if is of type.
 */
public static boolean validate(final File unzippedDir) throws AddingResourceException {
    final File fManifest = new File(unzippedDir, "imsmanifest.xml");
    final Document doc = IMSLoader.loadIMSDocument(fManifest);
    // do not throw exception already here, as it might be only a generic zip file
    if (doc == null) {
        return false;
    }

    // get all organization elements. need to set namespace
    final Element rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    final Map nsuris = new HashMap(1);
    nsuris.put("ns", nsuri);

    // Check for organiztaion element. Must provide at least one... title gets ectracted from either
    // the (optional) <title> element or the mandatory identifier attribute.
    // This makes sure, at least a root node gets created in CPManifestTreeModel.
    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);
    final Element orgaEl = (Element) meta.selectSingleNode(rootElement); // TODO: accept several organizations?
    if (orgaEl == null) {
        throw new AddingResourceException("resource.no.organisation");
    }

    // Check for at least one <item> element referencing a <resource>, which will serve as an entry point.
    // This is mandatory, as we need an entry point as the user has the option of setting
    // CPDisplayController to not display a menu at all, in which case the first <item>/<resource>
    // element pair gets displayed.
    final XPath resourcesXPath = rootElement.createXPath("//ns:resources");
    resourcesXPath.setNamespaceURIs(nsuris);
    final Element elResources = (Element) resourcesXPath.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AddingResourceException("resource.no.resource"); // no <resources> element.
    }
    final XPath itemsXPath = rootElement.createXPath("//ns:item");
    itemsXPath.setNamespaceURIs(nsuris);
    final List items = itemsXPath.selectNodes(rootElement);
    if (items.size() == 0) {
        throw new AddingResourceException("resource.no.item"); // no <item> element.
    }
    for (final Iterator iter = items.iterator(); iter.hasNext();) {
        final Element item = (Element) iter.next();
        final String identifierref = item.attributeValue("identifierref");
        if (identifierref == null) {
            continue;
        }
        final XPath resourceXPath = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']");
        resourceXPath.setNamespaceURIs(nsuris);
        final Element elResource = (Element) resourceXPath.selectSingleNode(elResources);
        if (elResource == null) {
            throw new AddingResourceException("resource.no.matching.resource");
        }
        if (elResource.attribute("scormtype") != null) {
            return false;
        }
        if (elResource.attribute("scormType") != null) {
            return false;
        }
        if (elResource.attribute("SCORMTYPE") != null) {
            return false;
        }
        if (elResource.attributeValue("href") != null) {
            return true; // success.
        }
    }
    return false;
    // throw new AddingResourceException("resource.general.error");
}
 
Example 14
Source Project: pega-tracerviewer   File: TraceEvent.java    License: Apache License 2.0 4 votes vote down vote up
protected void setName(Element traceEventElement) {

        Element element = traceEventElement.element("EventKey");

        if (element != null) {
            name = element.getText();
        } else {
            element = traceEventElement.element("InstanceName");

            if (element != null) {
                name = element.getText();
            }
        }

        if ((name != null) && (!"".equals(name))) {

            if (isInstanceHandle(name)) {

                Attribute attribute = traceEventElement.attribute("inskey");

                if (attribute != null) {

                    attribute = traceEventElement.attribute("keyname");

                    if (attribute != null) {

                        name = attribute.getText();

                        if (isDataPageEventKey()) {
                            name = buildActivityName(name);
                            name = buildDataPageDisplayName(name);
                        }
                    }

                } else {
                    name = buildActivityName(name);
                }
            } else if (!isInstanceWithKeys(name)) {
                name = buildActivityName(name);
            }
        }
    }
 
Example 15
public void initialise(Element element, NamespacePrefixResolver nspr, PermissionModel permissionModel)
{
    name = element.attributeValue(NAME);
    
    for (Iterator rpit = element.elementIterator(REQUIRED_PERMISSION); rpit.hasNext(); /**/)
    {
        QName qName;
        Element requiredPermissionElement = (Element) rpit.next();
        Attribute typeAttribute = requiredPermissionElement.attribute(RP_TYPE);
        if (typeAttribute != null)
        {
            qName = QName.createQName(typeAttribute.getStringValue(), nspr);
        }
        else
        {
            qName = typeQName;
        }

        String requiredName = requiredPermissionElement.attributeValue(RP_NAME);

        RequiredPermission.On on;
        String onString = requiredPermissionElement.attributeValue(RP_ON);
        if (onString.equalsIgnoreCase(NODE_ENTRY))
        {
            on = RequiredPermission.On.NODE;
        }
        else if (onString.equalsIgnoreCase(PARENT_ENTRY))
        {
            on = RequiredPermission.On.PARENT;
        }
        else if (onString.equalsIgnoreCase(CHILDREN_ENTRY))
        {
            on = RequiredPermission.On.CHILDREN;
        }
        else
        {
            throw new PermissionModelException("Required permission must specify parent or node for the on attribute.");
        }
        
        boolean implies = false;
        Attribute impliesAttribute = requiredPermissionElement.attribute(RP_IMPLIES);
        if (impliesAttribute != null)
        {
            implies = Boolean.parseBoolean(impliesAttribute.getStringValue());
        }
        
        RequiredPermission rq = new RequiredPermission(qName, requiredName, on, implies);
        
        requiredPermissions.add(rq);
    }
}
 
Example 16
private static void makeIdentifier(Element node, SimpleValue model, Mappings mappings) {

		// GENERATOR
		Element subnode = node.element( "generator" );
		if ( subnode != null ) {
			model.setIdentifierGeneratorStrategy( subnode.attributeValue( "class" ) );

			Properties params = new Properties();

			if ( mappings.getSchemaName() != null ) {
				params.setProperty( PersistentIdentifierGenerator.SCHEMA, mappings.getSchemaName() );
			}
			if ( mappings.getCatalogName() != null ) {
				params.setProperty( PersistentIdentifierGenerator.CATALOG, mappings.getCatalogName() );
			}

			Iterator iter = subnode.elementIterator( "param" );
			while ( iter.hasNext() ) {
				Element childNode = (Element) iter.next();
				params.setProperty( childNode.attributeValue( "name" ), childNode.getText() );
			}

			model.setIdentifierGeneratorProperties( params );
		}

		model.getTable().setIdentifierValue( model );

		// ID UNSAVED-VALUE
		Attribute nullValueNode = node.attribute( "unsaved-value" );
		if ( nullValueNode != null ) {
			model.setNullValue( nullValueNode.getValue() );
		}
		else {
			if ( "assigned".equals( model.getIdentifierGeneratorStrategy() ) ) {
				model.setNullValue( "undefined" );
			}
			else {
				model.setNullValue( null );
			}
		}
	}
 
Example 17
Source Project: olat   File: TextMarkerManagerImpl.java    License: Apache License 2.0 4 votes vote down vote up
/**
*/
  @Override
  public List<TextMarker> loadTextMarkerList(VFSLeaf textMarkerFile) {
      if (textMarkerFile == null) {
          // filename not defined at all
          return new ArrayList<TextMarker>();
      }
      XMLParser parser = new XMLParser();
      InputStream stream = textMarkerFile.getInputStream();
      if (stream == null) {
          // e.g. file was removed
          return new ArrayList<TextMarker>();
      }
      Document doc = parser.parse(stream, false);
      Element root = doc.getRootElement();
      if (root == null) {
          // file was empty;
          return new ArrayList<TextMarker>();
      }
      // Do version check. Not needed now, for future lazy migration code...
      Attribute versionAttribute = root.attribute(XML_VERSION_ATTRIBUTE);
      int version = (versionAttribute == null ? 1 : Integer.parseInt(versionAttribute.getStringValue()));
      if (version != VERSION) {
          // complain about version conflict or solve it
          throw new OLATRuntimeException("Could not load glossary entries due to version conflict. Loaded version was::" + version, null);
      }
      // parse text marker objects and put them into a list
      List markersElements = root.elements("textMarker");
      List<TextMarker> markers = new ArrayList<TextMarker>();
      Iterator iter = markersElements.iterator();
      while (iter.hasNext()) {
          Element textMarkerElement = (Element) iter.next();
          TextMarker textMarker = new TextMarker(textMarkerElement);
          markers.add(textMarker);
      }
      try {
          stream.close();
      } catch (IOException e) {
          throw new OLATRuntimeException(this.getClass(), "Error while closing text marker file stream", e);
      }
      return markers;
  }
 
Example 18
protected String parseString(Element element, String name) {
    Attribute attribute = element.attribute(name);
    return attribute == null ? null : attribute.getValue();
}
 
Example 19
Source Project: pega-tracerviewer   File: TraceEvent.java    License: Apache License 2.0 3 votes vote down vote up
protected void setRuleSet(Element traceEventElement) {

        Attribute attribute = traceEventElement.attribute("rsname");

        if (attribute != null) {
            ruleSet = attribute.getText();
        }

        attribute = traceEventElement.attribute("rsvers");

        if (attribute != null) {
            ruleSet = ruleSet + " " + attribute.getText();
        }

    }
 
Example 20
public static void bindOneToOne(Element node, OneToOne oneToOne, String path, boolean isNullable,
		Mappings mappings) throws MappingException {

	bindColumns( node, oneToOne, isNullable, false, null, mappings );

	Attribute constrNode = node.attribute( "constrained" );
	boolean constrained = constrNode != null && constrNode.getValue().equals( "true" );
	oneToOne.setConstrained( constrained );

	oneToOne.setForeignKeyType( constrained ?
			ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT :
			ForeignKeyDirection.FOREIGN_KEY_TO_PARENT );

	initOuterJoinFetchSetting( node, oneToOne );
	initLaziness( node, oneToOne, mappings, true );

	oneToOne.setEmbedded( "true".equals( node.attributeValue( "embed-xml" ) ) );

	Attribute fkNode = node.attribute( "foreign-key" );
	if ( fkNode != null ) oneToOne.setForeignKeyName( fkNode.getValue() );

	Attribute ukName = node.attribute( "property-ref" );
	if ( ukName != null ) oneToOne.setReferencedPropertyName( ukName.getValue() );

	oneToOne.setPropertyName( node.attributeValue( "name" ) );

	oneToOne.setReferencedEntityName( getEntityName( node, mappings ) );

	validateCascade( node, path );
}