private String text(String name) throws NoSuchElementException { was_CDATA = false; Element t = current(); NodeList l = t.getChildNodes(); if (name != null && !name.equals(DOMUtil.getLocalName(t))) { throw new NoSuchElementException("Not at element " + name + ": " + t.getNodeName() + "."); } if (l.getLength() == 0) { return null; } StringBuffer s = new StringBuffer(); was_CDATA = true; for (int i = 0; i < l.getLength(); i++) { Node n = l.item(i); short nt = n.getNodeType(); if (nt != Node.TEXT_NODE && nt != Node.CDATA_SECTION_NODE) { throw new NoSuchElementException("Not at a Text/CDATA element: " + t.getNodeName() + "."); } if (nt == Node.TEXT_NODE) { was_CDATA = false; } s.append(n.getNodeValue()); } return s.toString(); }
public SpanQuery getSpanQuery(Element e) throws ParserException { SpanQueryBuilder builder = builders.get(e.getNodeName()); if (builder == null) { throw new ParserException("No SpanQueryObjectBuilder defined for node " + e.getNodeName()); } return builder.getSpanQuery(e); }
private String nodeToString(final Element elem) { final StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(Constants.LESS_THAN).append(elem.getNodeName()); final NamedNodeMap namedNodeMap = elem.getAttributes(); for (int i = 0; i < namedNodeMap.getLength(); i++) { stringBuffer .append(Constants.STRING_BLANK) .append(namedNodeMap.item(i).getNodeName()) .append(Constants.EQUAL) .append(Constants.QUOTATION + namedNodeMap.item(i).getNodeValue() + Constants.QUOTATION); } stringBuffer.append(Constants.GREATER_THAN); final NodeList nodeList = elem.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { final Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // If the type of current node is ELEMENT_NODE, process it stringBuffer.append(nodeToString((Element) node)); } if (node.getNodeType() == Node.TEXT_NODE) { stringBuffer.append(node.getNodeValue()); } } stringBuffer.append("</").append(elem.getNodeName()).append(Constants.GREATER_THAN); return stringBuffer.toString(); }
/** * Loads a pair from the supplied XML element. * * @param graph the graph which elements to load Ideally, I need to match string IDs loaded to * those of the graph but this is not done because * <ul> * <li>graphseries used to mangle names of vertices, now this should not happen often (and * if I use relabelling when loading graphs, this would never happen). * <li>this method is expected to be general - purpose hence we do not expect a matching * graph to be present. * <li>matching was only needed when loading a compatibility table from a graph - graph * loader now does the matching after reading pairs. * </ul> * * @param elem element to load from * @return loaded state pair. */ public static <TARGET_TYPE, CACHE_TYPE extends CachedData<TARGET_TYPE, CACHE_TYPE>> PairScore readPair(AbstractLearnerGraph<TARGET_TYPE, CACHE_TYPE> graph, Element elem) { if (!elem.getNodeName().equals(StatechumXML.ELEM_PAIR.name())) throw new IllegalArgumentException("expected to load a pair but got " + elem.getNodeName()); if (!elem.hasAttribute(StatechumXML.ATTR_Q.name()) || !elem.hasAttribute(StatechumXML.ATTR_R.name())) throw new IllegalArgumentException("missing attribute in a pair"); String q = elem.getAttribute(StatechumXML.ATTR_Q.name()), r = elem.getAttribute(StatechumXML.ATTR_R.name()), score = elem.getAttribute(StatechumXML.ATTR_SCORE.name()), otherscore = elem.getAttribute(StatechumXML.ATTR_OTHERSCORE.name()); int scoreInt = JUConstants.intUNKNOWN, otherScoreInt = JUConstants.intUNKNOWN; if (score != null && score.length() > 0) try { scoreInt = Integer.valueOf(score); } catch (NumberFormatException ex) { statechum.Helper.throwUnchecked("failed to read a score in a pair", ex); } if (otherscore != null && otherscore.length() > 0) try { otherScoreInt = Integer.valueOf(otherscore); } catch (NumberFormatException ex) { statechum.Helper.throwUnchecked("failed to read a anotherscore in a pair", ex); } return new PairScore( AbstractLearnerGraph.generateNewCmpVertex(VertexID.parseID(q), graph.config), AbstractLearnerGraph.generateNewCmpVertex(VertexID.parseID(r), graph.config), scoreInt, otherScoreInt); }
private void readScraperFunctions(KodiScraper scraper, List<File> common) { for (File file : common) { // System.out.println("parsing common file: " + file); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document xml = parser.parse(file); Element docEl = xml.getDocumentElement(); // only process xml files with scraperfunctions if (docEl.getNodeName() == "scraperfunctions") { NodeList nl = docEl.getChildNodes(); // extract all scraperfunctions for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element el = (Element) n; ScraperFunction func = new ScraperFunction(); func.setName(el.getNodeName()); func.setClearBuffers(parseBoolean(el.getAttribute("clearbuffers"), true)); func.setAppendBuffer(parseAppendBuffer(el.getAttribute("dest"))); func.setDest(parseInt(el.getAttribute("dest"))); scraper.addFunction(func); // functions contain regexp expressions, so let's get those. processRegexps(func, el); } } } } catch (Exception e) { LOGGER.error("problem parsing scraper function", e); } } }
public HashMap<String, String> parseXml(InputStream inStream) throws Exception { HashMap<String, String> hashMap = new HashMap<String, String>(); // 实例化一个文档构建器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 通过文档构建器工厂获取一个文档构建器 DocumentBuilder builder = factory.newDocumentBuilder(); // 通过文档通过文档构建器构建一个文档实例 Document document = builder.parse(inStream); // 获取XML文件根节点 Element root = document.getDocumentElement(); // 获得所有子节点 NodeList childNodes = root.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { // 遍历子节点 Node childNode = (Node) childNodes.item(j); if (childNode.getNodeType() == Node.ELEMENT_NODE) { Element childElement = (Element) childNode; // 版本号 if ("version".equals(childElement.getNodeName())) { hashMap.put("version", childElement.getFirstChild().getNodeValue()); } // 软件名称 else if (("name".equals(childElement.getNodeName()))) { hashMap.put("name", childElement.getFirstChild().getNodeValue()); } // 下载地址 else if (("url".equals(childElement.getNodeName()))) { hashMap.put("url", childElement.getFirstChild().getNodeValue()); } } } return hashMap; }
@Override public void execute(PostSuiteParserPluginContext ctx) throws ParserPluginException { ExceptionAccumulator acc = new ExceptionAccumulator(); Set<String> dependentTests = ctx.getTestSuite().getDependencies().getDependenciesTests(); Set<String> dependentTestSuites = ctx.getTestSuite().getDependencies().getDependenciesSuites(); Element dependenciesElement = ParserHelper.getFirstChildElementCaseInsensitive( (Element) ctx.getRootNodeSuite(), DEPENDENCIES_NAME); for (Element e : ParserHelper.getChildren(dependenciesElement)) { try { AttributeHelper depAttributeHelper = new AttributeHelper(e); String dependentValue = depAttributeHelper.getRequiredString("name"); if (e.getNodeName().equalsIgnoreCase("test")) { dependentTests.add(dependentValue); } else if (e.getNodeName().equalsIgnoreCase("testsuite")) { dependentTestSuites.add(dependentValue); } else { throw new UnexpectedElementException(e); } } catch (Throwable th) { logger.fatal(th.getMessage()); // mc.error(th.getMessage()); acc.add(th); } } if (!acc.isEmpty()) { throw new ParserPluginException(acc); } }
// Serialize the bean using the specified namespace prefix & uri public String serialize(Object bean) throws IntrospectionException, IllegalAccessException { // Use the class name as the name of the root element String className = bean.getClass().getName(); String rootElementName = null; if (bean.getClass().isAnnotationPresent(ObjectXmlAlias.class)) { AnnotatedElement annotatedElement = bean.getClass(); ObjectXmlAlias aliasAnnotation = annotatedElement.getAnnotation(ObjectXmlAlias.class); rootElementName = aliasAnnotation.value(); } // Use the package name as the namespace URI Package pkg = bean.getClass().getPackage(); nsURI = pkg.getName(); // Remove a trailing semi-colon (;) if present (i.e. if the bean is an array) className = StringUtils.deleteTrailingChar(className, ';'); StringBuffer sb = new StringBuffer(className); String objectName = sb.delete(0, sb.lastIndexOf(".") + 1).toString(); domDocument = createDomDocument(objectName); document = domDocument.getDocument(); Element root = document.getDocumentElement(); // Parse the bean elements getBeanElements(root, rootElementName, className, bean); StringBuffer xml = new StringBuffer(); if (prettyPrint) xml.append(domDocument.serialize(lineSeperator, indentChars, includeXmlProlog)); else xml.append(domDocument.serialize(includeXmlProlog)); if (!includeTypeInfo) { int index = xml.indexOf(root.getNodeName()); xml.delete(index - 1, index + root.getNodeName().length() + 2); xml.delete(xml.length() - root.getNodeName().length() - 4, xml.length()); } return xml.toString(); }
public void parseXML(InputSource input) throws IOException { // Do the parsing and obtain the top-level node Element config = null; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); parser.setErrorHandler(new DefaultHandler()); config = parser.parse(input).getDocumentElement(); } catch (SAXException e) { throw new IOException(ValidatorMessages.ValidatorRuntime_badFormat); } catch (ParserConfigurationException e) { throw new IOException(ValidatorMessages.ValidatorRuntime_badFormat); } // If the top-level node wasn't what we expected, bail out if (!config.getNodeName().equalsIgnoreCase(NODE_VALIDATOR_SETTINGS)) { throw new IOException(ValidatorMessages.ValidatorRuntime_badFormat); } // Traverse the parsed structure and populate the InterpreterType to // Interpreter Map NodeList list = config.getChildNodes(); int length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); short type = node.getNodeType(); if (type == Node.ELEMENT_NODE) { Element validatorTypeElement = (Element) node; if (validatorTypeElement.getNodeName().equalsIgnoreCase(NODE_VALIDATOR_TYPE)) { populateValidatorType(validatorTypeElement); } } } }
@Override public void parse(NodeList childNodes) { if (childNodes != null && childNodes.getLength() > 0) { for (int i = 0; i < childNodes.getLength(); i++) { if (!(childNodes.item(i) instanceof Element)) continue; Element item = (Element) childNodes.item(i); if (item.getNodeName().equals("item")) { NodeList list = item.getChildNodes(); if (list != null && list.getLength() > 0) { String key = null; String value; for (int ii = 0; ii < list.getLength(); ii++) { if (!(list.item(ii) instanceof Element)) continue; Element item2 = (Element) list.item(ii); if (item2.getNodeName().equals("key")) { key = item2.getFirstChild().getNodeValue(); } else if (item2.getNodeName().equals("value")) { if (key == null) continue; NodeList deeper = item2.getChildNodes(); K object = (K) GenericConfigParse.parseObject(deeper); put(key, object); } } } } } } }
public L1NpcMakeItemAction(Element element) { super(element); _isAmountInputable = L1NpcXmlParser.getBoolAttribute(element, "AmountInputable", true); NodeList list = element.getChildNodes(); for (Element elem : new IterableElementList(list)) { if (elem.getNodeName().equalsIgnoreCase("Material")) { int id = Integer.valueOf(elem.getAttribute("ItemId")); int amount = Integer.valueOf(elem.getAttribute("Amount")); _materials.add(new L1ObjectAmount<Integer>(id, amount)); continue; } if (elem.getNodeName().equalsIgnoreCase("Item")) { int id = Integer.valueOf(elem.getAttribute("ItemId")); int amount = Integer.valueOf(elem.getAttribute("Amount")); _items.add(new L1ObjectAmount<Integer>(id, amount)); continue; } } if (_items.isEmpty() || _materials.isEmpty()) { throw new IllegalArgumentException(); } Element elem = L1NpcXmlParser.getFirstChildElementByTagName(element, "Succeed"); _actionOnSucceed = elem == null ? null : new L1NpcListedAction(elem); elem = L1NpcXmlParser.getFirstChildElementByTagName(element, "Fail"); _actionOnFail = elem == null ? null : new L1NpcListedAction(elem); }
public void testAnnotations() { SwingAppFrameworkInspector inspector = new SwingAppFrameworkInspector(); Document document = XmlUtils.documentFromString(inspector.inspect(null, Foo.class.getName())); assertEquals("inspection-result", document.getFirstChild().getNodeName()); // Entity Element entity = (Element) document.getDocumentElement().getFirstChild(); assertEquals(ENTITY, entity.getNodeName()); assertEquals(Foo.class.getName(), entity.getAttribute(TYPE)); assertFalse(entity.hasAttribute(NAME)); // Actions Element action = (Element) entity.getFirstChild(); assertEquals(ACTION, action.getNodeName()); assertEquals("doBar", action.getAttribute(NAME)); assertEquals("barLabel", action.getAttribute(LABEL)); assertEquals(action.getAttributes().getLength(), 2); assertEquals(entity.getChildNodes().getLength(), 1); }
public static Message parseMessage(Document document) { NodeList childs = document.getDocumentElement().getChildNodes(); boolean isMessage = false; boolean success = false; String text = ""; for (int i = 0; i < childs.getLength(); i++) { if (childs.item(i) instanceof Element) { Element el = (Element) childs.item(i); if (el.getNodeName().equals("text") || el.getNodeName().equals("message")) { text = el.getTextContent(); } if (el.getNodeName().equals("success")) { isMessage = true; success = Boolean.parseBoolean(el.getTextContent()); } } } if (isMessage) { return new Message(success, text); } return null; }
private static void loadFromStream(InputSource inputSource, Map<IPath, String> oldLocations) throws CoreException { Element cpElement; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); parser.setErrorHandler(new DefaultHandler()); cpElement = parser.parse(inputSource).getDocumentElement(); } catch (SAXException e) { throw createException(e, CorextMessages.JavaDocLocations_error_readXML); } catch (ParserConfigurationException e) { throw createException(e, CorextMessages.JavaDocLocations_error_readXML); } catch (IOException e) { throw createException(e, CorextMessages.JavaDocLocations_error_readXML); } if (cpElement == null) return; if (!cpElement.getNodeName().equalsIgnoreCase(NODE_ROOT)) { return; } NodeList list = cpElement.getChildNodes(); int length = list.getLength(); for (int i = 0; i < length; ++i) { Node node = list.item(i); short type = node.getNodeType(); if (type == Node.ELEMENT_NODE) { Element element = (Element) node; if (element.getNodeName().equalsIgnoreCase(NODE_ENTRY)) { String varPath = element.getAttribute(NODE_PATH); String varURL = parseURL(element.getAttribute(NODE_URL)).toExternalForm(); oldLocations.put(Path.fromPortableString(varPath), varURL); } } } }
private void parsePlanet(Element planetElement, Planet planet) { List<Satellite> satellitesList = new ArrayList<>(); NodeList satellites = planetElement.getElementsByTagName("satellites"); if (satellites.getLength() > 0) { satellites = satellites.item(0).getChildNodes(); for (int i = 0; i < satellites.getLength(); i++) { if (satellites.item(i).getNodeType() != Node.ELEMENT_NODE) { continue; } Satellite satellite = null; Element satelliteElement = (Element) satellites.item(i); if (satelliteElement.getNodeName().equals("satellite")) { satellite = new Satellite(); parseSatellite(satelliteElement, satellite); } else if (satelliteElement.getNodeName().equals("artificial")) { satellite = new ArtificialSatellite(); parseArtificial(satelliteElement, (ArtificialSatellite) satellite); } else if (satelliteElement.getNodeName().equals("ion_cannon")) { satellite = new IonCannon(); parseIonCannon(satelliteElement, (IonCannon) satellite); } else if (satelliteElement.getNodeName().equals("station")) { satellite = new SpaceStation(); parseStation(satelliteElement, (SpaceStation) satellite); } satellitesList.add(satellite); } planet.setSatellites(satellitesList); } parseBody(planetElement, planet); }
private void xmlReadSelectedElements(JarPackageData jarPackage, Element element) throws java.io.IOException { if (element.getNodeName().equals("selectedElements")) { // $NON-NLS-1$ jarPackage.setExportClassFiles( getBooleanAttribute(element, "exportClassFiles")); // $NON-NLS-1$ jarPackage.setExportOutputFolders( getBooleanAttribute(element, "exportOutputFolder", false)); // $NON-NLS-1$ jarPackage.setExportJavaFiles(getBooleanAttribute(element, "exportJavaFiles")); // $NON-NLS-1$ NodeList selectedElements = element.getChildNodes(); Set<IAdaptable> elementsToExport = new HashSet<IAdaptable>(selectedElements.getLength()); for (int j = 0; j < selectedElements.getLength(); j++) { Node selectedNode = selectedElements.item(j); if (selectedNode.getNodeType() != Node.ELEMENT_NODE) continue; Element selectedElement = (Element) selectedNode; if (selectedElement.getNodeName().equals("file")) // $NON-NLS-1$ addFile(elementsToExport, selectedElement); else if (selectedElement.getNodeName().equals("folder")) // $NON-NLS-1$ addFolder(elementsToExport, selectedElement); else if (selectedElement.getNodeName().equals("project")) // $NON-NLS-1$ addProject(elementsToExport, selectedElement); else if (selectedElement.getNodeName().equals("javaElement")) // $NON-NLS-1$ addJavaElement(elementsToExport, selectedElement); // Note: Other file types are not handled by this writer } jarPackage.setElements(elementsToExport.toArray()); } }
/* (non-Javadoc) * @see org.eclipse.pde.internal.builders.ExtensionsErrorReporter#validateContent(org.eclipse.core.runtime.IProgressMonitor) */ public void validateContent(IProgressMonitor monitor) { Element element = getDocumentRoot(); if (element == null) return; String elementName = element.getNodeName(); if (!getRootElementName().equals(elementName)) { reportIllegalElement(element, CompilerFlags.ERROR); } else { validateTopLevelAttributes(element); NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { if (monitor.isCanceled()) break; Element child = (Element) children.item(i); String name = child.getNodeName(); if (name.equals("extension")) { // $NON-NLS-1$ validateExtension(child); } else if (name.equals("extension-point")) { // $NON-NLS-1$ validateExtensionPoint(child); } else if (name.equals("runtime")) { // $NON-NLS-1$ validateRuntime(child); } else if (name.equals("requires")) { // $NON-NLS-1$ validateRequires(child); } else { int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT); if (severity != CompilerFlags.IGNORE) reportIllegalElement(element, severity); } } } }
protected static void ensureRootNodeNameIs(String rootName, Element elem) throws WeiboException { if (!rootName.equals(elem.getNodeName())) { throw new WeiboException( "Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/."); } }
protected static void ensureRootNodeNameIs(String rootName, Document doc) throws WeiboException { Element elem = doc.getDocumentElement(); if (!rootName.equals(elem.getNodeName())) { throw new WeiboException( "Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Twitter API at http://status.twitter.com/"); } }
public static L1NpcAction newAction(Element element) { try { Constructor<? extends L1NpcXmlAction> con = _actions.get(element.getNodeName()); return con.newInstance(element); } catch (NullPointerException e) { _log.warning(element.getNodeName() + " 未定義のNPCアクションです"); } catch (Exception e) { _log.log(Level.SEVERE, "NpcActionのクラスロードに失敗", e); } return null; }
protected static void ensureRootNodeNameIs(String rootName, Document doc) throws HttpException { Element elem = doc.getDocumentElement(); if (!rootName.equals(elem.getNodeName())) { throw new HttpException( "Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/"); } }
/** * @param typeToSet * @param iterable * @param parentElement * @param duplexExpression * @param elementSelector */ private int applyIterableSetOnElement( final Iterable<?> iterable, final Element parentElement, final DuplexExpression duplexExpression) { int changeCount = 0; for (Object o : iterable) { if (o == null) { continue; } if (!isStructureChangingValue(o)) { final Node newElement = duplexExpression.createChildWithPredicate(parentElement); final String asString = projector .config() .getStringRenderer() .render(o.getClass(), o, duplexExpression.getExpressionFormatPattern()); newElement.setTextContent(asString); ++changeCount; continue; } Element elementToAdd; if (o instanceof Node) { final Node n = (Node) o; elementToAdd = (Element) (Node.DOCUMENT_NODE != n.getNodeType() ? n : n.getOwnerDocument() == null ? null : n.getOwnerDocument().getDocumentElement()); } else { final DOMAccess p = (DOMAccess) o; elementToAdd = p.getDOMBaseElement(); } if (elementToAdd == null) { continue; } Element clone = (Element) elementToAdd.cloneNode(true); Element childWithPredicate = (Element) duplexExpression.createChildWithPredicate(parentElement); final String elementName = childWithPredicate.getNodeName(); if (!elementName.equals(clone.getNodeName())) { if (!"*".equals(elementName)) { clone = DOMHelper.renameElement(clone, elementName); } } DOMHelper.replaceElement(childWithPredicate, clone); ++changeCount; } return changeCount; }
/** * <work-area id="tree-edit"> <caption>Tree editor</caption> <link>tree-editor.jsp</link> * <icon>tree.gif</icon> <modules> <module name="tree"/> <module name="grid"/> <module * name="editor"/> </modules> </work-area> * * @param el */ public WorkAreaImpl(Element el, Core core) throws CMCConfigurationException, NoSuchModuleException { if (!"work-area".equals(el.getNodeName())) throw new CMCConfigurationException("Node name must be 'work-area'!"); id = el.getAttribute("id"); for (int i = 0; i < el.getChildNodes().getLength(); i++) { if (el.getChildNodes().item(i).getNodeType() != Node.ELEMENT_NODE) continue; Element e = (Element) el.getChildNodes().item(i); if ("caption".equals(e.getNodeName())) { if (e.getFirstChild() == null) throw new CMCConfigurationException("Caption must be set"); this.caption = e.getFirstChild().getNodeValue(); // log.debug("Caption is: " + this.caption); } else if ("link".equals(e.getNodeName())) { if (e.getFirstChild() == null) throw new CMCConfigurationException("Link must be set"); setUrl(e.getFirstChild().getNodeValue()); // log.debug("URL is: " + this.url); } else if ("icon".equals(e.getNodeName())) { if (e.getFirstChild() == null) throw new CMCConfigurationException("Icon must be set"); this.icon = e.getFirstChild().getNodeValue(); if (icon.endsWith("gif")) { icon = icon.replaceAll(".gif", ".png"); } // log.debug("Icon is: " + this.icon); } else if ("modules".equals(e.getNodeName())) { log.debug("we are loading modules..."); log.debug("e.getChildNodes().getLength() = " + e.getChildNodes().getLength()); for (int k = 0; k < e.getChildNodes().getLength(); k++) { Node n = e.getChildNodes().item(k); if (n.getNodeType() != Node.ELEMENT_NODE) continue; if (!"module".equals(n.getNodeName())) continue; Element m = (Element) n; String modulename = m.getAttribute("name"); modulesList.add(core.getModule(modulename)); modulesMap.put(modulename, core.getModule(modulename)); } } } if (url == null) { throw new CMCConfigurationException("Url is not set!"); } else { if (url.startsWith("http://") || url.startsWith("/")) { log.debug("url is an external link! URL= " + url); } else { if (url.indexOf("?") > -1) { url += "&workarea=" + id; } else { url += "?workarea=" + id; } } log.debug("url = " + url); } log.debug("modulesList = " + modulesList); }
public ContentAssistHistory load(InputSource source) throws CoreException { Element root; try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); parser.setErrorHandler(new DefaultHandler()); root = parser.parse(source).getDocumentElement(); } catch (SAXException e) { throw createException(e, JavaTextMessages.ContentAssistHistory_deserialize_error); } catch (ParserConfigurationException e) { throw createException(e, JavaTextMessages.ContentAssistHistory_deserialize_error); } catch (IOException e) { throw createException(e, JavaTextMessages.ContentAssistHistory_deserialize_error); } if (root == null || !root.getNodeName().equalsIgnoreCase(NODE_ROOT)) return null; int maxLHS = parseNaturalInt(root.getAttribute(ATTRIBUTE_MAX_LHS), DEFAULT_TRACKED_LHS); int maxRHS = parseNaturalInt(root.getAttribute(ATTRIBUTE_MAX_RHS), DEFAULT_TRACKED_RHS); ContentAssistHistory history = new ContentAssistHistory(maxLHS, maxRHS); NodeList list = root.getChildNodes(); int length = list.getLength(); for (int i = 0; i < length; ++i) { Node lhsNode = list.item(i); if (lhsNode.getNodeType() == Node.ELEMENT_NODE) { Element lhsElement = (Element) lhsNode; if (lhsElement.getNodeName().equalsIgnoreCase(NODE_LHS)) { String lhs = lhsElement.getAttribute(ATTRIBUTE_NAME); if (lhs != null) { Set<String> cache = history.getCache(lhs); NodeList children = lhsElement.getChildNodes(); int nRHS = children.getLength(); for (int j = 0; j < nRHS; j++) { Node rhsNode = children.item(j); if (rhsNode.getNodeType() == Node.ELEMENT_NODE) { Element rhsElement = (Element) rhsNode; if (rhsElement.getNodeName().equalsIgnoreCase(NODE_RHS)) { String rhs = rhsElement.getAttribute(ATTRIBUTE_NAME); if (rhs != null) { cache.add(rhs); } } } } } } } } return history; }
public String selectAllTable(String DBname, String tableName) throws ParserConfigurationException, SAXException, IOException { if (!checkDB(DBname)) { MyLogger.Log().error(DBMS.DB_NOT_FOUND); return DBMS.DB_NOT_FOUND; } if (!checkTable(DBname, tableName)) { MyLogger.Log().error(DBMS.TABLE_NOT_FOUND); return DBMS.TABLE_NOT_FOUND; } String dir = DBMS_Directory + "\\DB " + DBname + "\\" + tableName + ".xml"; Document doc = Load(dir); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("*"); String columns = ""; int numOfColumns = 0; for (int i = 1; i < nodeList.getLength(); i++) { Element fileElement = (Element) nodeList.item(i); if (!fileElement.getNodeName().toString().contains("ROW_NUM") && !columns.contains(fileElement.getNodeName().toString())) { columns = columns + fileElement.getNodeName() + " "; numOfColumns++; } } String values = ""; int countValues = 0; NodeList nl = doc.getElementsByTagName(tableName); NodeList n = nl.item(0).getChildNodes(); for (int i = 0; i < n.getLength(); i++) { NodeList rows = n.item(i).getChildNodes(); for (int j = 0; j < rows.getLength(); j++) { countValues++; if (numOfColumns == countValues) { values = values + rows.item(j).getChildNodes().item(0).getNodeValue(); } else { values = values + rows.item(j).getChildNodes().item(0).getNodeValue() + " "; } } if (numOfColumns == countValues) { values += "\n"; countValues = 0; } } if (values == "") { MyLogger.Log().error(DBMS.NOT_MATCH_CRITERIA); return DBMS.NOT_MATCH_CRITERIA; } values = values.substring(0, values.length() - 1); LastRow = maxRownumber(DBname, tableName); MyLogger.Log().info(DBMS.Con_Select); return values; }
public CMElementDeclaration getCMElementDeclaration(Element element) { CMElementDeclaration result = null; Document document = element.getOwnerDocument(); String[] doctypeInfo = getDoctypeInfo(document); if (doctypeInfo != null) { // we have detected doctype information so we assume that we can locate the // CMElementDeclaration // in the CMDocument's table of global elements CMDocument cmDocument = getCorrespondingCMDocument(element, false); // TODO... consider replacing above with // CMDocument cmDocument = getCMDocument(document, doctypeInfo[0], doctypeInfo[1]); if (cmDocument != null) { result = (CMElementDeclaration) cmDocument.getElements().getNamedItem(element.getNodeName()); // this is a hack to get our xsl code assist working... we might want to handle similar // grammar behaviour via some established model query setting if (result == null && getImplictDoctype(document) != null) { Node parent = element.getParentNode(); if (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) { result = getCMElementDeclaration((Element) parent); } } } } else { // here we use a namespaceTable to consider if the root element has any namespace information // NamespaceTable namespaceTable = new NamespaceTable(element.getOwnerDocument()); List list = NamespaceTable.getElementLineage(element); Element rootElement = (Element) list.get(0); namespaceTable.addElement(rootElement); if (namespaceTable.isNamespaceEncountered()) { // we assume that this is an XMLSchema style namespace aware document result = getCMElementDeclaration(element, list, namespaceTable); } else { result = checkExternalSchema(element); if (result == null) { // we assume that this is an inferred CMDocument for a DTD style 'namespaceless' document CMDocument cmDocument = getCMDocument("", "", "DTD"); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (cmDocument != null) { result = (CMElementDeclaration) cmDocument.getElements().getNamedItem(element.getNodeName()); } } } } return result; }
/** @see org.newdawn.slick.svg.inkscape.ElementProcessor#handles(org.w3c.dom.Element) */ public boolean handles(Element element) { if (element.getNodeName().equals("polygon")) { return true; } if (element.getNodeName().equals("path")) { if (!"arc".equals(element.getAttributeNS(Util.SODIPODI, "type"))) { return true; } } return false; }
private ArrayList getNodeElements(Element notationElement) { ArrayList result = new ArrayList(); NodeList nodeList = notationElement.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { org.w3c.dom.Node node = nodeList.item(i); if (!(node instanceof Element)) continue; Element element = (Element) node; if ("node".equals(element.getNodeName()) || "node-container".equals(element.getNodeName())) { result.add(element); } } return result; }
/** * Loads the initial data from the supplied XML element. * * @param elem where to load from * @return initial data */ public InitialData readInitialData(Element elem) { if (!elem.getNodeName().equals(StatechumXML.ELEM_INIT.name())) throw new IllegalArgumentException( "expecting to load learner initial data " + elem.getNodeName()); NodeList children = elem.getChildNodes(); InitialData result = new InitialData(); for (int i = 0; i < children.getLength(); ++i) if (children.item(i).getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) children.item(i); if (e.getNodeName().equals(StatechumXML.graphmlNodeNameNS.toString())) { if (result.graph != null) throw new IllegalArgumentException("duplicate graph element"); result.graph = new LearnerGraph(config); AbstractPersistence.loadGraph(e, result.graph, decoratedLearner.getLabelConverter()); } else if (e.getNodeName().equals(StatechumXML.ELEM_SEQ.name())) { String sequenceName = e.getAttribute(StatechumXML.ATTR_SEQ.name()); if (sequenceName.equals(StatechumXML.ATTR_POSITIVE_SEQUENCES.name())) { if (result.plus != null) throw new IllegalArgumentException("duplicate positive element"); result.plus = labelio.readSequenceList(e, StatechumXML.ATTR_POSITIVE_SEQUENCES.name()); if (!e.hasAttribute(StatechumXML.ATTR_POSITIVE_SIZE.name())) throw new IllegalArgumentException("missing positive size"); String size = e.getAttribute(StatechumXML.ATTR_POSITIVE_SIZE.name()); try { result.plusSize = Integer.valueOf(size); } catch (NumberFormatException ex) { statechum.Helper.throwUnchecked("positive value is not an integer " + size, ex); } } else if (sequenceName.equals(StatechumXML.ATTR_NEGATIVE_SEQUENCES.name())) { if (result.minus != null) throw new IllegalArgumentException("duplicate negative element"); result.minus = labelio.readSequenceList(e, StatechumXML.ATTR_NEGATIVE_SEQUENCES.name()); if (!e.hasAttribute(StatechumXML.ATTR_NEGATIVE_SIZE.name())) throw new IllegalArgumentException("missing negative size"); String size = e.getAttribute(StatechumXML.ATTR_NEGATIVE_SIZE.name()); try { result.minusSize = Integer.valueOf(size); } catch (NumberFormatException ex) { statechum.Helper.throwUnchecked("negative value is not an integer " + size, ex); } } else throw new IllegalArgumentException("unexpected kind of sequences: " + sequenceName); } else throw new IllegalArgumentException("unexpected element " + e.getNodeName()); } if (result.graph == null) throw new IllegalArgumentException("missing graph"); if (result.plus == null) throw new IllegalArgumentException("missing positive sequences"); if (result.minus == null) throw new IllegalArgumentException("missing negative sequences"); return result; }
/** * check whether the href/id element defined by keys has been exported. * * @param href href * @param id id * @param key keyname * @param tempDir absolute path to temporary director * @return result list */ public List<Boolean> checkExport( String href, final String id, final String key, final File tempDir) { // parsed export .xml to get exported elements final File exportFile = new File(tempDir, FILE_NAME_EXPORT_XML); boolean idExported = false; boolean keyrefExported = false; try { // load export.xml only once if (root == null) { final DocumentBuilder builder = XMLUtils.getDocumentBuilder(); builder.setEntityResolver(CatalogUtils.getCatalogResolver()); root = builder.parse(new InputSource(new FileInputStream(exportFile))); } // get file node which contains the export node final Element fileNode = searchForKey(root.getDocumentElement(), href, "file"); if (fileNode != null) { // iterate the child nodes final NodeList pList = fileNode.getChildNodes(); for (int j = 0; j < pList.getLength(); j++) { final Node node = pList.item(j); if (Node.ELEMENT_NODE == node.getNodeType()) { final Element child = (Element) node; // compare keys if (child.getNodeName().equals("keyref") && child.getAttribute(ATTRIBUTE_NAME_NAME).equals(key)) { keyrefExported = true; // compare topic id } else if (child.getNodeName().equals("topicid") && child.getAttribute(ATTRIBUTE_NAME_NAME).equals(id)) { idExported = true; // compare element id } else if (child.getNodeName().equals("id") && child.getAttribute(ATTRIBUTE_NAME_NAME).equals(id)) { idExported = true; } } if (idExported && keyrefExported) { break; } } } } catch (final Exception e) { e.printStackTrace(); } final List<Boolean> list = new ArrayList<>(); list.add(idExported); list.add(keyrefExported); return list; }