Java Code Examples for org.dom4j.Element

The following are top voted examples for showing how to use org.dom4j.Element. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: joai-project   File: EditorRenderer.java   Source Code and License 7 votes vote down vote up
/**
 *  Create label for a mulitBoxLabel element that will collapse the mulitBox
 *  input.<P>
 *
 *  Based on getComplexTypeLabel, but will always display collapse widget,
 *  rather than first testing for nodeIsExpandable as getComplexTypeLabel does.
 *  <P>
 *
 *  Depends on the multibox input having an id and display style initialized to
 *  value of collapseBean.displayState.
 *
 * @param  xpath  NOT YET DOCUMENTED
 * @return        The multiBoxLabel value
 */
public Label getMultiBoxLabel(String xpath) {
	ComplexTypeLabel labelObj = getComplexTypeLabel(xpath);
	Element alwaysExpandable = df.createElement("c__if")
		.addAttribute("test", "${true}");
	Element labelLink = alwaysExpandable.addElement("a")
		.addAttribute("href", "javascript__toggleDisplayState(" + RendererHelper.jspQuotedString("${id}") + ");");

	Element notExpandableTest = df.createElement("c__if")
		.addAttribute("test", "${false}");

	labelObj.isExpandableTest = alwaysExpandable.createCopy();
	labelObj.notExpandableTest = notExpandableTest.createCopy();
	labelObj.collapseWidget = getCollapseWidget().createCopy();
	return labelObj;
}
 
Example 2
Project: joai-project   File: MdeComplexType.java   Source Code and License 6 votes vote down vote up
/**
 *  Create "choose" controller for the case where an empty requiredMultiSelect
 *  node is closed. Called from renderComplexTypeConcrete, this controller
 *  provides a prompt for user when the required multiselect boxes are empty
 *  and not visible
 *
 * @return    The requiredMultiSelectControl value
 */
public Element getRequiredMultiSelectControl() {

	Element actionElement = df.createElement("span")
		.addAttribute("class", "action-button");

	// test to see if child node (the multiSelect) is empty
	Element isEmptyTest = actionElement.addElement("logic__equal")
		.addAttribute("name", formBeanName)
		.addAttribute("property", "nodeIsEmpty(" + xpath + ")")
		.addAttribute("value", "true");

	// test to see if the node is closed
	Element isOpenTest = isEmptyTest.addElement("c__if")
		.addAttribute("test", "${not " + formBeanName + ".collapseBean.isOpen}");

	//  "choose" controller link that toogles DisplayState of node
	Element chooseController = isOpenTest.addElement("a")
		.addAttribute("href", "javascript__toggleDisplayState(" + RendererHelper.jspQuotedString("${id}") + ")");
	chooseController.setText("choose");

	return actionElement;
}
 
Example 3
Project: PackagePlugin   File: FileUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 摸查项目输出目录
 * <p>
 * @param projectPath
 * @param kind        output 或 src
 * @return
 */
public static String readXML(String projectPath, String kind) {
    try {
        SAXReader saxReader = new SAXReader();
        File classpath = new File(projectPath + "/.classpath");
        if (classpath.exists()) {
            Document document = saxReader.read(classpath);
            List<Element> out = (List<Element>) document.selectNodes("/classpath/classpathentry[@kind='" + kind + "']");
            String tmp = "";
            for (Element out1 : out) {
                String combineaccessrules = out1.attributeValue("combineaccessrules");
                if ("false".equals(combineaccessrules) && "src".equals(kind)) {
                    continue;
                }
                tmp += out1.attributeValue("path") + ",";
            }
            return tmp.isEmpty() ? tmp : tmp.substring(0, tmp.length() - 1);
        }
    } catch (DocumentException ex) {
        MainFrame.LOGGER.log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, ex.getLocalizedMessage());
    }
    return "";
}
 
Example 4
Project: bdf2   File: ModelBuilder.java   Source Code and License 6 votes vote down vote up
private Element buildValidatorElement(Validator validator){
	BaseElement element=new BaseElement("Validator");
	int pos=validator.getName().lastIndexOf("Validator");
	String validatorType=validator.getName().substring(0,pos);
	validatorType=validatorType.substring(0,1).toLowerCase()+validatorType.substring(1,validatorType.length());
	element.addAttribute("type",validatorType);
	if(validator.getProperties()!=null){
		for(ValidatorProperty vp:validator.getProperties()){
			if(StringHelper.isNotEmpty(vp.getName()) && StringHelper.isNotEmpty(vp.getValue())){
				Element propertyElement=createPropertyElement(vp.getName(),vp.getValue());
				element.add(propertyElement);					
			}
		}
	}
	return element;
}
 
Example 5
Project: lams   File: JPAOverriddenAnnotationReader.java   Source Code and License 6 votes vote down vote up
private NamedStoredProcedureQueries getNamedStoredProcedureQueries(Element tree, XMLContext.Default defaults) {
	List<NamedStoredProcedureQuery> queries = buildNamedStoreProcedureQueries( tree, defaults );
	if ( defaults.canUseJavaAnnotations() ) {
		NamedStoredProcedureQuery annotation = getPhysicalAnnotation( NamedStoredProcedureQuery.class );
		addNamedStoredProcedureQueryIfNeeded( annotation, queries );
		NamedStoredProcedureQueries annotations = getPhysicalAnnotation( NamedStoredProcedureQueries.class );
		if ( annotations != null ) {
			for ( NamedStoredProcedureQuery current : annotations.value() ) {
				addNamedStoredProcedureQueryIfNeeded( current, queries );
			}
		}
	}
	if ( queries.size() > 0 ) {
		AnnotationDescriptor ad = new AnnotationDescriptor( NamedStoredProcedureQueries.class );
		ad.setValue( "value", queries.toArray( new NamedStoredProcedureQuery[queries.size()] ) );
		return AnnotationFactory.create( ad );
	}
	else {
		return null;
	}
}
 
Example 6
Project: joai-project   File: MdeNode.java   Source Code and License 6 votes vote down vote up
/**
 *  Insert an HTML comment into the html source.
 *
 * @param  e  NOT YET DOCUMENTED
 * @param  s  NOT YET DOCUMENTED
 */
protected void insertHtmlComment(Element e, String s) {
	prtln("\ninsertHtmlComment()");
	Element comment = df.createElement("st__htmlComment");
	comment.setText(s);
	Element parent = e.getParent();

	if (parent != null) {
		List children = parent.elements();
		int index = children.indexOf(e);
		children.add(index, comment);
	}
	else {
		// prtlnErr("PARENT NOT FOUND");
	}
}
 
Example 7
Project: bdf2   File: AbstractConverter.java   Source Code and License 6 votes vote down vote up
protected void fillDataSetAndDataPathProperty(Element element,ComponentInfo component,boolean isCollection){
	String[] dataSetDataPath=this.retriveDataSetAndDataPath(component);
	if(dataSetDataPath!=null){
		if(StringHelper.isNotEmpty(dataSetDataPath[0])){
			BaseElement dataSetElement=new BaseElement("Property");	
			dataSetElement.addAttribute("name", "dataSet");
			dataSetElement.setText(dataSetDataPath[0]);
			element.add(dataSetElement);
		}
		if(StringHelper.isNotEmpty(dataSetDataPath[1]) && !hasDataPath(component)){
			BaseElement dataPathElement=new BaseElement("Property");
			dataPathElement.addAttribute("name", "dataPath");
			String dataPath=dataSetDataPath[1];
			if(!isCollection){
				int pos=dataPath.lastIndexOf(".");
				if(pos>0){
					dataPath=dataPath.substring(0,pos)+".#"+dataPath.substring(pos+1,dataPath.length());
				}					
			}
			
			dataPathElement.setText(dataPath);
			element.add(dataPathElement);
		}
	}
}
 
