Java Code Examples for org.dom4j.Element.selectNodes()

The following are Jave code examples for showing how to use selectNodes() of the org.dom4j.Element class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: atlas   File: AtlasProxy.java   View Source Code Vote up 8 votes
public static void addAtlasProxyClazz(Document document, Set<String> nonProxyChannels,  Result result) {

        Element root = document.getRootElement();// Get the root node

        List<? extends Node> serviceNodes = root.selectNodes("//@android:process");

        String packageName = root.attribute("package").getStringValue();

        Set<String> processNames = new HashSet<>();
        processNames.add(packageName);

        for (Node node : serviceNodes) {
            if (null != node && StringUtils.isNotEmpty(node.getStringValue())) {
                String value = node.getStringValue();
                processNames.add(value);
            }
        }

        processNames.removeAll(nonProxyChannels);

        List<String> elementNames = Lists.newArrayList("activity", "service", "provider");

        Element applicationElement = root.element("application");

        for (String processName : processNames) {

            boolean isMainPkg = packageName.equals(processName);
            //boolean isMainPkg = true;
            String processClazzName = processName.replace(":", "").replace(".", "_");

            for (String elementName : elementNames) {

                String fullClazzName = "ATLASPROXY_" +  (isMainPkg ? "" : (packageName.replace(".", "_") + "_" )) +  processClazzName + "_" + StringUtils.capitalize(elementName);

                if ("activity".equals(elementName)) {
                    result.proxyActivities.add(fullClazzName);
                } else if ("service".equals(elementName)) {
                    result.proxyServices.add(fullClazzName);
                } else {
                    result.proxyProviders.add(fullClazzName);
                }

                Element newElement = applicationElement.addElement(elementName);
                newElement.addAttribute("android:name", ATLAS_PROXY_PACKAGE + "." + fullClazzName);

                if (!packageName.equals(processName)) {
                    newElement.addAttribute("android:process", processName);
                }

                boolean isProvider = "provider".equals(elementName);
                if (isProvider) {
                    newElement.addAttribute("android:authorities",
                                            ATLAS_PROXY_PACKAGE + "." + fullClazzName);
                }

            }

        }

    }
 
Example 2
Project: atlas   File: XmlHelper.java   View Source Code Vote up 6 votes
public static void removeStringValue(File file, String key) throws IOException, DocumentException {

        if (!file.exists()) {
            return;
        }

        Document document = XmlHelper.readXml(file);// Read the XML file
        Element root = document.getRootElement();// Get the root node
        List<? extends Node> nodes = root.selectNodes("//string");
        for (Node node : nodes) {
            Element element = (Element)node;
            String name = element.attributeValue("name");
            if (key.equals(name)) {
                element.getParent().remove(element);
                break;
            }
        }
        // sLogger.warn("[resxmlediter] add " + key + " to " + file.getAbsolutePath());
        XmlHelper.saveDocument(document, file);
    }
 
Example 3
Project: GraphicsViewJambi   File: ExportNetworkToXML.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
public void setOriginAttribute(final String id, final String x, final String y)
{	
	String s = "junction[@type='Other_Junction' and contains(@intNode,'"+ id +"')]";
	//System.out.println("add O: " + id);
	Element r = document.getRootElement();
	List<Element> list = r.selectNodes(s);
	String junctemp = "";
	if(!list.isEmpty())
	{
		junctemp = list.get(0).attribute("id").getValue();
	}
	
	origin.addAttribute("id", id);
	origin.addAttribute("x", x);
	origin.addAttribute("y", y);
	origin.addAttribute("junction", junctemp);
}
 
Example 4
Project: bulbasaur   File: RunnableState.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public StateLike parse(Element elem) {
    require(elem.attributeValue("name") != null,
        "attribute 'name' in node is required");
    stateName = elem.attributeValue("name");
    stateAlias = elem.attributeValue("alias");
    // 得到所有该节点下的 paths 下的 path
    List<Element> childPaths = elem.selectNodes(PATH_TAG);
    for (Element node : childPaths) {
        require(node.attributeValue("to") != null, "attribute to in path node is required");

        String pathTo = node.attributeValue("to");
        String expr = null;
        if (node.attributeValue("expr") != null) {
            expr = node.attributeValue("expr");
        }
        // 新实例一个path,并加入到paths中
        Path pt = new Path(pathTo, expr);
        // 添加到path 列表中
        paths.add(pt);
    }
    return this;
}
 
