private FixedCoords getFixedCoords(Element shape, int width, int height, String suffix) { if (suffix == null) suffix = ""; // parse the coordinates and check if they are fixed or reverse fixed String val = shape.getAttribute(ATR_X + suffix); int x, y, fixedX = 0, fixedY = 0; if (val.endsWith(VAL_RF)) { x = width; fixedX = x - Integer.parseInt(val.substring(0, val.length() - 2)); } else if (val.endsWith(VAL_F)) { x = Integer.parseInt(val.substring(0, val.length() - 1)); fixedX = -1; } else { x = Integer.parseInt(val); } val = shape.getAttribute(ATR_Y + suffix); if (val.endsWith(VAL_RF)) { y = height; fixedY = y - Integer.parseInt(val.substring(0, val.length() - 2)); } else if (val.endsWith(VAL_F)) { y = Integer.parseInt(val.substring(0, val.length() - 1)); fixedY = -1; } else { y = Integer.parseInt(val); } return new FixedCoords(x, fixedX, y, fixedY); }
@Test public void testAddRemoveChild() throws Exception { // builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); String xml = "<?xml version=\"1.0\"?>" + "<root>" + "<item id=\"a\"/>" + "<child id=\"1\"/>" + "<item id=\"b\"/>" + "<child id=\"2\"/>" + "</root>"; DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element root = doc.getDocumentElement(); Element newElem = doc.createElement("tail"); newElem.setAttribute("id", "3"); Node appended = root.appendChild(newElem); Assert.assertEquals("added element", "tail", root.getLastChild().getNodeName()); Assert.assertEquals("added attribute", "3", ((Element) root.getLastChild()).getAttribute("id")); root.setAttribute("id", "root"); Assert.assertEquals("root attribute set", "root", root.getAttribute("id")); root.removeAttribute("id"); Assert.assertEquals("root attribute remove", null, root.getAttribute("id")); root.removeChild(appended); Assert.assertEquals("removed element", "child", root.getLastChild().getNodeName()); Assert.assertEquals("removed element", "2", ((Element) root.getLastChild()).getAttribute("id")); }
private Dim getDim(Element shape) { return new Dim( Integer.parseInt(shape.getAttribute(ATR_X)), Integer.parseInt(shape.getAttribute(ATR_Y)), Integer.parseInt(shape.getAttribute(ATR_WIDTH)), Integer.parseInt(shape.getAttribute(ATR_HEIGHT))); }
/** * Reads in a decision stored in XML. * * @param decN - the XML element. */ public void fromXML(Element decN) { this.fromXML = true; RationaleDB db = RationaleDB.getHandle(); String rid = decN.getAttribute("rid"); id = Integer.parseInt(rid.substring(2)); name = decN.getAttribute("name"); type = DecisionType.fromString(decN.getAttribute("type")); devPhase = Phase.fromString(decN.getAttribute("phase")); status = DecisionStatus.fromString(decN.getAttribute("status")); Node child = decN.getFirstChild(); importHelper(child); Node nextNode = child.getNextSibling(); while (nextNode != null) { importHelper(nextNode); nextNode = nextNode.getNextSibling(); } db.addPatternDecisionFromXML(this); }
public List parsePage(String pageCode) { List sections = new ArrayList(); List folders = new ArrayList(); List files = new ArrayList(); int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\""); int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\""); String usefulSection = ""; if (start != -1 && end != -1) { usefulSection = pageCode.substring(start, end); } else { debug("Could not parse page"); } try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(usefulSection)); Document doc = db.parse(is); NodeList divs = doc.getElementsByTagName("div"); for (int i = 0; i < divs.getLength(); i++) { Element div = (Element) divs.item(i); boolean isFolder = false; if (div.getAttribute("class").equals("filename")) { NodeList imgs = div.getElementsByTagName("img"); for (int j = 0; j < imgs.getLength(); j++) { Element img = (Element) imgs.item(j); if (img.getAttribute("class").indexOf("folder") > 0) { isFolder = true; } else { isFolder = false; // it's a file } } NodeList anchors = div.getElementsByTagName("a"); Element anchor = (Element) anchors.item(0); String attr = anchor.getAttribute("href"); String fileName = anchor.getAttribute("title"); String fileURL; if (isFolder && !attr.equals("#")) { folders.add(attr); folders.add(fileName); } else if (!isFolder && !attr.equals("#")) { // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be // sneaky here. fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1"; files.add(fileURL); files.add(fileName); } } } } catch (Exception e) { debug(e.toString()); } sections.add(files); sections.add(folders); return sections; }
private NELemma createNELemma(Element n) { NELemma neLemma = new NELemma(); neLemma.lemma = n.getAttribute("normalizedForm"); neLemma.neLabel = n.getAttribute("type"); neLemma.gloss = n.getAttribute("gloss"); neLemma = (NELemma) DatabaseMapping.canonical(databaseMapping.lemmaMap, neLemma); return neLemma; }
private Lineprops getLineProps(Element shape) { return new Lineprops( shape.hasAttribute(ATR_STROKE) ? Float.parseFloat(shape.getAttribute(ATR_STROKE)) : IMPLIED_STROKE, shape.hasAttribute(ATR_LINETYPE) ? Float.parseFloat(shape.getAttribute(ATR_LINETYPE)) : IMPLIED_LINE); }
private static void removeConnections(Element parent, String child) { for (Element conn : childElementsWithName(parent, "conn")) { String inputPort = conn.getAttribute("input"); String inputNode = inputPort.split("\\.")[0]; String outputNode = conn.getAttribute("output"); if (inputNode.equals(child) || outputNode.equals(child)) parent.removeChild(conn); } }
/** * ** Gets a virtual DBRecord from the specified remote service ** @param servReq The remote web * service ** @return The virtual DBRecord (cannot be saved or reloaded) */ @SuppressWarnings("unchecked") public gDBR getVirtualDBRecord(final ServiceRequest servReq) throws DBException { String CMD_dbget = DBFactory.CMD_dbget; String TAG_Response = servReq.getTagResponse(); String TAG_Record = DBFactory.TAG_Record; String ATTR_command = servReq.getAttrCommand(); String ATTR_result = servReq.getAttrResult(); /* send request / get response */ Document xmlDoc = null; try { xmlDoc = servReq.sendRequest( CMD_dbget, new ServiceRequest.RequestBody() { public StringBuffer appendRequestBody(StringBuffer sb, int indent) { return DBRecordKey.this.toRequestXML(sb, indent); } }); } catch (IOException ioe) { Print.logException("Error", ioe); throw new DBException("Request read error", ioe); } /* parse 'GTSResponse' */ Element gtsResponse = xmlDoc.getDocumentElement(); if (!gtsResponse.getTagName().equalsIgnoreCase(TAG_Response)) { Print.logError("Request XML does not start with '%s'", TAG_Response); throw new DBException("Response XML does not begin eith '" + TAG_Response + "'"); } /* request command/argument */ String cmd = StringTools.trim(gtsResponse.getAttribute(ATTR_command)); String result = StringTools.trim(gtsResponse.getAttribute(ATTR_result)); if (StringTools.isBlank(result)) { result = StringTools.trim(gtsResponse.getAttribute("type")); } if (!result.equalsIgnoreCase("success")) { Print.logError("Response indicates failure"); throw new DBException("Response does not indicate 'success'"); } /* Record */ NodeList rcdList = XMLTools.getChildElements(gtsResponse, TAG_Record); if (rcdList.getLength() <= 0) { Print.logError("No 'Record' tags"); throw new DBException("GTSResponse does not contain any 'Record' tags"); } Element rcdElem = (Element) rcdList.item(0); /* return DBRecord */ gDBR dbr = (gDBR) DBFactory.parseXML_DBRecord(rcdElem); dbr.setVirtual(true); return dbr; }
public List getUserList() { List<Map> list = new ArrayList<Map>(); try { /* String apiUrl=rallyApiHost+"/user?query="+ "((TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6169133135)%20or%20"+ "(TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6083311244))"+ "&fetch=true&order=Name&start=1&pagesize=100"; */ String apiUrl = rallyApiHost + "/user?query=(Disabled%20=%20false)" + "&fetch=true&order=Name&start=1&pagesize=100"; log.info("apiUrl=" + apiUrl); String responseXML = getRallyXML(apiUrl); org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = bSAX.build(new StringReader(responseXML)); Element root = doc.getRootElement(); XPath xpath = XPath.newInstance("//Object"); List xlist = xpath.selectNodes(root); Iterator iter = xlist.iterator(); while (iter.hasNext()) { Map map = new HashMap(); Element item = (Element) iter.next(); String userRef = item.getAttribute("ref").getValue(); String userName = item.getAttribute("refObjectName").getValue(); String userObjectId = item.getChildText("ObjectID"); map.put("userRef", userRef); map.put("userObjectId", userObjectId); map.put("userName", userName); list.add(map); } } catch (Exception ex) { log.error("", ex); } return list; }
public FieldObject(Element element, SimpleMethod simpleMethod) { super(element, simpleMethod); // the schema for this element now just has the "field" attribute, though the old "field-name" // and "map-name" pair is still supported fieldAcsr = new ContextAccessor<T>(element.getAttribute("field"), element.getAttribute("field-name")); mapAcsr = new ContextAccessor<Map<String, ? extends Object>>(element.getAttribute("map-name")); type = element.getAttribute("type"); if (UtilValidate.isEmpty(type)) { type = "String"; } }
public FieldToField(Element element, SimpleMethod simpleMethod) { super(element, simpleMethod); mapAcsr = new ContextAccessor<Map<String, Object>>(element.getAttribute("map-name")); fieldAcsr = new ContextAccessor<Object>(element.getAttribute("field-name")); toMapAcsr = new ContextAccessor<Map<String, Object>>(element.getAttribute("to-map-name")); toFieldAcsr = new ContextAccessor<Object>(element.getAttribute("to-field-name")); // set toMapAcsr and toFieldAcsr to their defualt values of mapAcsr and fieldAcsr if empty if (toMapAcsr.isEmpty()) { toMapAcsr = mapAcsr; } if (toFieldAcsr.isEmpty()) { toFieldAcsr = fieldAcsr; } }
private static Set<String> getChildNodeNames(Element parent) { HashSet<String> names = new HashSet<String>(); for (Element e : childElementsWithName(parent, "node")) { names.add(e.getAttribute("name")); } return names; }
public ArrayList<String> parseXML() throws Exception { ArrayList<String> ret = new ArrayList<String>(); handshake(); URL url = new URL( "http://mangaonweb.com/page.do?cdn=" + cdn + "&cpn=book.xml&crcod=" + crcod + "&rid=" + (int) (Math.random() * 10000)); String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(page)); Document d = builder.parse(is); Element doc = d.getDocumentElement(); NodeList pages = doc.getElementsByTagName("page"); total = pages.getLength(); for (int i = 0; i < pages.getLength(); i++) { Element e = (Element) pages.item(i); ret.add(e.getAttribute("path")); } return (ret); }
private void processPanel(Session session, Element element, HashMap additionalInformation) { panelElementPresent = true; String panelName = element.getAttribute("name"); if (panelName == null) { panelName = "Panel" + panelCounter++; } List<Track> panelTracks = new ArrayList(); NodeList elements = element.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) { Node childNode = elements.item(i); if (childNode.getNodeName().equalsIgnoreCase(SessionElement.DATA_TRACK.getText()) || // Is this a track? childNode.getNodeName().equalsIgnoreCase(SessionElement.TRACK.getText())) { List<Track> tracks = processTrack(session, (Element) childNode, additionalInformation); if (tracks != null) { panelTracks.addAll(tracks); } } else { process(session, childNode, additionalInformation); } } TrackPanel panel = IGV.getInstance().getTrackPanel(panelName); panel.addTracks(panelTracks); }
@Test public void testElementGetAPIs() throws Exception { // builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); String xml = "<?xml version=\"1.0\"?>" + "<t:root xmlns=\"http://void.com/\" xmlns:t=\"http://t.com/\" id=\"stella\" t:type=\"police\">" + "<t:item id=\"a\"/>" + "<child id=\"1\"/>" + "<t:item id=\"b\"/>" + "<child id=\"2\"/>" + "</t:root>"; DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); Element root = doc.getDocumentElement(); Assert.assertEquals("tagName", "t:root", root.getTagName()); Assert.assertEquals("attribute", "stella", root.getAttribute("id")); Assert.assertEquals("attributeNS", "police", root.getAttributeNS("http://t.com/", "type")); Assert.assertEquals("attribute(has)", true, root.hasAttribute("id")); Assert.assertEquals("attribute(has)", false, root.hasAttribute("__id__")); Assert.assertEquals("attributeNS(has)", true, root.hasAttributeNS("http://t.com/", "type")); Assert.assertEquals("attributeNS(has)", false, root.hasAttributeNS("http://t.com/", "tipe")); }
public void importDocument(NEDocument document) { Element root = document.DOMDocument.getDocumentElement(); List<Element> names = XML.getElementsByTagname(root, "ns:ne", false); nl.openconvert.log.ConverterLog.defaultLog.println("TITLE: " + document.title); ElementConcordancer concordancer = new ElementConcordancer(); databaseMapping.documentMapping.insertObject(connection, "documents", document); for (Element n : names) { NELemma neLemma = createNELemma(n); NEWordform neWord = createNEWordform(n); NEAnalyzedWordform awf = createNEAnalyzedWordform(neLemma, neWord); String id = n.getAttribute("xml:id"); if (id != null && id.length() > 0) { String quotation = concordancer.getConcordance(n); NEAttestation at = createNEAttestation(document, awf, id, quotation); } List<Element> neParts = XML.getElementsByTagname(n, "ns:nePart", false); int partNumber = 0; if (addEntriesForParts) for (Element np : neParts) { NELemma pLemma = createNELemma(np); NEWordform pWord = createNEWordform(np); NEAnalyzedWordform pAwf = createNEAnalyzedWordform(pLemma, pWord); String pid = np.getAttribute("xml:id"); if (pid != null && pid.length() > 0) { NEAttestation at = createNEAttestation(document, pAwf, pid, null); } NEContainment nec = new NEContainment(); nec.parent = awf; nec.child = pAwf; nec.partNumber = partNumber++; nec = (NEContainment) DatabaseMapping.canonical(databaseMapping.containmentMap, nec); // HM (bah.) should add extra key for group id to this... // or should we add this to the PoS info for an NE (structure?) } // lexicon.addLemma(lemma, PoS, neLabel, gloss); } }
private static void removeConnection(Element parent, String child, String input) { for (Element conn : childElementsWithName(parent, "conn")) { String inputPort = conn.getAttribute("input"); if (inputPort.equals(String.format("%s.%s", child, input))) { parent.removeChild(conn); } } }
private static Element portWithName(Element nodeElement, String portName) { for (Element port : childElementsWithName(nodeElement, "port")) { if (port.getAttribute("name").equals(portName)) { return port; } } return null; }
public BaseCompare(Element element, SimpleMapProcess simpleMapProcess) { super(element, simpleMapProcess); this.operator = element.getAttribute("operator"); this.type = element.getAttribute("type"); this.format = element.getAttribute("format"); /* -- Let ObjectType handle the default -- if (UtilValidate.isEmpty(this.format)) { if ("Date".equals(type)) { this.format = "yyyy-MM-dd"; } else if ("Time".equals(type)) { this.format = "HH:mm:ss"; } else if ("Timestamp".equals(type)) { this.format = "yyyy-MM-dd HH:mm:ss"; } } */ }
private String getAttribute(Element element, String key) { String value = element.getAttribute(key); if (value != null) { if (value.trim().equals("")) { value = null; } } return value; }
private Text makeText(Element textNode, ClassGraphics graphics) { String str = textNode.getAttribute(ATR_STRING); String fontName = textNode.getAttribute(ATR_FONTNAME); int fontStyle = Integer.parseInt(textNode.getAttribute(ATR_FONTSTYLE)); int fontSize = Integer.parseInt(textNode.getAttribute(ATR_FONTSIZE)); Font font = new Font(fontName, fontStyle, fontSize); FixedCoords fc = getFixedCoords(textNode, graphics.getBoundWidth(), graphics.getBoundHeight(), null); Text newText = new Text(fc.x, fc.y, font, getColor(textNode), str, isShapeFixed(textNode)); newText.setFixedX(fc.fx); newText.setFixedY(fc.fy); return newText; }
private static String getParentPublishedInput(Element parent, String child, String input) { for (Element port : childElementsWithName(parent, "port")) { Attr childRef = port.getAttributeNode("childReference"); if (childRef != null && childRef.getValue().equals(String.format("%s.%s", child, input))) { return port.getAttribute("name"); } } return null; }
/** * Parses an XML element as a date * * @param element The element containing the date * @return The date value parsed from the element * @throws IOException If there's an error parsing the date */ public Object readDate(Element element) throws IOException { // Get the text corresponding to this element String str = getElementString(element); String fmt = element.getAttribute("format"); if ("".equals(fmt)) { return parseDate(str, JOXDateHandler.determineDateFormat()); } else { return parseDate(str, new SimpleDateFormat(fmt)); } }
JdbcIndexDefinition( DataSource ds, Element element, Set allIndexedFields, boolean storeText, boolean mergeText, Analyzer a, boolean isSub) { this.dataSource = ds; indexSql = element.getAttribute("sql"); key = element.getAttribute("key"); String elementId = element.getAttribute("identifier"); identifier = "".equals(elementId) ? key : elementId; findSql = element.getAttribute("find"); NodeList childNodes = element.getChildNodes(); for (int k = 0; k < childNodes.getLength(); k++) { if (childNodes.item(k) instanceof Element) { Element childElement = (Element) childNodes.item(k); if ("field".equals(childElement.getLocalName())) { if (childElement.getAttribute("keyword").equals("true")) { keyWords.add(childElement.getAttribute("name")); } String m = childElement.getAttribute("multiple"); if ("".equals(m)) m = "add"; if (!m.equals("add")) { nonDefaultMultiples.put( childElement.getAttribute("name"), Indexer.Multiple.valueOf(m.toUpperCase())); } String b = childElement.getAttribute("boost"); if (!b.equals("")) { boosts.put(childElement.getAttribute("name"), Float.valueOf(b)); } } else if ("related".equals(childElement.getLocalName())) { subQueries.add( new JdbcIndexDefinition( ds, childElement, allIndexedFields, storeText, mergeText, a, true)); } } } this.analyzer = a; this.isSub = isSub; assert !isSub || "".equals(findSql); }
private static List<String> getParentPublishedInputs(Element parent, String child) { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (Element port : childElementsWithName(parent, "port")) { Attr childRef = port.getAttributeNode("childReference"); if (childRef != null && childRef.getValue().split("\\.")[0].equals(child)) { builder.add(port.getAttribute("name")); } } return builder.build(); }
private static Object xgetAt(Element element, String elementName) { if ("..".equals(elementName)) { return parent(element); } if ("**".equals(elementName)) { return depthFirst(element); } if (elementName.startsWith("@")) { return element.getAttribute(elementName.substring(1)); } return getChildElements(element, elementName); }
private Color getColor(Element shape) { Color color; if (shape.hasAttribute(ATR_COLOUR)) { String s = shape.getAttribute(ATR_COLOUR); if (s.indexOf(',') > -1) { String[] rgb = s.split(","); color = new Color( Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2])); } else { color = new Color(Integer.parseInt(s)); } } else color = IMPLIED_COLOR; if (shape.hasAttribute(ATR_TRANSPARENCY)) { int alpha = Integer.parseInt(shape.getAttribute(ATR_TRANSPARENCY)); if (alpha < 255) return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); } return color; }
private static Vector<Annotation> parseAnnotations(Node parent) throws XmlParserException { Vector<Annotation> annotations = new Vector<Annotation>(); NodeList nodes = parent.getChildNodes(); for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) { Node node = nodes.item(nodeid); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element element = (Element) node; if (element.getTagName().equals("annotation")) { String label = null, value = null, valuetype = null, unit = null; NodeList annotation_nodes = element.getChildNodes(); for (int annotationid = 0; annotationid < annotation_nodes.getLength(); ++annotationid) { Node annotation_node = annotation_nodes.item(annotationid); if (annotation_node.getNodeType() != Node.ELEMENT_NODE) continue; Element annotation_element = (Element) annotation_node; if (annotation_element.getTagName().equals("label")) label = annotation_element.getTextContent(); else if (annotation_element.getTagName().equals("value")) value = annotation_element.getTextContent(); else if (annotation_element.getTagName().equals("valuetype")) valuetype = annotation_element.getTextContent(); } if (label == null || value == null || valuetype == null) throw new XmlParserException("Annotation is missing either: label, value or valuetype"); Annotation annotation = new Annotation(label, value, Annotation.ValueType.valueOf(valuetype)); annotation.setUnit(unit); if (annotation.getValueType() == Annotation.ValueType.ONTOLOGY) annotation.setOntologyRef(element.getAttribute("ontologyref")); if (element.getAttribute("unit") != null) annotation.setUnit(element.getAttribute("unit")); annotations.add(annotation); } } return annotations; }
@Override public void apply(Element e) { if (isNodeWithPrototype(e, nodePrototype)) { String nodeName = e.getAttribute("name"); Element port = portWithName(e, oldPortName); if (port != null) port.setAttribute("name", newPortName); Element parent = (Element) e.getParentNode(); List<Element> connections = childElementsWithName(parent, "conn"); renamePortInNodeList(connections, "input", nodeName, oldPortName, newPortName); List<Element> ports = childElementsWithName(parent, "port"); renamePortInNodeList(ports, "childReference", nodeName, oldPortName, newPortName); } }