Example 8
Project: bdf2   File: ModelBuilder.java   Source Code and License 6 votes vote down vote up
private Element createReferencePropertyDef(Entity entity,RuleSet ruleSet,boolean isSelf){
	String nodeName=Reference.class.getSimpleName();
	Rule rule=ruleSet.getRule(nodeName);
	Element referenceDefElement=new BaseElement(rule.getNodeName());
	referenceDefElement.addAttribute("name", entity.getName());
	//创建dataType与dataProvider属性
	Element dataTypeElement=createPropertyElement("dataType",null);
	if(isSelf){
		dataTypeElement.setText("[SELF]");			
	}else{
		dataTypeElement.setText("["+ entity.getName()+"]");						
	}
	referenceDefElement.add(dataTypeElement);
	String entityName=entity.getName();
	Element dataProviderElement=createPropertyElement("dataProvider","dataProvider"+entityName.substring(0,1).toUpperCase()+entityName.substring(1,entityName.length()));
	if(entity.getPageSize()>0){
		Element pageSizeElement=createPropertyElement("pageSize",String.valueOf(entity.getPageSize()));
		referenceDefElement.add(pageSizeElement);
	}
	referenceDefElement.add(dataProviderElement);
	referenceDefElement.add(createReferenceParameterElement(entity));
	return referenceDefElement;
}
 
Example 9
Project: lams   File: HbmBinder.java   Source Code and License 6 votes vote down vote up
private static void parseFilterDef(Element element, Mappings mappings) {
	String name = element.attributeValue( "name" );
	LOG.debugf( "Parsing filter-def [%s]", name );
	String defaultCondition = element.getTextTrim();
	if ( StringHelper.isEmpty( defaultCondition ) ) {
		defaultCondition = element.attributeValue( "condition" );
	}
	HashMap paramMappings = new HashMap();
	Iterator params = element.elementIterator( "filter-param" );
	while ( params.hasNext() ) {
		final Element param = (Element) params.next();
		final String paramName = param.attributeValue( "name" );
		final String paramType = param.attributeValue( "type" );
		LOG.debugf( "Adding filter parameter : %s -> %s", paramName, paramType );
		final Type heuristicType = mappings.getTypeResolver().heuristicType( paramType );
		LOG.debugf( "Parameter heuristic type : %s", heuristicType );
		paramMappings.put( paramName, heuristicType );
	}
	LOG.debugf( "Parsed filter-def [%s]", name );
	FilterDefinition def = new FilterDefinition( name, defaultCondition, paramMappings );
	mappings.addFilterDefinition( def );
}
 
Example 10
Project: uflo   File: ForeachParser.java   Source Code and License 6 votes vote down vote up
public Object parse(Element element, long processId, boolean parseChildren) {
	ForeachNode node=new ForeachNode();
	node.setProcessId(processId);
	parseNodeCommonInfo(element, node);
	node.setSequenceFlows(parseFlowElement(element,processId,parseChildren));
	String type=element.attributeValue("foreach-type");
	if(StringUtils.isNotEmpty(type)){
		node.setForeachType(ForeachType.valueOf(type));			
	}
	node.setVariable(unescape(element.attributeValue("var")));
	if(StringUtils.isNotBlank(element.attributeValue("process-variable"))){
		node.setProcessVariable(unescape(element.attributeValue("process-variable")));			
	}else{
		node.setProcessVariable(unescape(element.attributeValue("in")));						
	}
	node.setHandlerBean(unescape(element.attributeValue("handler-bean")));
	NodeDiagram diagram=parseDiagram(element);
	diagram.setIcon("/icons/foreach.svg");
	diagram.setShapeType(ShapeType.Circle);
	diagram.setBorderWidth(1);
	node.setDiagram(diagram);
	return node;
}
 
Example 11
Project: minlia-iot   File: AbstractApiComponent.java   Source Code and License 6 votes vote down vote up
/**
 * 获取节点值
 * @param root
 * @param clazz
 * @param name
 * @return
 */
@SuppressWarnings("unchecked")
protected Optional<Object> elementValue(Element root, Class<?> clazz, String name) {
    Optional<String> elementTextOptional = elementText(root, name);
    if (elementTextOptional.isPresent()) {
        if (clazz == Integer.class) {
            return Optional.of(new Integer(elementTextOptional.get()));
        } else if (clazz == Long.class) {
            return Optional.of(new Long(elementTextOptional.get()));
        } else if (Enum.class.isAssignableFrom(clazz)) {
            try {
                Class enumClass = Class.forName(clazz.getName());
                return Optional.of(Enum.valueOf(enumClass, elementTextOptional.get()));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                return Optional.empty();
            }
        } else {
            return Optional.of(elementTextOptional.get());
        }
    } else {
        return Optional.empty();
    }
}
 
Example 12
Project: joai-project   File: Choice.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the members that could be added to the specified instanceElement
 * according to schema constraints.
 */
public List getAcceptableMembers (Element instanceElement) { 
	prtln ("\ngetAcceptableMembers with instanceElement:");
	prtln (instanceElement.asXML());
	ChoiceGuard guard;
	try {
		guard = new ChoiceGuard (this, instanceElement);
	} catch (Exception e) {
		prtln ("ChoiceGard init error: " + e.getMessage());
		return new ArrayList();
	}
	prtln ("about to call ChoiceGuard getAcceptableMembers()");
	List members = guard.getAcceptableMembers();
	prtln ("acceptable members:");
	printMemberList (members);
	return members;
}
 
Example 13
Project: bdf2   File: DecisionConverter.java   Source Code and License 6 votes vote down vote up
public JpdlInfo toJpdl(Element element) {
	BaseElement targetElement=new BaseElement("decision");
	String name=this.buildCommonJpdlElement(element, targetElement);
	String decisionType=element.attributeValue("decisionType");
	String decisionValue=element.attributeValue("decisionValue");
	if(decisionType.equals("handler")){
		BaseElement handlerElement=new BaseElement("handler");
		handlerElement.addAttribute("class", decisionValue);
		targetElement.add(handlerElement);
	}else{
		targetElement.addAttribute("expr",decisionValue);
	}
	JpdlInfo info=new JpdlInfo();
	info.setName(name);
	info.setElement(targetElement);
	return info;
}
 
Example 14
Project: uflo   File: EndParser.java   Source Code and License 6 votes vote down vote up
public Object parse(Element element,long processId,boolean parseChildren) {
	EndNode node=new EndNode();
	node.setProcessId(processId);
	parseNodeCommonInfo(element, node);
	String terminate=element.attributeValue("terminate");
	if(StringUtils.isNotEmpty(terminate)){
		node.setTerminate(Boolean.valueOf(terminate));
	}
	NodeDiagram diagram=parseDiagram(element);
	if(node.isTerminate()){
		diagram.setIcon("/icons/end-terminate.svg");
	}else{
		diagram.setIcon("/icons/end.svg");
	}
	diagram.setShapeType(ShapeType.Circle);
	diagram.setBorderWidth(1);
	node.setDiagram(diagram);
	return node;
}
 
Example 15
Project: Divinity_Original_Sin_2_zhCN   File: DOS2ToMap.java   Source Code and License 6 votes vote down vote up
@Override
public Map toMap(Document document) {
  Map<String, String> m = new HashMap<String, String>();
  /**
   * <contentList> <content contentuid=
   * "h00007224gb454g4b8bgb762g7865d9ee3dbb">如果不是这样的话!哈,开玩笑啦,我们在一起很合适,就像面包上的果酱。你想和我组队吗?我敢说你们需要一点野兽风味!</content>
   * <content contentuid="h0001d8b9g13d6g4605g85e9g708fe1e537c8">定制</content> </contentList>
   */
  // 获取根节点元素对象
  Element root = document.getRootElement();
  // 子节点
  List<Element> list = root.elements();
  // 使用递归
  Iterator<Element> iterator = list.iterator();
  while (iterator.hasNext()) {
    Element e = iterator.next();
    Attribute attribute = e.attribute("contentuid");
    m.put(attribute.getValue(), e.getText());
  }
  return m;
}
 