Example 5
Project: bulbasaur   File: Event.java   View Source Code Vote up 6 votes
@Override
public StateLike parse(Element elem) {
    super.parse(elem);
    List<Element> pre_invokesPaths = elem.selectNodes(PRE_INVOKES_TAG);
    for (Element node : pre_invokesPaths) {// 拿 孩子节点
        for (Iterator i = node.elementIterator(); i.hasNext(); ) {
            Element child = (Element)i.next();
            try {
                preInvokes.add(InvokableFactory.newInstance(child.getName(), child));
            } catch (RuntimeException re) {
                logger.error(String.format("实例Invokable类型时候出错,类型为:%s , 异常为: %s", child.getName(), re.toString()));
                throw re;
            } catch (Throwable e) {
                logger.error(String.format("实例Invokable类型时候出错,类型为: %s , 异常为:", child.getName(), e.toString()));
                throw new UndeclaredThrowableException(e,
                    "error happened when newInstance Invokable class:" + child.getName());
            }
        }
    }
    return this;
}
 
Example 6
Project: bulbasaur   File: BizInfo.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public StateLike parse(Element elem) {
    List<Element> infoElemList = elem.selectNodes(INFO_TAG);
    for (Element infoElem : infoElemList) {
        BizInfoElement bizInfoElement = new BizInfoElement();
        for (Iterator<Attribute> it = infoElem.attributeIterator(); it.hasNext(); ) {
            Attribute attribute = it.next();
            bizInfoElement.attribute.put(attribute.getName(), attribute.getValue());
        }
        String key = bizInfoElement.attribute.get(KEY_TAG);
        require(StringUtils.hasText(key), "attribute '" + KEY_TAG + "' in node bizInfo/info is required");
        if (bizInfoList.get(key) == null) {
            bizInfoList.put(key, new ArrayList<BizInfoElement>());
        }
        bizInfoList.get(key).add(bizInfoElement);
    }
    return this;
}
 
Example 7
Project: GraphicsViewJambi   File: ImportLocalNetImplement.java   View Source Code Vote up 5 votes
@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 8
Project: atlas   File: ManifestFileUtils.java   View Source Code Vote up 5 votes
private static void fillFullClazzName(Element root, String packageName, String type) {
    List<? extends Node> applicatNodes = root.selectNodes("//" + type);
    for (Node node : applicatNodes) {
        Element element = (Element)node;
        Attribute attribute = element.attribute("name");
        if (attribute != null) {
            if (attribute.getValue().startsWith(".")) {
                attribute.setValue(packageName + attribute.getValue());
            }
        }
    }
}
 
Example 9
Project: atlas   File: ManifestFileUtils.java   View Source Code Vote up 5 votes
private static void removeProvider(Document document) throws IOException, DocumentException {

        Element root = document.getRootElement();// Get the root node
        List<? extends Node> nodes = root.selectNodes("//provider");
        for (Node node : nodes) {
            Element element = (Element)node;
            String name = element.attributeValue("name");
            logger.info("[Remove Provider]" + name);
            element.getParent().remove(element);
        }
    }
 
Example 10
Project: GraphicsViewJambi   File: ImportNetworkFromLocal.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public Network networkStorage()
{
	final Element root = document.getRootElement();
	final List<Element> junctionList = root.selectNodes(LocalXmlAttributeMatch.JUNCTION); 
	final List<Element> extLinkList = root.selectNodes(LocalXmlAttributeMatch.EXTLINK);
	
	addJunctionToNetwork(junctionList);
	addExtLinkToNetwork(extLinkList);
	
	return network;
}
 