Example 16
Project: etagate   File: GateSetting.java   Source Code and License 6 votes vote down vote up
public void parse(URL is) {
		SAXReader saxReader = new SAXReader();

		try {
			Document document = saxReader.read(is);
			Element root = document.getRootElement();
			
			collectProperty(root);
			parseAuth(root);
			parseApp(root);
//			
//			System.out.println("====================parse ok=============");
//			System.out.println(properties.toString());
//			System.out.println(authSetting.toString());
		} catch (DocumentException e) {
			log.error("Load route.xml error.");
			e.printStackTrace();
		}

	}
 
Example 17
Project: bdf2   File: TabControlConverter.java   Source Code and License 6 votes vote down vote up
public Element convert(ComponentInfo component, RuleSet ruleSet,
		Element rootElement) throws Exception {
	String name=TabControl.class.getSimpleName();
	XmlNode node=TabControl.class.getAnnotation(XmlNode.class);
	if(node!=null && StringHelper.isNotEmpty(node.nodeName())){
		name=node.nodeName();
	}
	Rule rule=ruleSet.getRule(name);
	BaseElement element = fillElement(component,ruleSet,rule,rootElement);
	if(component.getChildren()!=null){
		for(ComponentInfo c:component.getChildren()){
			this.buildChildren(element,c,ruleSet,rootElement);							
		}
	}
	return element;
}
 
Example 18
Project: SimpleController   File: XmlGenerator.java   Source Code and License 6 votes vote down vote up
private Document readDocument(String path,String name, int age) throws DocumentException{
	SAXReader reader=new SAXReader();
	Document document=reader.read(path);
	Element root=document.getRootElement();
	List listOfTextView=document.selectNodes("view/body/form/textView");
	for(Iterator<Element> i=listOfTextView.listIterator();i.hasNext();){
		Element textView=i.next();
		if(textView.selectSingleNode("name").getText().equals("userName")){
			textView.selectSingleNode("value").setText(name);
		}
		if(textView.selectSingleNode("name").getText().equals("userAge")){
			textView.selectSingleNode("value").setText(""+age);
		}
	}
	System.out.println(document);
	return document;
}
 
Example 19
Project: lams   File: XMLContext.java   Source Code and License 6 votes vote down vote up
private List<String> addEntityListenerClasses(Element element, String packageName, List<String> addedClasses) {
	List<String> localAddedClasses = new ArrayList<String>();
	Element listeners = element.element( "entity-listeners" );
	if ( listeners != null ) {
		@SuppressWarnings( "unchecked" )
		List<Element> elements = listeners.elements( "entity-listener" );
		for (Element listener : elements) {
			String listenerClassName = buildSafeClassName( listener.attributeValue( "class" ), packageName );
			if ( classOverriding.containsKey( listenerClassName ) ) {
				//maybe switch it to warn?
				if ( "entity-listener".equals( classOverriding.get( listenerClassName ).getName() ) ) {
					LOG.duplicateListener( listenerClassName );
					continue;
				}
				throw new IllegalStateException("Duplicate XML entry for " + listenerClassName);
			}
			localAddedClasses.add( listenerClassName );
			classOverriding.put( listenerClassName, listener );
		}
	}
	LOG.debugf( "Adding XML overriding information for listeners: %s", localAddedClasses );
	addedClasses.addAll( localAddedClasses );
	return localAddedClasses;
}
 
Example 20
Project: uflo   File: AbstractParser.java   Source Code and License 6 votes vote down vote up
protected NodeDiagram parseDiagram(Element element){
	NodeDiagram diagram=new NodeDiagram();
	String g=element.attributeValue("g");
	String name=element.attributeValue("name");
	String label=element.attributeValue("label");
	diagram.setLabel(label);			
	diagram.setName(name);
	if(StringUtils.isNotBlank(g)){
		String[] info=g.split(",");
		if(info.length!=4){
			throw new IllegalArgumentException("Node "+element.attributeValue("name")+" diagram info is invalide!");
		}
		diagram.setX(Integer.valueOf(info[0]));
		diagram.setY(Integer.valueOf(info[1]));
		diagram.setWidth(Integer.valueOf(info[2]));
		diagram.setHeight(Integer.valueOf(info[3]));			
	}
	String x=element.attributeValue("x");
	String y=element.attributeValue("y");
	String width=element.attributeValue("width");
	String height=element.attributeValue("height");
	if(StringUtils.isNotBlank(x)){
		diagram.setX(Integer.valueOf(x));
	}
	if(StringUtils.isNotBlank(y)){
		diagram.setY(Integer.valueOf(y));
	}
	if(StringUtils.isNotBlank(width)){
		diagram.setWidth(Integer.valueOf(width));
	}
	if(StringUtils.isNotBlank(height)){
		diagram.setHeight(Integer.valueOf(height));
	}
	return diagram;
}
 
Example 21
Project: bdf2   File: AbstractConverter.java   Source Code and License 6 votes vote down vote up
protected String buildCommonJpdlElement(Element element,Element targetElement){
	String name=element.attributeValue("name");
	String desc=element.attributeValue("desc");
	targetElement.addAttribute("name",name);
	Element descElement=new BaseElement("description");
	if(StringUtils.isNotEmpty(desc)){
		descElement.setText(desc);			
	}
	int width=Integer.parseInt(element.attributeValue("width"));
	int height=Integer.parseInt(element.attributeValue("height"));
	int x=Integer.parseInt(element.attributeValue("x"));
	int y=Integer.parseInt(element.attributeValue("y"));
	x=x-(width/2);
	y=y-(height/2);
	String g=x+","+y+","+width+","+height;
	if(this instanceof TransitionConverter){
		g=x+","+y;			
	}
	targetElement.addAttribute("g", g);
	/*for(Object obj:element.attributes()){
		Attribute attr=(Attribute)obj;
		targetElement.addAttribute(attr.getName(),attr.getValue());
	}*/
	return name;
}
 
Example 22
Project: urule   File: ParenParser.java   Source Code and License 6 votes vote down vote up
@Override
public ParenValue parse(Element element) {
	ParenValue value=new ParenValue();
	for(Object obj:element.elements()){
		if(obj==null || !(obj instanceof Element)){
			continue;
		}
		Element ele=(Element)obj;
		if(valueParser.support(ele.getName())){
			value.setValue(valueParser.parse(ele));
		}else if(arithmeticParser.support(ele.getName())){
			value.setArithmetic(arithmeticParser.parse(ele));
		}
	}
	return value;
}
 
Example 23
Project: unitimes   File: CourseOfferingExport.java   Source Code and License 6 votes vote down vote up
protected void exportCourse(Element courseElement, CourseOffering course, Session session) {
    courseElement.addAttribute("id", (course.getExternalUniqueId()!=null?course.getExternalUniqueId():course.getUniqueId().toString()));
    courseElement.addAttribute("subject", course.getSubjectArea().getSubjectAreaAbbreviation());
    courseElement.addAttribute("courseNbr", course.getCourseNbr());
    if (course.getReservation() != null)
    	courseElement.addAttribute("reserved", course.getReservation().toString());
    courseElement.addAttribute("controlling", course.isIsControl()?"true":"false");
    if (course.getConsentType()!=null)
    	courseElement.addElement("consent").addAttribute("type", course.getConsentType().getReference());
    if (course.getTitle()!=null)
        courseElement.addAttribute("title", course.getTitle());
    if (course.getScheduleBookNote()!=null)
        courseElement.addAttribute("scheduleBookNote", course.getScheduleBookNote());
    for (Iterator i=course.getCreditConfigs().iterator();i.hasNext();) {
        CourseCreditUnitConfig credit = (CourseCreditUnitConfig)i.next();
        exportCredit(courseElement.addElement("courseCredit"), credit, session);
    }
}
 