Example 11
Project: bulbasaur   File: State.java   View Source Code Vote up 5 votes
@Override
public StateLike parse(Element elem) {
    super.parse(elem);
    if (elem.attributeValue(REPEATLIST_TAG) != null) {
        repeatList = elem.attributeValue(REPEATLIST_TAG);
    }
    if (elem.attributeValue(IGNOREWEEKEND_TAG) != null) {
        ignoreWeekend = Boolean.valueOf(elem.attributeValue(IGNOREWEEKEND_TAG));
    }

    List<Element> invokesPaths = elem.selectNodes(INVOKES_TAG);
    // 拿孩子节点
    for (Element node : invokesPaths) {
        for (Iterator i = node.elementIterator(); i.hasNext(); ) {
            Element child = (Element)i.next();
            try {
                invokes.add(InvokableFactory.newInstance(child.getName(), child));
            } catch (RuntimeException re) {
                logger.error(String.format("实例Invokable类型时候出错,类型为: %s , 异常为: %s", child.getName(), re.toString()));
                throw re;
            } catch (Throwable e) {
                logger.error(String.format("实例Invokable类型时候出错,类型为: %s , 异常为: %s", child.getName(), e.toString()));
                throw new UndeclaredThrowableException(e,
                    "error happened when newInstance Invokable class:" + child.getName());
            }

        }
    }
    return this;
}
 
Example 12
Project: GraphicsViewJambi   File: ImportSumoODMatrix.java   View Source Code Vote up 5 votes
/**
 * 获取OD List
 */
@SuppressWarnings("unchecked")
public void createODNodeList()
{
	final Element root = document.getRootElement();
	final List<Element> tazList = root.selectNodes("taz");
	
	final int tazListSize = tazList.size();
	for(int i = 0; i<tazListSize; i++)
	{
		//Get a Taz from the Taz List
		Element element = tazList.get(i);
		
		List<Element> tazSourceList = element.selectNodes("tazSource");
		if(!tazSourceList.isEmpty())
		{
			String origin = tazSourceList.get(0).attribute("id").getValue();
			originList.add(origin);
		}
		
		List<Element> tazSinkList = element.selectNodes("tazSink");
		if(!tazSinkList.isEmpty())
		{
			String destination = tazSinkList.get(0).attribute("id").getValue();
			destinationList.add(destination);
		}
	}
}
 
Example 13
Project: GraphicsViewJambi   File: ImportLocalNetImplement.java   View Source Code Vote up 5 votes
/**
 * 存储路网到Network
 * @return
 */
@SuppressWarnings("unchecked")
public Network networkStorage()
{
	final Element root = document.getRootElement();
	final List<Element> junctionList = root.selectNodes(LocalXmlAttributeMatch.JUNCTION); 
	final List<Element> extLinkList = root.selectNodes(LocalXmlAttributeMatch.EXTLINK);
	final List<Element> originList = root.selectNodes(LocalXmlAttributeMatch.ORIGIN);
	addJunctionToNetwork(junctionList);
	addExtLinkToNetwork(extLinkList);
	addODToODMatrix(originList);
	return network;
}
 
Example 14
Project: joai-project   File: OAISetsXMLConfigManager.java   View Source Code Vote up 4 votes
/**
 *  Reads the ListSets config XML to extract the set definition for a given set into a SetDefinitionsForm
 *  bean.
 *
 * @param  listSetsXml    The ListSets config XML to read
 * @param  setSpec        The setSpec to read
 * @return                The setDefinitionsForm, or null if none configred for that setSpec
 * @exception  Exception  If error parsing the XML
 */
public static SetDefinitionsForm getSetDefinitionsForm(String listSetsXml, String setSpec)
	 throws Exception {

	Document document = Dom4jUtils.getXmlDocument(listSetsXml);
	Element setElement = (Element) document.selectSingleNode("/ListSets/set[setSpec='" + setSpec + "']");
	if (setElement == null)
		return null;

	SetDefinitionsForm setDefinitionsForm = new SetDefinitionsForm();
	setDefinitionsForm.setSetName(setElement.valueOf("setName"));
	setDefinitionsForm.setSetSpec(setElement.valueOf("setSpec"));
	setDefinitionsForm.setSetDescription(setElement.valueOf("setDescription/description"));
	setDefinitionsForm.setSetURL(setElement.valueOf("setDescription/identifier"));
	setDefinitionsForm.setIncludedFormat(setElement.valueOf("virtualSearchField/virtualSearchTermDefinition/Query//booleanQuery/textQuery[@field='xmlFormat']"));
	setDefinitionsForm.setIncludedQuery(setElement.valueOf("virtualSearchField/virtualSearchTermDefinition/Query/booleanQuery/luceneQuery[not(@excludeOrRequire='exclude')]"));
	setDefinitionsForm.setExcludedQuery(setElement.valueOf("virtualSearchField/virtualSearchTermDefinition/Query/booleanQuery/luceneQuery[@excludeOrRequire='exclude']"));

	// Handle include clauses

	// Get included dirs
	List includedDirs = setElement.selectNodes("virtualSearchField/virtualSearchTermDefinition/Query//booleanQuery/textQuery[@field='docdir' and not(@excludeOrRequire='exclude')]");
	ArrayList dirsList = new ArrayList(includedDirs.size());
	for (int i = 0; i < includedDirs.size(); i++)
		dirsList.add( ((Node) includedDirs.get(i)).getText() );
	setDefinitionsForm.setIncludedDirs((String[])dirsList.toArray(new String[]{}));

	// Get included terms/phrases
	List terms = setElement.selectNodes("virtualSearchField/virtualSearchTermDefinition/Query//booleanQuery/textQuery[@field='default' and not(@excludeOrRequire='exclude')]");
	String text = "";
	prtln("terms size: " + terms.size());
	for (int i = 0; i < terms.size(); i++) {
		text += ((Node) terms.get(i)).getText();
		if (i < terms.size() - 1)
			text += ", ";
	}
	setDefinitionsForm.setIncludedTerms(text);

	// Handle exclude clauses

	// Get excluded dirs
	List exdludedDirs = setElement.selectNodes("virtualSearchField/virtualSearchTermDefinition/Query/booleanQuery/textQuery[@field='docdir' and @excludeOrRequire='exclude']");
	dirsList = new ArrayList(exdludedDirs.size());
	for (int i = 0; i < exdludedDirs.size(); i++)
		dirsList.add( ((Node) exdludedDirs.get(i)).getText() );
	setDefinitionsForm.setExcludedDirs((String[])dirsList.toArray(new String[]{}));
	
	/* dirStrings = setDefinitionsForm.getExcludedDirs();
	for (int i = 0; i < exdludedDirs.size(); i++)
		dirStrings[i] = ((Node) exdludedDirs.get(i)).getText();
	setDefinitionsForm.setExcludedDirs(dirStrings); */

	// Get excluded terms/phrases
	terms = setElement.selectNodes("virtualSearchField/virtualSearchTermDefinition/Query/booleanQuery/textQuery[@field='default' and @excludeOrRequire='exclude']");
	text = "";
	for (int i = 0; i < terms.size(); i++) {
		text += ((Node) terms.get(i)).getText();
		if (i < terms.size() - 1)
			text += ", ";
	}
	setDefinitionsForm.setExcludedTerms(text);

	//prtln("setDefinitionsForm.getSetName(): " + setDefinitionsForm.getSetName());
	return setDefinitionsForm;
}
 
Example 15
Project: joai-project   File: RemoteSearcher.java   View Source Code Vote up 4 votes
/**
 *  analogus to SimpleLuceneIndex.searchDoc, performs a search and returns an
 *  array of {@link RemoteResultDoc} objects that represent the results of the
 *  search. <p>
 *
 *  Note: the urlCheck WebService returns information about duplicate records
 *  (that don't match the query, but which refer to the same resource) returned
 *  as an <b>alsoCatalogedBy</b> element of <b>MatchingRecord</b> . These
 *  duplicates are treated as search results by searchDocs - they are expanded
 *  into RemoteResultDoc objects and added to the results returned.
 *
 *@param  s  Description of the Parameter
 *@return    Description of the Return Value
 */