Example 24
Project: atlas   File: ManifestFileUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Delete the custom header
 *
 * @param document
 * @param manifestOptions
 */
private static void removeCustomLaunches(Document document, ManifestOptions manifestOptions) {
    if (null == manifestOptions) {
        return;
    }
    Element root = document.getRootElement();// Get the root node
    // Update launch information
    if (manifestOptions.getRetainLaunches() != null && manifestOptions.getRetainLaunches().size() > 0) {
        List<? extends Node> nodes = root.selectNodes(
            "//activity/intent-filter/category|//activity-alias/intent-filter/category");
        for (Node node : nodes) {
            Element e = (Element)node;
            if ("android.intent.category.LAUNCHER".equalsIgnoreCase(e.attributeValue("name"))) {
                Element activityElement = e.getParent().getParent();
                String activiyName = activityElement.attributeValue("name");
                if (!manifestOptions.getRetainLaunches().contains(activiyName)) {
                    if (activityElement.getName().equalsIgnoreCase("activity-alias")) {
                        activityElement.getParent().remove(activityElement);
                    } else {
                        e.getParent().remove(e);
                    }
                }
            }
        }
    }
}
 
Example 25
Project: unitimes   File: PageAccessFilter.java   Source Code and License 6 votes vote down vote up
public void init(FilterConfig cfg) throws ServletException {
	iContext = cfg.getServletContext();
	try {
		Document config = (new SAXReader()).read(cfg.getServletContext().getResource(cfg.getInitParameter("config")));
		for (Iterator i=config.getRootElement().element("action-mappings").elementIterator("action"); i.hasNext();) {
			Element action = (Element)i.next();
			String path = action.attributeValue("path");
			String input = action.attributeValue("input");
			if (path!=null && input!=null) {
				iPath2Tile.put(path+".do", input);
			}
		}
	} catch (Exception e) {
		sLog.error("Unable to read config "+cfg.getInitParameter("config")+", reason: "+e.getMessage());
	}
	if (cfg.getInitParameter("debug-time")!=null) {
		debugTime = Long.parseLong(cfg.getInitParameter("debug-time"));
	}
	if (cfg.getInitParameter("dump-time")!=null) {
		dumpTime = Long.parseLong(cfg.getInitParameter("dump-time"));
	}
	if (cfg.getInitParameter("session-attributes")!=null) {
		dumpSessionAttribues = Boolean.parseBoolean(cfg.getInitParameter("session-attributes"));
	}
}
 
Example 26
Project: sbc-qsystem   File: QIndicatorBoardMonitor.java   Source Code and License 6 votes vote down vote up
@Override
public Element getConfig() {
    final File boardFile = new File(getConfigFile());
    if (boardFile.exists()) {
        try {
            return new SAXReader(false).read(boardFile).getRootElement();
        } catch (DocumentException ex) {
            QLog.l().logger()
                .error("Невозможно прочитать файл конфигурации главного табло. " + ex
                    .getMessage());
            return DocumentHelper.createElement("Ответ");
        }
    } else {
        QLog.l().logger()
            .warn("Файл конфигурации главного табло \"" + configFile + "\" не найден. ");
        return DocumentHelper.createElement("Ответ");
    }
}
 
Example 27
Project: ats-framework   File: XmlText.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the child XPaths of a XML element
 *
 * @return the XPath of the XML element.
 * @return the child XPaths of a XML element
 * @throws XMLException
 */
@PublicAtsApi
public String[] getElementXPaths(
                                  String xpath ) throws XMLException {

    ArrayList<String> elementXPaths = new ArrayList<>(1);

    if (StringUtils.isNullOrEmpty(xpath)) {
        throw new XMLException("Null/empty xpath is not allowed.");
    }

    Element element = findElement(xpath);

    if (element == null) {
        throw new XMLException("'" + xpath + "' is not a valid path");
    }

    Iterator<Element> it = element.elementIterator();

    while (it.hasNext()) {
        elementXPaths.add(it.next().getUniquePath());
    }

    return elementXPaths.toArray(new String[elementXPaths.size()]);
}
 
Example 28
Project: ats-framework   File: XmlText.java   Source Code and License 6 votes vote down vote up
/**
 * Append text to a XML element.
 *
 * @param xpath XPath , pointing to a XML element
 * @param text the text , which will be appended to a XML element
 * @return this instance
 * @throws XMLException
 */
@PublicAtsApi
public XmlText appendText(
                           String xpath,
                           String text ) throws XMLException {

    if (StringUtils.isNullOrEmpty(xpath)) {
        throw new XMLException("Null/empty xpath is not allowed.");
    }

    if (StringUtils.isNullOrEmpty(text)) {
        throw new XMLException("Null/empty text is not allowed.");
    }

    Element element = findElement(xpath);

    if (element == null) {
        throw new XMLException("'" + xpath + "' is not a valid path");
    }

    element.addText(text);

    return this;
}
 
Example 29
Project: unitimes   File: LowercaseTableNames.java   Source Code and License 6 votes vote down vote up
protected void writeAttributes(Element element) throws IOException {
    for (int i = 0, size = element.attributeCount(); i < size; i++) {
        Attribute attribute = element.attribute(i);
           char quote = format.getAttributeQuoteCharacter();
           if (element.attributeCount() > 2) {
               writePrintln();
               indent();
               writer.write(format.getIndent());
           } else {
           	writer.write(" ");
           }
           writer.write(attribute.getQualifiedName());
           writer.write("=");
           writer.write(quote);
           writeEscapeAttributeEntities(attribute.getValue());
           writer.write(quote);
    }
}
 
Example 30
Project: joai-project   File: DcsViewRecord.java   Source Code and License 6 votes vote down vote up
private void renderMaster () throws Exception {
	Element base = df.createElement("div");
	/* base.addAttribute ("class", "level--1"); */
	List elements = instanceDocument.getRootElement().elements();
	// prtln("batchRenderAndWrite found " + elements.size() + " elements");
	for (Iterator i = elements.iterator(); i.hasNext(); ) {
		Element child = (Element) i.next();
		String xpath = child.getPath();
		String pageName = XPathUtils.getNodeName(xpath);
		Element include = base.addElement("jsp__include");
		include.addAttribute("page", getMasterComponentPath (pageName));
	}
	
	File dest = getJspDest (null);
	if (!writeJsp(base, dest, this.getMasterJspHeader())) {
		throw new Exception ("renderMaster(): failed to write jsp to " + dest);
	}
	
}
 
Example 31
Project: ofmeet-openfire-plugin   File: OfMeetPlugin.java   Source Code and License 6 votes vote down vote up
public void sessionDestroyed(Session session)
{
	Log.debug("OfMeet Plugin -  sessionDestroyed "+ session.getAddress().toString() + "\n" + ((ClientSession) session).getPresence().toXML());

	boolean skypeAvailable = XMPPServer.getInstance().getPluginManager().getPlugin("ofskype") != null;

	if (OfMeetAzure.skypeids.containsKey(session.getAddress().getNode()))
	{
		String sipuri = OfMeetAzure.skypeids.remove(session.getAddress().getNode());

		IQ iq = new IQ(IQ.Type.set);
		iq.setFrom(session.getAddress());
		iq.setTo(XMPPServer.getInstance().getServerInfo().getXMPPDomain());

		Element child = iq.setChildElement("request", "http://igniterealtime.org/protocol/ofskype");
		child.setText("{'action':'stop_skype_user', 'sipuri':'" + sipuri + "'}");
		XMPPServer.getInstance().getIQRouter().route(iq);

		Log.info("OfMeet Plugin - closing skype session " + sipuri);
	}
}
 