public RemoteResultDoc[] searchDocs(String s) {
	RemoteResultDoc[] emptyResults = new RemoteResultDoc[]{};
	if (s == null) {
		prtln("RemoteResultDoc: got null for the search parameter");
		return emptyResults;
	}
	Document webServiceResultDoc = null;
	try {
		prtln("about to call webserviceClient.urlCheck with " + s);
		webServiceResultDoc = wsc.urlCheck(s);
	} catch (WebServiceClientException e) {
		prtln(e.getMessage());
		return emptyResults;
	}
	if (webServiceResultDoc == null) {
		prtln("urlCheck returned null");
		return emptyResults;
	}
	// parse results document
	List matchingRecords = webServiceResultDoc.selectNodes("//results/matchingRecord");
	if (matchingRecords.size() == 0) {
		prtln("urlCheck returned no matches");
		return emptyResults;
	}
	else {
		ArrayList matches = new ArrayList();
		for (Iterator i = matchingRecords.iterator(); i.hasNext(); ) {
			Element matchingRecord = (Element) i.next();
			// prtln ("about to parse matchingRecord:\n" + Dom4jUtils.prettyPrint(matchingRecord));

			RemoteResultDoc m = new RemoteResultDoc(matchingRecord, this);
			matches.add(m);

			// now deal with the alsoCatalogedBys
			List alsoCatalogedBys = matchingRecord.selectNodes("//additionalMetadata[@realm='adn']/alsoCatalogedBy");
			if (alsoCatalogedBys == null) {
				// prtln ("no alsoCatalogedBys found");
			}
			else {
				// prtln (alsoCatalogedBys.size() + " alsoCatalogedBys found");
				for (Iterator n = alsoCatalogedBys.iterator(); n.hasNext(); ) {
					Element ae = (Element) n.next();
					String collection = ae.attributeValue("collectionLabel");
					String id = ae.getText();
					RemoteResultDoc am = new RemoteResultDoc(id, m.getUrl(), collection, this);
					matches.add(am);
				}
			}
		}
		prtln("searchDocs found " + matches.size() + " items");
		return (RemoteResultDoc[]) matches.toArray(emptyResults);
	}
}
 
Example 16
Project: joai-project   File: VirtualSearchFieldMapper.java   View Source Code Vote up 4 votes
private void addVirtualSearchField(Element virtualSearchField) throws Exception {

		String field = virtualSearchField.valueOf("@field");

		if (field == null || field.trim().length() == 0)

			throw new Exception("Error parsing document: element <virtualSearchField> must have a single, non-empty 'field' attribute. Error found at " + virtualSearchField.getPath());



		List virtualSearchTermDefinitions = virtualSearchField.selectNodes("virtualSearchTermDefinition");

		for (int i = 0; i < virtualSearchTermDefinitions.size(); i++)

			addVirtualSearchTermDefinition((Element) virtualSearchTermDefinitions.get(i), field);

	}
 
Example 17
Project: atlas   File: ManifestHelper.java   View Source Code Vote up 4 votes
public static void collectBundleInfo(AppVariantContext appVariantContext, BundleInfo bundleInfo, File manifest,
                                     List<AndroidLibrary> androidLibraries)
    throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(getModifyManifestFile(manifest, appVariantContext));// Read the XML file
    Element root = document.getRootElement();// Get the root node

    List<? extends Node> metadataNodes = root.selectNodes("//meta-data");
    for (Node node : metadataNodes) {
        Element element = (Element)node;
        Attribute attribute = element.attribute("name");
        if (attribute.getValue().equals("label")) {
            Attribute labelAttribute = element.attribute("value");
            bundleInfo.setName(labelAttribute.getValue());
        } else if (attribute.getValue().equals("description")) {
            Attribute descAttribute = element.attribute("value");
            bundleInfo.setDesc(descAttribute.getValue());
        } else if(attribute.getValue().startsWith("atlas.fragment.intent.action.")){
            bundleInfo.getRemoteFragments().put(attribute.getValue(),
                    element.attribute("value").getValue());
        }else if(attribute.getValue().startsWith("atlas.view.intent.action")){
            bundleInfo.getRemoteViews().put(attribute.getValue(),
                    element.attribute("value").getValue());
        }else if(attribute.getValue().startsWith("atlas.transaction.intent.action")){
            bundleInfo.getRemoteTransactors().put(attribute.getValue(),
                    element.attribute("value").getValue());
        }
    }

    addComponents(bundleInfo, root);

    if (null != androidLibraries) {
        for (AndroidLibrary depLib : androidLibraries) {
            SAXReader reader2 = new SAXReader();
            Document document2 = reader2.read(
                getModifyManifestFile(depLib.getManifest(), appVariantContext));// Read the XML file
            Element root2 = document2.getRootElement();// Get the root node
            addComponents(bundleInfo, root2);
        }
    }

}
 
Example 18
Project: GraphicsViewJambi   File: ImportLocalNetImplement.java   View Source Code Vote up 4 votes
/**
 * 添加外部连接到路网
 * @param extLinkList
 */
@SuppressWarnings("unchecked")
private void addExtLinkToNetwork(List<Element> extLinkList)
{
	final int extLinkListSize = extLinkList.size();
	System.out.println("ExtLink's count: " + extLinkListSize); 
	for(int i = 0; i<extLinkListSize; i++)
	{
		//Get a node from the node list
		Element element = extLinkList.get(i);
		
		List<Attribute> listExtLinkAttribute = element.attributes();
		String id = listExtLinkAttribute.get(0).getValue();
		//String fromJunction = listExtLinkAttribute.get(1).getValue();
		//String toJunction = listExtLinkAttribute.get(2).getValue();
		String numLanes = listExtLinkAttribute.get(3).getValue();
		String speed = listExtLinkAttribute.get(4).getValue();
		String length = listExtLinkAttribute.get(5).getValue();

		Vertex linkStartNodeVertex = null;	//连接的起点
		Vertex linkEndNodeVertex = null;  	//连接的终点
		
		List<Element> extConnectionList = element.selectNodes(LocalXmlAttributeMatch.EXTCONNECTION);
		//int numExtConnection = extConnectionList.size();	
		
		List<Attribute> listExtConnectionAttribute = extConnectionList.get(0).attributes();
		String fromNode = listExtConnectionAttribute.get(0).getValue();		//外部连接内部起点
		String from_x = listExtConnectionAttribute.get(1).getValue();  			//起点X坐标
		String from_y = listExtConnectionAttribute.get(2).getValue();  			//起点Y坐标
		String toNode = listExtConnectionAttribute.get(3).getValue();  		//外部连接内部终点
		String to_x = listExtConnectionAttribute.get(4).getValue();	   			//终点X坐标
		String to_y = listExtConnectionAttribute.get(5).getValue();    			//终点Y坐标
		String dir = listExtConnectionAttribute.get(6).getValue();	   				//转向信息

		linkStartNodeVertex = new Vertex(fromNode,"Internal",
				Double.parseDouble(from_x),
				Double.parseDouble(from_y));
		linkEndNodeVertex = new Vertex(toNode,"Internal",
				Double.parseDouble(to_x),
				Double.parseDouble(to_y));
		
		//添加外部连接到路网
		//-----------------------------------------------------------
		Link link = new Link(linkStartNodeVertex, linkEndNodeVertex);
		link.setDirection(dir);
		link.setName(id);
		link.setLaneCount(Integer.parseInt(numLanes));
		link.setLinkType("External");
		link.setSpeed(Double.parseDouble(speed));
		link.setLength(Double.parseDouble(length));
		
		network.addLink(link);
	}
}
 
Example 19
Project: GraphicsViewJambi   File: ImportSumoNetwork.java   View Source Code Vote up 4 votes
/**
 * Analysis Information in a Node
 * 
 * @param matrix
 * 		Information will be stored in the Matrix
 * @param nodeToAnalysis
 * 		Node To Analysis
 * @param nodeList
 * 		Node List
 * @param matchAttributeList
 */