Example 32
Project: iBase4J   File: XmlUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 将List数据类型转换为符合XML格式规范的字符串(基于节点值的方式)
 * 
 * @param pList 传入的List数据(List对象可以是Dto、VO、Domain的属性集)
 * @param pRootNodeName 根节点名称
 * @param pFirstNodeName 行节点名称
 * @return string 返回XML格式字符串
 */
public static final String parseList2XmlBasedNode(List pList, String pRootNodeName, String pFirstNodeName) {
	Document document = DocumentHelper.createDocument();
	Element output = document.addElement(pRootNodeName);
	for (int i = 0; i < pList.size(); i++) {
		Map map = (Map) pList.get(i);
		Element elRow = output.addElement(pFirstNodeName);
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Element leaf = elRow.addElement((String) entry.getKey());
			leaf.setText(String.valueOf(entry.getValue()));
		}
	}
	String outXml = document.asXML().substring(39);
	return outXml;
}
 
Example 33
Project: joai-project   File: AttributeGroup.java   Source Code and License 5 votes vote down vote up
/**
 *  NOT YET DOCUMENTED
 *
 * @return    NOT YET DOCUMENTED
 */
public String toString() {
	String s = "AttributeGroup: " + name;
	s += super.toString();
		String nl = "\n\t";
	for (Iterator i=getAttributes().iterator();i.hasNext();) {
		Element e = (Element)i.next();
		s += nl + e.asXML();
	}
	return s;
}
 
Example 34
Project: unitimes   File: CourseOfferingExport.java   Source Code and License 5 votes vote down vote up
protected void exportAssignment(Element classElement, Assignment assignment, Session session) {
    exportDatePattern(classElement, assignment.getDatePattern(), session);
    exportTimeLocation(classElement, assignment, session);
    exportRooms(classElement, assignment, session);
    if (iClassEvents != null)
    	exportEvent(classElement, iClassEvents.get(assignment.getClassId()), session);
    if (iExportGroupInfos)
    	exportGroupInfos(classElement, assignment, session);
}
 
Example 35
Project: unitimes   File: BaseImport.java   Source Code and License 5 votes vote down vote up
protected String getRequiredStringAttribute(Element element, String attributeName, String elementName) throws Exception{		
	String attributeValue = element.attributeValue(attributeName);
	if (attributeValue == null || attributeValue.trim().length() == 0){
		throw new Exception("For element '" + elementName + "' a '" + attributeName + "' is required");
	} else {
		attributeValue = attributeValue.trim().replace('\u0096', ' ').replace('\u0097', ' ');
	}						
	return(attributeValue);
}
 
Example 36
Project: ARCLib   File: XmlBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void addSiblingNodeTest() throws IOException, SAXException, TransformerException {
    Document doc = DocumentHelper.createDocument(DocumentHelper.createElement("root"));

    Element root = doc.getRootElement();

    Element child = DocumentHelper.createElement("child");
    child.setText("test value 1");

    root.add(child);

    xmlBuilder.addNode(doc, "/root/child", "test value 2", uris.get("ARCLIB"));
    assertThat(doc.asXML(), is("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root><child>test value 1</child><child xmlns=\"http://arclib.lib.cas.cz/ARCLIB_XML\">test value 2</child></root>"));
}
 
Example 37
Project: lams   File: JPAOverriddenAnnotationReader.java   Source Code and License 5 votes vote down vote up
private static void buildIndex(AnnotationDescriptor annotation, Element element){
	List indexElementList = element.elements( "index" );
	Index[] indexes = new Index[indexElementList.size()];
	for(int i=0;i<indexElementList.size();i++){
		Element subelement = (Element)indexElementList.get( i );
		AnnotationDescriptor indexAnn = new AnnotationDescriptor( Index.class );
		copyStringAttribute( indexAnn, subelement, "name", false );
		copyStringAttribute( indexAnn, subelement, "column-list", true );
		copyBooleanAttribute( indexAnn, subelement, "unique" );
		indexes[i] = AnnotationFactory.create( indexAnn );
	}
	annotation.setValue( "indexes", indexes );
}
 
Example 38
Project: iBase4J   File: XmlUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 将XML规范的字符串转为List对象(XML基于节点属性值的方式)
 * 
 * @param pStrXml 传入的符合XML格式规范的字符串
 * @return list 返回List对象
 */
public static final List parseXml2List(String pStrXml) {
	List lst = new ArrayList();
	String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	Document document = null;
	try {
		if (pStrXml.indexOf("<?xml") < 0)
			pStrXml = strTitle + pStrXml;
		document = DocumentHelper.parseText(pStrXml);
	} catch (DocumentException e) {
		log.error("==开发人员请注意:==\n将XML格式的字符串转换为XML DOM对象时发生错误啦!" + "\n详细错误信息如下:", e);
	}
	// 获取到根节点
	Element elRoot = document.getRootElement();
	// 获取根节点的所有子节点元素
	Iterator elIt = elRoot.elementIterator();
	while (elIt.hasNext()) {
		Element el = (Element) elIt.next();
		Iterator attrIt = el.attributeIterator();
		Map map = new HashMap();
		while (attrIt.hasNext()) {
			Attribute attribute = (Attribute) attrIt.next();
			map.put(attribute.getName().toLowerCase(), attribute.getData());
		}
		lst.add(map);
	}
	return lst;
}
 
Example 39
Project: unitimes   File: PointInTimeDataExport.java   Source Code and License 5 votes vote down vote up
private void exportCourseType(CourseType courseType){
	Element courseTypeElement = courseTypesElement.addElement(sCourseTypeElementName);
	courseTypeElement.addAttribute(sUniqueIdAttribute, courseType.getUniqueId().toString());
	courseTypeElement.addAttribute(sReferenceAttribute, courseType.getReference());
	courseTypeElement.addAttribute(sLabelAttribute, courseType.getLabel());
	courseTypeElements.put(courseType.getUniqueId(), courseTypeElement);
}
 
Example 40
Project: wherehowsX   File: XMLFileAnalyzer.java   Source Code and License 5 votes vote down vote up
private void getChildNodes(Element node, String parent) {
    String nodeName = getNodename(node, parent);
    if (!node.getTextTrim().equals(""))
        keyToValues.put(nodeName, node.getTextTrim());

    List<Element> listElement = node.elements();
    for (Element e : listElement) {
        if (!parent.equals(""))
            getChildNodes(e, parent + "." + node.getName());
        else
            getChildNodes(e, node.getName());
    }
}
 
Example 41
Project: wherehowsX   File: XMLFileAnalyzer.java   Source Code and License 5 votes vote down vote up
private String getNodename(Element node, String parent) {
    String nodeName = "";
    if (!parent.equals(""))
        nodeName = parent + "." + node.getName();
    else
        nodeName = node.getName();
    return nodeName;
}
 