@SuppressWarnings("unchecked")
public void saveEdgeAttributeValues(Matrix matrix, 
									  final String nodeToAnalysis, 
									  final List<Element> nodeList, 
									  final List<String> matchAttributeList)
{
	final int nodeListSize = nodeList.size();
	
	System.out.println(nodeToAnalysis +" \'s count: " + nodeListSize); 
	for(int i = 0; i<nodeListSize; i++)
	{
		//Get a node from the node list
		final Element element = nodeList.get(i);
		
		//match attribute information
		//System.out.println("! ----------------------------------------------- !");
		//System.out.println("! Start Node --  " + element.getName() + "  -- Start Node !");
		
		final List<Attribute> listAttribute = element.attributes();
		Map<String, String> mapCurrently = new HashMap<String, String>();
		for (final Attribute attr : listAttribute)
		{
			//Save all Attribute and it's Value in a Key-Value Map
			mapCurrently.put(attr.getName(),attr.getValue());
		}
		
		if(nodeToAnalysis.equals(SumoXmlAttributeMatch.EDGE))
		{
			//Sub Node
			String start_node = mapCurrently.get("from") + "@" + mapCurrently.get("id");
			String end_node = mapCurrently.get("to") + "@" + mapCurrently.get("id");
			double speed = 0, length = 0, start_x = 0, start_y = 0, end_x = 0, end_y = 0;

			final List<Element> subNodeList = element.selectNodes("lane");
			int numLanes = subNodeList.size();	
			for(int p = 0; p<numLanes; p++)
			{
				speed += Double.parseDouble(subNodeList.get(p).attribute("speed").getValue());
				length += Double.parseDouble(subNodeList.get(p).attribute("length").getValue());

				final String[] shape = subNodeList.get(p).attribute("shape").getValue().split(",| ");
				start_x += Double.parseDouble(shape[0]);
				start_y += Double.parseDouble(shape[1]);
				end_x += Double.parseDouble(shape[shape.length-2]);
				end_y += Double.parseDouble(shape[shape.length-1]);
			}
			speed /= numLanes;
			length /= numLanes;
			start_x /= numLanes;
			start_y /= numLanes;
			end_x /= numLanes;
			end_y /= numLanes;

			matrix.setAsObject(mapCurrently.get("id"), i,0);
			matrix.setAsObject(mapCurrently.get("from"), i,1);
			matrix.setAsObject(mapCurrently.get("to"), i,2);
			matrix.setAsObject(Integer.toString(numLanes), i,3);
			matrix.setAsObject(Double.toString(speed), i,4);
			matrix.setAsObject(Double.toString(length), i,5);
			matrix.setAsObject(start_node, i,6);
			matrix.setAsObject(Double.toString(start_x), i,7);
			matrix.setAsObject(Double.toString(start_y), i,8);
			matrix.setAsObject(end_node, i,9);
			matrix.setAsObject(Double.toString(end_x), i,10);
			matrix.setAsObject(Double.toString(end_y), i,11);
		}
		//System.out.println("! End Node --  " + element.getName() + "  -- End Node !");
		//System.out.println("! ----------------------------------------------- !\n");		
	}
}
 
Example 20
Project: joai-project   File: VirtualSearchFieldMapper.java   View Source Code Vote up 3 votes
private void addVirtualSearchTermDefinition(Element virtualSearchTermDefinition, String field) throws Exception {

		String term = virtualSearchTermDefinition.valueOf("@term");

		if (term == null || term.trim().length() == 0)

			throw new Exception("Error parsing document: element <virtualSearchTermDefinition> must have a single, non-empty 'term' attribute. Error found at " + virtualSearchTermDefinition.getPath());



		List virtualDefinitionElement = virtualSearchTermDefinition.selectNodes("Query/*");

		if (virtualDefinitionElement == null || virtualDefinitionElement.size() == 0)

			throw new Exception("Error parsing document: <virtualSearchTermDefinition> child element '<Query>' is empty or missing. Error found at " + virtualSearchTermDefinition.getPath());

		if (virtualDefinitionElement.size() > 1)

			throw new Exception("Error parsing document: element <virtualSearchTermDefinition> must contain a single child element within the '<Query>' element but contains more than one. Error found at " + virtualSearchTermDefinition.getPath());



		Query query = XMLQueryParser.getLuceneQuery((Element) virtualDefinitionElement.get(0), localQueryParser);



		setQuery(field, term, query);

	}