Example 42
Project: unitimes   File: CourseTimetableExport.java   Source Code and License 5 votes vote down vote up
protected void exportClass(Element classElement, Class_ clazz, CourseOffering course, Session session) {
    classElement.addAttribute("id", clazz.getUniqueId().toString());
    classElement.addAttribute("subject", course.getSubjectArea().getSubjectAreaAbbreviation());
    classElement.addAttribute("courseNbr", course.getCourseNbr());
    classElement.addAttribute("type", clazz.getItypeDesc().trim());
    classElement.addAttribute("suffix", getClassSuffix(clazz));
    if (clazz.getSchedulingSubpart().getInstrOfferingConfig().isUnlimitedEnrollment())
        classElement.addAttribute("limit", "inf");
    else
        classElement.addAttribute("limit", String.valueOf(clazz.getClassLimit()));
    if (clazz.getSchedulePrintNote()!=null)
        classElement.addAttribute("scheduleNote", clazz.getSchedulePrintNote());
    classElement.addAttribute("studentScheduling", clazz.isEnabledForStudentScheduling()?"true":"false");
    classElement.addAttribute("displayInScheduleBook", clazz.isEnabledForStudentScheduling()?"true":"false");
    classElement.addAttribute("controlling", course.isIsControl()?"true":"false");
    classElement.addAttribute("cancelled", clazz.isCancelled() ? "true" : "false");
    if (clazz.getManagingDept().getSolverGroup() != null)
    	classElement.addAttribute("solver", clazz.getManagingDept().getSolverGroup().getAbbv());
    for (Iterator i=clazz.getChildClasses().iterator();i.hasNext();) {
        Class_ childClazz = (Class_)i.next();
        exportClass(classElement.addElement("class"), childClazz, course, session);
    }
    if (clazz.getCommittedAssignment()!=null)
        exportAssignment(classElement, clazz.getCommittedAssignment(), session);
    else if (clazz.getManagingDept().getSolverGroup()!=null && clazz.getManagingDept().getSolverGroup().getCommittedSolution()!=null) {
        exportArrHours(classElement, clazz, session);
    }
    if (clazz.isDisplayInstructor())
        for (Iterator i=clazz.getClassInstructors().iterator();i.hasNext();) {
            ClassInstructor instructor = (ClassInstructor)i.next(); 
            if (instructor.getInstructor().getExternalUniqueId()!=null)
                exportInstructor(classElement.addElement("instructor"), instructor, session);
        }
}
 
Example 43
Project: unitimes   File: CourseOfferingExport.java   Source Code and License 5 votes vote down vote up
protected void exportEvent(Element classElement, Event event, Session session) {
  	if (event == null) return;
  	List<Meeting> meetings = new ArrayList<Meeting>(event.getMeetings());
  	Collections.sort(meetings, new Comparator<Meeting>() {
	@Override
	public int compare(Meeting m1, Meeting m2) {
		if (m1.equals(m2)) return 0;
		int cmp = m1.getMeetingDate().compareTo(m2.getMeetingDate());
		if (cmp != 0) return cmp;
		cmp = m1.getStartPeriod().compareTo(m2.getStartPeriod());
		if (cmp != 0) return cmp;
		Location l1 = (m1.getLocationPermanentId() == null ? null : iMeetingLocations.get(m1.getLocationPermanentId()));
		Location l2 = (m2.getLocationPermanentId() == null ? null : iMeetingLocations.get(m2.getLocationPermanentId()));
		cmp = (l1 == null ? "" : l1.getLabel()).compareTo(l2 == null ? "" : l2.getLabel());
		if (cmp != 0) return cmp;
		return m1.getUniqueId().compareTo(m2.getUniqueId());
	}
});
      for (Meeting meeting: meetings) {
          if (meeting.getStatus() != Meeting.Status.APPROVED) continue;
          Element meetingElement = classElement.addElement("meeting");
          meetingElement.addAttribute("startDate", sDateFormat.format(meeting.getMeetingDate()));
          meetingElement.addAttribute("endDate", sDateFormat.format(meeting.getMeetingDate()));
          meetingElement.addAttribute("startTime", sTimeFormat.format(meeting.getStartTime()));
          meetingElement.addAttribute("endTime", sTimeFormat.format(meeting.getStopTime()));
          Calendar c = Calendar.getInstance(Locale.US); c.setTime(meeting.getMeetingDate());
          switch (c.get(Calendar.DAY_OF_WEEK)) {
              case Calendar.MONDAY : meetingElement.addAttribute("days","M"); break;
              case Calendar.TUESDAY : meetingElement.addAttribute("days","T"); break;
              case Calendar.WEDNESDAY : meetingElement.addAttribute("days","W"); break;
              case Calendar.THURSDAY : meetingElement.addAttribute("days","R"); break;
              case Calendar.FRIDAY : meetingElement.addAttribute("days","F"); break;
              case Calendar.SATURDAY : meetingElement.addAttribute("days","S"); break;
              case Calendar.SUNDAY : meetingElement.addAttribute("days","U"); break;
          }
          Location location = (meeting.getLocationPermanentId() == null ? null : iMeetingLocations.get(meeting.getLocationPermanentId()));
          if (location==null) {
          } else if (location instanceof Room) {
              meetingElement.addAttribute("building", ((Room)location).getBuildingAbbv());
              meetingElement.addAttribute("room", ((Room)location).getRoomNumber());
          } else {
              meetingElement.addAttribute("location", location.getLabel());
          }
      }
  }
 
Example 44
Project: unitimes   File: PointInTimeDataExport.java   Source Code and License 5 votes vote down vote up
private void exportCourse(Element courseElement, CourseOffering course, Session session) {
	if (!subjectElements.containsKey(course.getSubjectArea().getUniqueId())){
		exportSubjectArea(course.getSubjectArea());
	}
    courseElement.addAttribute(sUniqueIdAttribute, course.getUniqueId().toString());
    courseElement.addAttribute(sExternalIdAttribute, (course.getExternalUniqueId()!=null?course.getExternalUniqueId():course.getUniqueId().toString()));
    courseElement.addAttribute(sSubjectAreaAbbreviationAttribute, course.getSubjectArea().getSubjectAreaAbbreviation());
    courseElement.addAttribute(sCourseNbrAttribute, course.getCourseNbr());
    courseElement.addAttribute(sControllingAttribute, course.isIsControl()?"true":"false");
    courseElement.addAttribute(sPermanentIdAttribute, (course.getPermId() == null ? course.getUniqueId().toString() : course.getPermId()));
    if (course.getProjectedDemand() != null){
        courseElement.addAttribute(sProjectedDemandAttribute,
        		course.getProjectedDemand().toString());
    }
    if (course.getTitle() != null) {
    	courseElement.addAttribute(sTitleAttribute, course.getTitle());
    }
    if (course.getNbrExpectedStudents() != null) {
    	courseElement.addAttribute(sNumberExpectedStudentsAttribute, course.getNbrExpectedStudents().toString());
    }
    if (course.getDemand() != null){
    	courseElement.addAttribute(sLastlikeDemandAttribute, course.getDemand().toString());
    }
    if (course.getCourseType() != null) {
    	if (!courseTypeElements.containsKey(course.getCourseType().getUniqueId())){
    		exportCourseType(course.getCourseType());
    	}
    	courseElement.addAttribute(sCourseTypeIdAttribute, (course.getCourseType().getUniqueId().toString()) );
    }
    if (course.getUniqueIdRolledForwardFrom() != null){
    	courseElement.addAttribute(sUniqueIdRolledForwardFromAttribute, course.getUniqueIdRolledForwardFrom().toString());
    }
}
 
Example 45
Project: banana   File: MessageUtil.java   Source Code and License 5 votes vote down vote up
public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
    Map<String, String> rtnMap = new HashMap<>();

    SAXReader reader = new SAXReader();

    try (ServletInputStream in = request.getInputStream()) {
        Document root = reader.read(in);
        Element rootElement = root.getRootElement();

        List<Element> elements = rootElement.elements();
        elements.forEach(e -> rtnMap.put(e.getName(), e.getText()));
    }

    return rtnMap;
}
 
Example 46
Project: joai-project   File: SchemEditForm.java   Source Code and License 5 votes vote down vote up
/**
 *  Gets the choiceOptions for the element specified by "encodedPath", adding
 *  indexing if the element is a multiChoice.
 *
 * @param  encodedPath  a jsp-encoded xpath
 * @return              The choiceOptions value
 */
public LabelValueBean[] getChoiceOptions(String encodedPath) {
	// prtln ("choiceOptions - " + encodedPath);
	List choices = new ArrayList();
	String xpath = XPathUtils.decodeXPath(encodedPath);
	Choice compositor = null;
	if (schemaHelper.hasChoiceCompositor(xpath)) {
		compositor = (Choice) schemaHelper.getCompositor(xpath);
		Element instanceElement = (Element) docMap.selectSingleNode(xpath);
		if (compositor != null && instanceElement != null) {
			choices = compositor.getAcceptableMembers(instanceElement);
		}
	}

	LabelValueBean[] selectOptions = new LabelValueBean[choices.size() + 1];
	selectOptions[0] = new LabelValueBean("-- choice --", "");
	for (int i = 0; i < choices.size(); i++) {
		String label = (String) choices.get(i);
		String choicePath = encodedPath + "/" + label;

		// paths for multichoice parents and repeating choices require indexing
		if (schemaHelper.isMultiChoiceElement(xpath) ||
			schemaHelper.isRepeatingElement(choicePath)) {
			int choiceIndex = this.getMemberCountOf(choicePath) + 1;
			choicePath = choicePath + "_" + choiceIndex + "_";
		}
		selectOptions[i + 1] = new LabelValueBean(label, choicePath);
	}
	return selectOptions;
}
 
Example 47
Project: lams   File: JPAOverriddenAnnotationReader.java   Source Code and License 5 votes vote down vote up
private Inheritance getInheritance(Element tree, XMLContext.Default defaults) {
	Element element = tree != null ? tree.element( "inheritance" ) : null;
	if ( element != null ) {
		AnnotationDescriptor ad = new AnnotationDescriptor( Inheritance.class );
		Attribute attr = element.attribute( "strategy" );
		InheritanceType strategy = InheritanceType.SINGLE_TABLE;
		if ( attr != null ) {
			String value = attr.getValue();
			if ( "SINGLE_TABLE".equals( value ) ) {
				strategy = InheritanceType.SINGLE_TABLE;
			}
			else if ( "JOINED".equals( value ) ) {
				strategy = InheritanceType.JOINED;
			}
			else if ( "TABLE_PER_CLASS".equals( value ) ) {
				strategy = InheritanceType.TABLE_PER_CLASS;
			}
			else {
				throw new AnnotationException(
						"Unknown InheritanceType in XML: " + value + " (" + SCHEMA_VALIDATION + ")"
				);
			}
		}
		ad.setValue( "strategy", strategy );
		return AnnotationFactory.create( ad );
	}
	else if ( defaults.canUseJavaAnnotations() ) {
		return getPhysicalAnnotation( Inheritance.class );
	}
	else {
		return null;
	}
}
 
Example 48
Project: joai-project   File: DleseCollectionFileIndexingWriter.java   Source Code and License 5 votes vote down vote up
/**
 *  Gets the gradeRanges for this collection.
 *
 * @return                The gradeRanges value
 * @exception  Exception  NOT YET DOCUMENTED
 */
protected String[] getGradeRanges() throws Exception {
	List nodes = getDom4jDoc().selectNodes("/*[local-name()='collectionRecord']/*[local-name()='general']/*[local-name()='gradeRanges']/*[local-name()='gradeRange']");
	ArrayList vals = new ArrayList();
	String tmp;
	for (int i = 0; i < nodes.size(); i++) {
		tmp = ((Element) nodes.get(i)).getText();
		if (!vals.contains(tmp))
			vals.add(tmp);
	}
	return (String[]) vals.toArray(new String[]{});
}
 
Example 49
Project: bdf2   File: DataSetDropDownConverter.java   Source Code and License 5 votes vote down vote up
public Element convert(ComponentInfo component, RuleSet ruleSet,
		Element rootElement) throws Exception {
	String name=DataSetDropDown.class.getSimpleName();
	XmlNode node=DataSetDropDown.class.getAnnotation(XmlNode.class);
	if(node!=null && StringHelper.isNotEmpty(node.nodeName())){
		name=node.nodeName();
	}
	Rule rule=ruleSet.getRule(name);
	BaseElement element = fillElement(component,ruleSet,rule,rootElement);
	this.fillDataSetAndDataPathProperty(element, component,true);
	return element;
}
 
Example 50
Project: aaden-pay   File: MemoryLabelParser.java   Source Code and License 5 votes vote down vote up
private void initAreaMap() {
	try {
		String path = FileUtils.getClassOrSystemPath(areaPath);
		if (path == null) {
			throw new IllegalArgumentException(areaPath + " does not exist");
		}

		AREA_MAP = new HashMap<String, Area>();

		// 加载行政区
		Document document = XmlUtils.getDocument(path);
		if (document == null) {
			logger.warn("解析行政区.xml失败");
			return;
		}

		Element element = null;
		Area area = null;
		for (@SuppressWarnings("unchecked")
		Iterator<Element> it = document.getRootElement().elementIterator(areaNode[0]); it.hasNext();) {
			element = it.next();
			area = new Area();
			area.setAreaCode(element.attributeValue(areaNode[1]));
			area.setAreaName(element.attributeValue(areaNode[2]));
			area.setParentCode(element.attributeValue(areaNode[3]));
			AREA_MAP.put(area.getAreaCode(), area);
		}
	} catch (Exception e) {
		logger.error(" 初始化行政区失败", e);
	}
}
 
Example 51
Project: joai-project   File: OsmRecordExporter.java   Source Code and License 5 votes vote down vote up
public static String getExportXml (String xml, String collection, String repositoryUrl) throws Exception {
	OsmRecordExporter rec = new OsmRecordExporter (xml);
	
	String id = rec.getId();
	// String urlOfRecord = parentUrl + "/" + id;
	String urlOfRecord = repositoryUrl + "/" + collection + "/" + id;
	rec.setUrl (urlOfRecord);
	List allAssetNodes = rec.getAssetNodes();
	// prtln ("parentUrl: " + parentUrl);
	/*
	the url for assetNodes has the form:
	http://nldr.library.ucar.edu/collections/soars/2009_Goode_Sharome.pdf
	*/
	
	for (int i=0;i<allAssetNodes.size();i++) {
		Element assetElement = (Element)allAssetNodes.get(i);
		try {
			String physicalUrl = assetElement.attributeValue("url");
			
			// if a record is embargoed, we simply do not provide the url
			String citableUrl = (rec.isEmbargoed() ? "" :
								urlOfRecord + "/" + new File (physicalUrl).getName());
								
			assetElement.addAttribute("url", citableUrl);
		} catch (Throwable t) {
			prtln ("could not process assetElement: " + t.getMessage());
			prtln ("assetElement: " + Dom4jUtils.prettyPrint(assetElement));
		}
	}
			
	// prtln (Dom4jUtils.prettyPrint(rec.getXmlNode())); // tihs is fine!
	return Dom4jUtils.prettyPrint(rec.getXmlNode());
}
 
Example 52
Project: unitimes   File: RoomSharingExport.java   Source Code and License 5 votes vote down vote up
protected void fillLocationData(Location location, Element element) {
	if (location instanceof Room) {
		Room room = (Room) location;
		element.addAttribute("building", room.getBuilding().getAbbreviation());
		element.addAttribute("roomNbr", room.getRoomNumber());
	} else {
		element.addAttribute("name", location.getLabel());
	}
	if (location.getExternalUniqueId() != null && !location.getExternalUniqueId().isEmpty())
		element.addAttribute("id", location.getExternalUniqueId());
}
 
Example 53
Project: joai-project   File: SimpleType.java   Source Code and License 5 votes vote down vote up
/**
 *  Gets the unionMemberTypesAsString attribute of the SimpleType object
 *
 *@return    The unionMemberTypesAsString value
 */
public String getUnionMemberTypesAsString() {
	String members = "";
	List list = getElement().selectNodes(NamespaceRegistry.makeQualifiedName(xsdPrefix, "union"));
	Iterator i = list.iterator();
	if (i.hasNext()) {
		Element e = (Element) i.next();
		members = e.attributeValue("memberTypes");
	}
	return members;
}
 
Example 54
Project: urule   File: ConstantLibraryParser.java   Source Code and License 5 votes vote down vote up
public ConstantLibrary parse(Element element) {
	List<ConstantCategory> categories=new ArrayList<ConstantCategory>();
	for(Object obj:element.elements()){
		if(obj==null || !(obj instanceof Element)){
			continue;
		}
		Element ele=(Element)obj;
		if(ele.getName().equals("category")){
			categories.add(parseConstantCategory(ele));
		}
	}
	ConstantLibrary library=new ConstantLibrary();
	library.setCategories(categories);
	return library;
}
 
Example 55
Project: bulbasaur   File: Delay.java   Source Code and License 5 votes vote down vote up
@Override
public StateLike parse(Element elem) {
    super.parse(elem);
    List<Element> intervalElement = elem.selectNodes(TIME_TAG);
    // 拿 孩子节点
    for (Element intervalNode : intervalElement) {
        this.time = intervalNode.getStringValue();
    }
    return this;
}
 
Example 56
Project: Spring-Boot-Server   File: XmlUtils.java   Source Code and License 5 votes vote down vote up
public static List<PageData> getAssetDatas(String xmlStr) throws Exception {
		Document document = DocumentHelper.parseText(xmlStr);
		List<PageData> res = null;
		if(null != document){
			res = new ArrayList<PageData>();
			//获取文档的根节点
			Element root = document.getRootElement();
			//取得某个节点的子节点
			Element element_sentence_list = root.element("ContentList");
			//取得某节点下所有名为“Program”的子节点,并进行遍历
			List nodes = element_sentence_list.elements("Program");
			for (Iterator it = nodes.iterator(); it.hasNext();) {
				PageData pd_tmp = new PageData();
				Element elm = (Element) it.next();
				pd_tmp.put("name", elm.attribute("name").getText());
				pd_tmp.put("resourceCode", elm.attribute("contentID").getText());
				//取得某节点下所有名为“Series”的子节点,并进行遍历
				List nodes1 = elm.elements("PictureList");
				for (Iterator it1 = nodes1.iterator(); it1.hasNext();) {
					Element elm1 = (Element) it1.next();
					List nodes2 = elm1.elements("Picture"); 
					for (Iterator it2 = nodes2.iterator(); it2.hasNext();) {
						Element elm2 = (Element) it2.next();
						pd_tmp.put("picFileURL", elm2.attribute("fileURL").getText());
//						System.out.println(elm.attribute("contentId").getText() + "-" + elm.attribute("name").getText() + "-" + elm2.attribute("fileURL").getText());
						res.add(pd_tmp);
					}
					break;
				}
			}
		}
		return res;
	}
 
Example 57
Project: joai-project   File: ViewerRenderer.java   Source Code and License 5 votes vote down vote up
/**
 *  Formats the label and value for the current node.<p>
 *
 *  NOTE: this probably shouldn't be here, since it is misnamed (it does not
 *  have anything to do with "input"). To fix this problem we have to change
 *  super classes to differentiate between renders that create edit inputs and
 *  those that simply display values.
 *
 * @param  xpath       NOT YET DOCUMENTED
 * @param  label       NOT YET DOCUMENTED
 * @param  inputField  NOT YET DOCUMENTED
 * @return             The labelledInputField_1 value
 */
public Element getRenderedField_1(String xpath, Label label, Element inputField) {
	prtln("getRenderedField()");
	// prtln ("inputField: " + Dom4jUtils.prettyPrint(inputField));


	Element table = df.createElement("table")
		.addAttribute("class", "input-field-table");

	Element row = table.addElement("tr")
		.addAttribute("class", "form-row");

	// LABEL cell
	Element labelCell = row.addElement("td")
		.addAttribute("class", "label-cell");

	rhelper.attachToolHelp(labelCell, xpath);
	labelCell.add(label.getElement());

	// INPUT cell
	Element emptyTest = missingValueTest(xpath);
	Element debugging = emptyTest.addElement("span")
		.addAttribute("class", "element-error-msg");
	debugging.setText("missing value");

	Element notEmptyTest = hasValueTest(xpath);
	notEmptyTest.add(inputField);

	Element inputFieldCell = row.addElement("td")
		.addAttribute("class", "input-cell");
	inputFieldCell.add(emptyTest);
	inputFieldCell.add(notEmptyTest);

	return table;
}
 
Example 58
Project: GraphicsViewJambi   File: ImportLocalNetImplement.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void addODToODMatrix(List<Element> originList)
{
	final int originListSize = originList.size();
	System.out.println("Origin's count: " + originListSize); 
	for(int i = 0; i<originListSize; i++)
	{
		Vertex orgV = null;		//连接的起点
				
		Element element = originList.get(i);
		String orgid = element.attribute("id").getValue();
		String orgx = element.attribute("x").getValue();
		String orgy = element.attribute("y").getValue();
		
		orgV = new Vertex(orgid,"Internal",Double.parseDouble(orgx),Double.parseDouble(orgy));
		
		List<Element> destinationList = element.selectNodes(LocalXmlAttributeMatch.DESTINATION);
		int destinationCount = destinationList.size();	
		for(int j = 0; j<destinationCount; j++)
		{
			Vertex desV = null;  	//连接的终点
			String demand = null;
			
			Element destinaton = destinationList.get(j);
			String desid = destinaton.attribute("id").getValue();
			String desx = destinaton.attribute("x").getValue();
			String desy = destinaton.attribute("y").getValue();
			demand = destinaton.attribute("demand").getValue();
			
			desV = new Vertex(desid,"Internal",Double.parseDouble(desx),Double.parseDouble(desy));
			OD od = new OD(orgV,desV,Double.parseDouble(demand));
			odMatrix.addOD(od);
		}
	}
}
 
Example 59
Project: alfresco-repository   File: NodePermission.java   Source Code and License 5 votes vote down vote up
public void initialise(Element element, NamespacePrefixResolver nspr, PermissionModel permissionModel)
{
   Attribute nodeRefAttribute = element.attribute(NODE_REF);
   if(nodeRefAttribute != null)
   {
       nodeRef = new NodeRef(nodeRefAttribute.getStringValue());
   }
   
   Attribute inheritFromParentAttribute = element.attribute(INHERIT_FROM_PARENT);
   if(inheritFromParentAttribute != null)
   {
       inheritPermissionsFromParent = Boolean.parseBoolean(inheritFromParentAttribute.getStringValue());
   }
   else
   {
       inheritPermissionsFromParent = true;
   }
   
   // Node Permissions Entry

   for (Iterator npit = element.elementIterator(NODE_PERMISSION); npit.hasNext(); /**/)
   {
       Element permissionEntryElement = (Element) npit.next();
       ModelPermissionEntry permissionEntry = new ModelPermissionEntry(nodeRef);
       permissionEntry.initialise(permissionEntryElement, nspr, permissionModel);
       permissionEntries.add(permissionEntry);
   }
    
}
 
Example 60
Project: urule   File: CommonFunctionActionParser.java   Source Code and License 5 votes vote down vote up
@Override
public Action parse(Element element) {
	ExecuteCommonFunctionAction action=new ExecuteCommonFunctionAction();
	action.setLabel(element.attributeValue("function-label"));
	action.setName(element.attributeValue("function-name"));
	for(Object obj:element.elements()){
		if(!(obj instanceof Element)){
			continue;
		}
		Element ele=(Element)obj;
		if(!ele.getName().equals("function-parameter")){
			continue;
		}
		CommonFunctionParameter p=new CommonFunctionParameter();
		p.setName(ele.attributeValue("name"));
		p.setProperty(ele.attributeValue("property-name"));
		p.setPropertyLabel(ele.attributeValue("property-label"));
		for(Object object:ele.elements()){
			if(!(object instanceof Element)){
				continue;
			}
			Element e=(Element)object;
			if(!e.getName().equals("value")){
				continue;
			}
			p.setObjectParameter(valueParser.parse(e));
		}
		action.setParameter(p);
	}
	return action;
}