List of usage examples for org.w3c.dom Node getNextSibling
public Node getNextSibling();
From source file:com.portfolio.rest.RestServicePortfolio.java
/********************************************************/ @Path("/rights") @POST/*from w w w .j a va 2 s . c o m*/ @Produces(MediaType.APPLICATION_XML) public String postChangeRights(String xmlNode, @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest) { UserInfo ui = checkCredential(httpServletRequest, null, null, null); String returnValue = ""; try { /** * <node uuid=""> * <role name=""> * <right RD="" WR="" DL="" /> * <action>reset</action> * </role> * </node> *====== * <portfolio uuid=""> * <xpath>XPATH</xpath> * <role name=""> * <right RD="" WR="" DL="" /> * <action>reset</action> * </role> * </portfolio> *====== * <portfoliogroup name=""> * <xpath>XPATH</xpath> * <role name=""> * <right RD="" WR="" DL="" /> * <action>reset</action> * </role> * </portfoliogroup> **/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(new ByteArrayInputStream(xmlNode.getBytes("UTF-8"))); XPath xPath = XPathFactory.newInstance().newXPath(); ArrayList<String> portfolio = new ArrayList<String>(); String xpathRole = "/role"; XPathExpression findRole = xPath.compile(xpathRole); String xpathNodeFilter = "/xpath"; XPathExpression findXpath = xPath.compile(xpathNodeFilter); String nodefilter = ""; NodeList roles = null; /// Fetch portfolio(s) String portfolioNode = "//portfoliogroup"; Node portgroupnode = (Node) xPath.compile(portfolioNode).evaluate(doc, XPathConstants.NODE); if (portgroupnode == null) { String portgroupname = portgroupnode.getAttributes().getNamedItem("name").getNodeValue(); // Query portfolio group for list of uuid // while( res.next() ) // portfolio.add(portfolio); Node xpathNode = (Node) findXpath.evaluate(portgroupnode, XPathConstants.NODE); nodefilter = xpathNode.getNodeValue(); roles = (NodeList) findRole.evaluate(portgroupnode, XPathConstants.NODESET); } else { // Or add the single one portfolioNode = "//portfolio[@uuid]"; Node portnode = (Node) xPath.compile(portfolioNode).evaluate(doc, XPathConstants.NODE); portfolio.add(portnode.getNodeValue()); Node xpathNode = (Node) findXpath.evaluate(portnode, XPathConstants.NODE); nodefilter = xpathNode.getNodeValue(); roles = (NodeList) findRole.evaluate(portnode, XPathConstants.NODESET); } ArrayList<String> nodes = new ArrayList<String>(); XPathExpression xpathFilter = xPath.compile(nodefilter); for (int i = 0; i < portfolio.size(); ++i) // For all portfolio { String portfolioUuid = portfolio.get(i); String portfolioStr = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId, 0, this.label, null, null, ui.subId).toString(); Document docPort = documentBuilder.parse(new ByteArrayInputStream(portfolioStr.getBytes("UTF-8"))); /// Fetch nodes inside those portfolios NodeList portNodes = (NodeList) xpathFilter.evaluate(docPort, XPathConstants.NODESET); for (int j = 0; j < portNodes.getLength(); ++j) { Node node = portNodes.item(j); String nodeuuid = node.getAttributes().getNamedItem("id").getNodeValue(); nodes.add(nodeuuid); // Keep those we have to change rights } } /// Fetching single node if (nodes.isEmpty()) { String singleNode = "/node"; Node sNode = (Node) xPath.compile(singleNode).evaluate(doc, XPathConstants.NODE); String uuid = sNode.getAttributes().getNamedItem("uuid").getNodeValue(); nodes.add(uuid); roles = (NodeList) findRole.evaluate(sNode, XPathConstants.NODESET); } /// For all roles we have to change for (int i = 0; i < roles.getLength(); ++i) { Node rolenode = roles.item(i); String rolename = rolenode.getAttributes().getNamedItem("name").getNodeValue(); Node right = rolenode.getFirstChild(); // if ("user".equals(rolename)) { /// username as role } if ("#text".equals(right.getNodeName())) right = right.getNextSibling(); if ("right".equals(right.getNodeName())) // Changing node rights { NamedNodeMap rights = right.getAttributes(); NodeRight noderight = new NodeRight(null, null, null, null, null, null); String val = rights.getNamedItem("RD").getNodeValue(); if (val != null) noderight.read = Boolean.parseBoolean(val); val = rights.getNamedItem("WR").getNodeValue(); if (val != null) noderight.write = Boolean.parseBoolean(val); val = rights.getNamedItem("DL").getNodeValue(); if (val != null) noderight.delete = Boolean.parseBoolean(val); val = rights.getNamedItem("SB").getNodeValue(); if (val != null) noderight.submit = Boolean.parseBoolean(val); /// Apply modification for all nodes for (int j = 0; j < nodes.size(); ++j) { String nodeid = nodes.get(j); // change right dataProvider.postRights(ui.userId, nodeid, rolename, noderight); } } else if ("action".equals(right.getNodeName())) // Using an action on node { /// Apply modification for all nodes for (int j = 0; j < nodes.size(); ++j) { String nodeid = nodes.get(j); // TODO: check for reset keyword // reset right dataProvider.postMacroOnNode(ui.userId, nodeid, "reset"); } } } // returnValue = dataProvider.postRRGCreate(ui.userId, xmlNode); logRestRequest(httpServletRequest, xmlNode, returnValue, Status.OK.getStatusCode()); if (returnValue == "faux") { throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits d'acces"); } return returnValue; } catch (RestWebApplicationException ex) { throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires"); } catch (Exception ex) { ex.printStackTrace(); logRestRequest(httpServletRequest, xmlNode, ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex), Status.INTERNAL_SERVER_ERROR.getStatusCode()); dataProvider.disconnect(); throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } finally { dataProvider.disconnect(); } }
From source file:com.occamlab.te.parsers.ImageParser.java
private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes) throws Exception { HashMap<Object, Object> bandMap = new HashMap<Object, Object>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getLocalName().equals("subimage")) { Element e = (Element) node; int x = Integer.parseInt(e.getAttribute("x")); int y = Integer.parseInt(e.getAttribute("y")); int w = Integer.parseInt(e.getAttribute("width")); int h = Integer.parseInt(e.getAttribute("height")); processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes()); } else if (node.getLocalName().equals("checksum")) { CRC32 checksum = new CRC32(); Raster raster = buffimage.getRaster(); DataBufferByte buffer; if (node.getParentNode().getLocalName().equals("subimage")) { WritableRaster outRaster = raster.createCompatibleWritableRaster(); buffimage.copyData(outRaster); buffer = (DataBufferByte) outRaster.getDataBuffer(); } else { buffer = (DataBufferByte) raster.getDataBuffer(); }//w ww .j av a 2 s . c om int numbanks = buffer.getNumBanks(); for (int j = 0; j < numbanks; j++) { checksum.update(buffer.getData(j)); } Document doc = node.getOwnerDocument(); node.appendChild(doc.createTextNode(Long.toString(checksum.getValue()))); } else if (node.getLocalName().equals("count")) { String band = ((Element) node).getAttribute("bands"); String sample = ((Element) node).getAttribute("sample"); if (sample.equals("all")) { bandMap.put(band, null); } else { HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band); if (sampleMap == null) { if (!bandMap.containsKey(band)) { sampleMap = new HashMap<Object, Object>(); bandMap.put(band, sampleMap); } } sampleMap.put(Integer.decode(sample), new Integer(0)); } } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24 // PwD String transparentNodata = checkTransparentNodata(buffimage, node); node.setTextContent(transparentNodata); } } } Iterator bandIt = bandMap.keySet().iterator(); while (bandIt.hasNext()) { String band_str = (String) bandIt.next(); int band_indexes[]; if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) { band_indexes = new int[1]; band_indexes[0] = 0; } else { band_indexes = new int[band_str.length()]; for (int i = 0; i < band_str.length(); i++) { if (band_str.charAt(i) == 'A') band_indexes[i] = 3; if (band_str.charAt(i) == 'B') band_indexes[i] = 2; if (band_str.charAt(i) == 'G') band_indexes[i] = 1; if (band_str.charAt(i) == 'R') band_indexes[i] = 0; } } Raster raster = buffimage.getRaster(); java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str); boolean addall = (sampleMap == null); if (sampleMap == null) { sampleMap = new java.util.HashMap(); bandMap.put(band_str, sampleMap); } int minx = raster.getMinX(); int maxx = minx + raster.getWidth(); int miny = raster.getMinY(); int maxy = miny + raster.getHeight(); int bands[][] = new int[band_indexes.length][raster.getWidth()]; for (int y = miny; y < maxy; y++) { for (int i = 0; i < band_indexes.length; i++) { raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]); } for (int x = minx; x < maxx; x++) { int sample = 0; for (int i = 0; i < band_indexes.length; i++) { sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8); } Integer sampleObj = new Integer(sample); boolean add = addall; if (!addall) { add = sampleMap.containsKey(sampleObj); } if (add) { Integer count = (Integer) sampleMap.get(sampleObj); if (count == null) { count = new Integer(0); } count = new Integer(count.intValue() + 1); sampleMap.put(sampleObj, count); } } } } Node node = nodes.item(0); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getLocalName().equals("count")) { String band = ((Element) node).getAttribute("bands"); String sample = ((Element) node).getAttribute("sample"); HashMap sampleMap = (HashMap) bandMap.get(band); Document doc = node.getOwnerDocument(); if (sample.equals("all")) { Node parent = node.getParentNode(); Node prevSibling = node.getPreviousSibling(); Iterator sampleIt = sampleMap.keySet().iterator(); Element countnode = null; int digits; String prefix; switch (buffimage.getType()) { case BufferedImage.TYPE_BYTE_BINARY: digits = 1; prefix = ""; break; case BufferedImage.TYPE_BYTE_GRAY: digits = 2; prefix = "0x"; break; default: prefix = "0x"; digits = band.length() * 2; } while (sampleIt.hasNext()) { countnode = doc.createElementNS(node.getNamespaceURI(), "count"); Integer sampleInt = (Integer) sampleIt.next(); Integer count = (Integer) sampleMap.get(sampleInt); if (band.length() > 0) { countnode.setAttribute("bands", band); } countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits)); Node textnode = doc.createTextNode(count.toString()); countnode.appendChild(textnode); parent.insertBefore(countnode, node); if (sampleIt.hasNext()) { if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) { parent.insertBefore(prevSibling.cloneNode(false), node); } } } parent.removeChild(node); node = countnode; } else { Integer count = (Integer) sampleMap.get(Integer.decode(sample)); if (count == null) count = new Integer(0); Node textnode = doc.createTextNode(count.toString()); node.appendChild(textnode); } } } node = node.getNextSibling(); } }
From source file:net.sf.jasperreports.engine.util.JRStyledTextParser.java
/** * *//*from www . ja v a2s . c o m*/ private void parseStyle(JRStyledText styledText, Node parentNode) throws SAXException { NodeList nodeList = parentNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.TEXT_NODE) { styledText.append(node.getNodeValue()); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_style.equals(node.getNodeName())) { NamedNodeMap nodeAttrs = node.getAttributes(); Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); if (nodeAttrs.getNamedItem(ATTRIBUTE_fontName) != null) { styleAttrs.put(TextAttribute.FAMILY, nodeAttrs.getNamedItem(ATTRIBUTE_fontName).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isBold) != null) { styleAttrs.put(TextAttribute.WEIGHT, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isBold).getNodeValue()) ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isItalic) != null) { styleAttrs.put(TextAttribute.POSTURE, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isItalic).getNodeValue()) ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isUnderline) != null) { styleAttrs.put(TextAttribute.UNDERLINE, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isUnderline).getNodeValue()) ? TextAttribute.UNDERLINE_ON : null); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isStrikeThrough) != null) { styleAttrs.put(TextAttribute.STRIKETHROUGH, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isStrikeThrough).getNodeValue()) ? TextAttribute.STRIKETHROUGH_ON : null); } if (nodeAttrs.getNamedItem(ATTRIBUTE_size) != null) { styleAttrs.put(TextAttribute.SIZE, Float.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_size).getNodeValue())); } if (nodeAttrs.getNamedItem(ATTRIBUTE_pdfFontName) != null) { styleAttrs.put(JRTextAttribute.PDF_FONT_NAME, nodeAttrs.getNamedItem(ATTRIBUTE_pdfFontName).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_pdfEncoding) != null) { styleAttrs.put(JRTextAttribute.PDF_ENCODING, nodeAttrs.getNamedItem(ATTRIBUTE_pdfEncoding).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_isPdfEmbedded) != null) { styleAttrs.put(JRTextAttribute.IS_PDF_EMBEDDED, Boolean.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_isPdfEmbedded).getNodeValue())); } if (nodeAttrs.getNamedItem(ATTRIBUTE_forecolor) != null) { Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_forecolor).getNodeValue(), Color.black); styleAttrs.put(TextAttribute.FOREGROUND, color); } if (nodeAttrs.getNamedItem(ATTRIBUTE_backcolor) != null) { Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_backcolor).getNodeValue(), Color.black); styleAttrs.put(TextAttribute.BACKGROUND, color); } int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_bold.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_italic.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_underline.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_sup.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_sub.equalsIgnoreCase(node.getNodeName())) { Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); styleAttrs.put(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB); int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_font.equalsIgnoreCase(node.getNodeName())) { NamedNodeMap nodeAttrs = node.getAttributes(); Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); if (nodeAttrs.getNamedItem(ATTRIBUTE_size) != null) { styleAttrs.put(TextAttribute.SIZE, Float.valueOf(nodeAttrs.getNamedItem(ATTRIBUTE_size).getNodeValue())); } if (nodeAttrs.getNamedItem(ATTRIBUTE_color) != null) { Color color = JRColorUtil.getColor(nodeAttrs.getNamedItem(ATTRIBUTE_color).getNodeValue(), Color.black); styleAttrs.put(TextAttribute.FOREGROUND, color); } if (nodeAttrs.getNamedItem(ATTRIBUTE_fontFace) != null) { String fontFaces = nodeAttrs.getNamedItem(ATTRIBUTE_fontFace).getNodeValue(); StringTokenizer t = new StringTokenizer(fontFaces, ","); while (t.hasMoreTokens()) { String face = t.nextToken().trim(); if (AVAILABLE_FONT_FACE_NAMES.contains(face)) { styleAttrs.put(TextAttribute.FAMILY, face); break; } } } int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_br.equalsIgnoreCase(node.getNodeName())) { styledText.append("\n"); int startIndex = styledText.length(); resizeRuns(styledText.getRuns(), startIndex, 1); parseStyle(styledText, node); styledText.addRun( new JRStyledText.Run(new HashMap<Attribute, Object>(), startIndex, styledText.length())); if (startIndex < styledText.length()) { styledText.append("\n"); resizeRuns(styledText.getRuns(), startIndex, 1); } } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_li.equalsIgnoreCase(node.getNodeName())) { String tmpText = styledText.getText(); if (tmpText.length() > 0 && !tmpText.endsWith("\n")) { styledText.append("\n"); } styledText.append(" \u2022 "); int startIndex = styledText.length(); resizeRuns(styledText.getRuns(), startIndex, 1); parseStyle(styledText, node); styledText.addRun( new JRStyledText.Run(new HashMap<Attribute, Object>(), startIndex, styledText.length())); // if the text in the next node does not start with a '\n', or // if the next node is not a <li /> one, we have to append a new line Node nextNode = node.getNextSibling(); String textContent = getFirstTextOccurence(nextNode); if (nextNode != null && !((nextNode.getNodeType() == Node.ELEMENT_NODE && NODE_li.equalsIgnoreCase(nextNode.getNodeName()) || (textContent != null && textContent.startsWith("\n"))))) { styledText.append("\n"); resizeRuns(styledText.getRuns(), startIndex, 1); } } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_a.equalsIgnoreCase(node.getNodeName())) { if (hyperlink == null) { NamedNodeMap nodeAttrs = node.getAttributes(); Map<Attribute, Object> styleAttrs = new HashMap<Attribute, Object>(); hyperlink = new JRBasePrintHyperlink(); hyperlink.setHyperlinkType(HyperlinkTypeEnum.REFERENCE); styleAttrs.put(JRTextAttribute.HYPERLINK, hyperlink); if (nodeAttrs.getNamedItem(ATTRIBUTE_href) != null) { hyperlink.setHyperlinkReference(nodeAttrs.getNamedItem(ATTRIBUTE_href).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_type) != null) { hyperlink.setLinkType(nodeAttrs.getNamedItem(ATTRIBUTE_type).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_target) != null) { hyperlink.setLinkTarget(nodeAttrs.getNamedItem(ATTRIBUTE_target).getNodeValue()); } int startIndex = styledText.length(); parseStyle(styledText, node); styledText.addRun(new JRStyledText.Run(styleAttrs, startIndex, styledText.length())); hyperlink = null; } else { throw new SAXException("Hyperlink <a> tags cannot be nested."); } } else if (node.getNodeType() == Node.ELEMENT_NODE && NODE_param.equalsIgnoreCase(node.getNodeName())) { if (hyperlink == null) { throw new SAXException("Hyperlink <param> tags must appear inside an <a> tag only."); } else { NamedNodeMap nodeAttrs = node.getAttributes(); JRPrintHyperlinkParameter parameter = new JRPrintHyperlinkParameter(); if (nodeAttrs.getNamedItem(ATTRIBUTE_name) != null) { parameter.setName(nodeAttrs.getNamedItem(ATTRIBUTE_name).getNodeValue()); } if (nodeAttrs.getNamedItem(ATTRIBUTE_valueClass) != null) { parameter.setValueClass(nodeAttrs.getNamedItem(ATTRIBUTE_valueClass).getNodeValue()); } String strValue = node.getTextContent(); if (strValue != null) { Object value = JRValueStringUtils.deserialize(parameter.getValueClass(), strValue); parameter.setValue(value); } hyperlink.addHyperlinkParameter(parameter); } } else if (node.getNodeType() == Node.ELEMENT_NODE) { String nodeName = "<" + node.getNodeName() + ">"; throw new SAXException("Tag " + nodeName + " is not a valid styled text tag."); } } }
From source file:org.exist.xquery.modules.jfreechart.Configuration.java
/** * Read configuration from node and initialize configuration. * @throws XPathException Thrown when an element cannot be read. *///from w w w .ja v a 2s. c om public void parse(Node configuration) throws XPathException { if (configuration.getNodeType() == Node.ELEMENT_NODE && configuration.getLocalName().equals("configuration")) { //Get the First Child Node child = configuration.getFirstChild(); while (child != null) { //Parse each of the child nodes if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { if (child.getLocalName().equals("title")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'title' cannot be parsed"); } else { title = value; } } else if (child.getLocalName().equals("categoryAxisLabel")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'categoryAxisLabel' cannot be parsed"); } else { categoryAxisLabel = value; } } else if (child.getLocalName().equals("categoryAxisColor")) { Color value = Colour.getColor(getValue(child)); if (value == null) { throw new XPathException("Value for 'categoryAxisColor' cannot be parsed"); } else { categoryAxisColor = value; } } else if (child.getLocalName().equals("valueAxisLabel")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'valueAxisLabel' cannot be parsed"); } else { valueAxisLabel = value; } } else if (child.getLocalName().equals("valueAxisColor")) { Color value = Colour.getColor(getValue(child)); if (value == null) { throw new XPathException("Value for 'valueAxisColor' cannot be parsed"); } else { valueAxisColor = value; } } else if (child.getLocalName().equals("timeAxisLabel")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'timeAxisLabel' cannot be parsed"); } else { timeAxisLabel = value; } } else if (child.getLocalName().equals("timeAxisColor")) { Color value = Colour.getColor(getValue(child)); if (value == null) { throw new XPathException("Value for 'timeAxisColor' cannot be parsed"); } else { timeAxisColor = value; } } else if (child.getLocalName().equals("domainAxisLabel")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'domainAxisLabel' cannot be parsed"); } else { domainAxisLabel = value; } } else if (child.getLocalName().equals("rangeAxisLabel")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'rangeAxisLabel' cannot be parsed"); } else { rangeAxisLabel = value; } } else if (child.getLocalName().equals("pieSectionLabel")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'pieSectionLabel' cannot be parsed"); } else { pieSectionLabel = value; } } else if (child.getLocalName().equals("pieSectionNumberFormat")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'pieSectionNumberFormat' cannot be parsed"); } else { pieSectionNumberFormat = value; } } else if (child.getLocalName().equals("pieSectionPercentFormat")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'pieSectionPercentFormat' cannot be parsed"); } else { pieSectionPercentFormat = value; } } else if (child.getLocalName().equals("orientation")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'orientation' cannot be parsed"); } else if ("HORIZONTAL".equalsIgnoreCase(value)) { orientation = PlotOrientation.HORIZONTAL; } else if ("VERTICAL".equalsIgnoreCase(value)) { orientation = PlotOrientation.VERTICAL; } else { throw new XPathException("Wrong value for 'orientation'"); } } else if (child.getLocalName().equals("tableOrder")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'tableOrder' cannot be parsed"); } else if ("COLUMN".equalsIgnoreCase(value)) { order = TableOrder.BY_COLUMN; } else if ("ROW".equalsIgnoreCase(value)) { order = TableOrder.BY_ROW; } else { throw new XPathException("Wrong value for 'tableOrder'"); } } else if (child.getLocalName().equals("legend")) { Boolean value = parseBoolean(getValue(child)); if (value == null) { throw new XPathException("Value for 'legend' cannot be parsed"); } else { generateLegend = value; } } else if (child.getLocalName().equals("tooltips")) { Boolean value = parseBoolean(getValue(child)); if (value == null) { throw new XPathException("Value for 'tooltips' cannot be parsed"); } else { generateTooltips = value; } } else if (child.getLocalName().equals("urls")) { Boolean value = parseBoolean(getValue(child)); if (value == null) { throw new XPathException("Value for 'urls' cannot be parsed"); } else { generateUrls = value; } } else if (child.getLocalName().equals("width")) { Integer value = parseInteger(getValue(child)); if (value == null) { throw new XPathException("Value for 'width' cannot be parsed"); } else { imageWidth = value; } } else if (child.getLocalName().equals("height")) { Integer value = parseInteger(getValue(child)); if (value == null) { throw new XPathException("Value for 'height' cannot be parsed"); } else { imageHeight = value; } } else if (child.getLocalName().equals("titleColor")) { Color value = Colour.getColor(getValue(child)); if (value == null) { throw new XPathException("Value for 'titleColor' cannot be parsed"); } else { titleColor = value; } } else if (child.getLocalName().equals("chartBackgroundColor")) { Color value = Colour.getColor(getValue(child)); if (value == null) { throw new XPathException("Value for 'chartBackgroundColor' cannot be parsed"); } else { chartBackgroundColor = value; } } else if (child.getLocalName().equals("plotBackgroundColor")) { Color value = Colour.getColor(getValue(child)); if (value == null) { throw new XPathException("Value for 'plotBackgroundColor' cannot be parsed"); } else { plotBackgroundColor = value; } } else if (child.getLocalName().equals("seriesColors")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'seriesColors' cannot be parsed"); } else { seriesColors = value; } } else if (child.getLocalName().equals("sectionColors")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'sectionColors' cannot be parsed"); } else { sectionColors = value; } } else if (child.getLocalName().equals("sectionColorsDelimiter")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'sectionColorsDelimiter' cannot be parsed"); } else { sectionColorsDelimiter = value; } } else if (child.getLocalName().equals("rangeLowerBound")) { Double value = parseDouble(getValue(child)); if (value == null) { throw new XPathException("Value for 'rangeLowerBound' cannot be parsed"); } else { rangeLowerBound = value; } } else if (child.getLocalName().equals("rangeUpperBound")) { Double value = parseDouble(getValue(child)); if (value == null) { throw new XPathException("Value for 'rangeUpperBound' cannot be parsed"); } else { rangeUpperBound = value; } } else if (child.getLocalName().equals("categoryItemLabelGeneratorClass")) { String value = getValue(child); if (value == null) { throw new XPathException( "Value for 'categoryItemLabelGeneratorClass' cannot be parsed"); } else { categoryItemLabelGeneratorClass = value; } } else if (child.getLocalName().equals("categoryItemLabelGeneratorParameter")) { String value = getValue(child); if (value == null) { throw new XPathException( "Value for 'categoryItemLabelGeneratorParameter' cannot be parsed"); } else { categoryItemLabelGeneratorParameter = value; } } else if (child.getLocalName().equals("categoryItemLabelGeneratorNumberFormat")) { String value = getValue(child); if (value == null) { throw new XPathException( "Value for 'categoryItemLabelGeneratorNumberFormat' cannot be parsed"); } else { categoryItemLabelGeneratorNumberFormat = value; } } else if (child.getLocalName().equals("imageType")) { String value = getValue(child); if (value == null) { throw new XPathException("Value for 'imageType' cannot be parsed"); } else { imageType = value; } } } //next node child = child.getNextSibling(); } } }
From source file:net.sourceforge.pmd.lang.xml.ast.DOMLineNumbers.java
private int determineLocation(Node n, int index) { int nextIndex = index; if (n.getNodeType() == Node.DOCUMENT_TYPE_NODE) { nextIndex = xmlString.indexOf("<!DOCTYPE", nextIndex); } else if (n.getNodeType() == Node.COMMENT_NODE) { nextIndex = xmlString.indexOf("<!--", nextIndex); } else if (n.getNodeType() == Node.ELEMENT_NODE) { nextIndex = xmlString.indexOf("<" + n.getNodeName(), nextIndex); } else if (n.getNodeType() == Node.CDATA_SECTION_NODE) { nextIndex = xmlString.indexOf("<![CDATA[", nextIndex); } else if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { ProcessingInstruction pi = (ProcessingInstruction) n; nextIndex = xmlString.indexOf("<?" + pi.getTarget(), nextIndex); } else if (n.getNodeType() == Node.TEXT_NODE) { String te = unexpandEntities(n, n.getNodeValue()); int newIndex = xmlString.indexOf(te, nextIndex); if (newIndex > 0) { nextIndex = newIndex;/*from ww w . j a v a 2s . c o m*/ } } else if (n.getNodeType() == Node.ENTITY_REFERENCE_NODE) { nextIndex = xmlString.indexOf("&" + n.getNodeName() + ";", nextIndex); } setBeginLocation(n, nextIndex); if (n.hasChildNodes()) { NodeList childs = n.getChildNodes(); for (int i = 0; i < childs.getLength(); i++) { nextIndex = determineLocation(childs.item(i), nextIndex); } } if (n.getNodeType() == Node.ELEMENT_NODE) { nextIndex += 2 + n.getNodeName().length() + 1; // </nodename> } else if (n.getNodeType() == Node.DOCUMENT_TYPE_NODE) { Node nextSibling = n.getNextSibling(); if (nextSibling.getNodeType() == Node.ELEMENT_NODE) { nextIndex = xmlString.indexOf("<" + nextSibling.getNodeName(), nextIndex) - 1; } else if (nextSibling.getNodeType() == Node.COMMENT_NODE) { nextIndex = xmlString.indexOf("<!--", nextIndex); } else { nextIndex = xmlString.indexOf(">", nextIndex); } } else if (n.getNodeType() == Node.COMMENT_NODE) { nextIndex += 4 + 3; // <!-- and --> nextIndex += n.getNodeValue().length(); } else if (n.getNodeType() == Node.TEXT_NODE) { String te = unexpandEntities(n, n.getNodeValue()); nextIndex += te.length(); } else if (n.getNodeType() == Node.CDATA_SECTION_NODE) { nextIndex += "<![CDATA[".length() + n.getNodeValue().length() + "]]>".length(); } else if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { ProcessingInstruction pi = (ProcessingInstruction) n; nextIndex += "<?".length() + pi.getTarget().length() + "?>".length() + pi.getData().length(); } setEndLocation(n, nextIndex - 1); return nextIndex; }
From source file:org.adeptnet.auth.saml.SAMLClient.java
private Element[] selectNodes(final Node _sibling, final String uri, final String nodeName) { final List<Element> list = new ArrayList<>(); Node sibling = _sibling; while (sibling != null) { if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri) && sibling.getLocalName().equals(nodeName)) { list.add((Element) sibling); }/*from ww w.j a v a 2s . c o m*/ sibling = sibling.getNextSibling(); } return list.toArray(new Element[list.size()]); }
From source file:org.adeptnet.auth.saml.SAMLClient.java
private void initMap() { if (!map.isEmpty()) { return;/*from w ww . j av a 2s . c o m*/ } final InputStream is = org.apache.xml.security.Init.class.getResourceAsStream("resource/config.xml"); if (is == null) { LOG.error("cannot read resource/config.xml"); return; } try { /* read library configuration file */ final DocumentBuilder db = createDocumentBuilder(false, true); final Document doc = db.parse(is); Node node = doc.getFirstChild(); for (; node != null; node = node.getNextSibling()) { if ("Configuration".equals(node.getLocalName())) { break; } } if (node == null) { LOG.error("Error in reading configuration file - Configuration element not found"); return; } for (Node el = node.getFirstChild(); el != null; el = el.getNextSibling()) { if (Node.ELEMENT_NODE != el.getNodeType()) { continue; } if (!"JCEAlgorithmMappings".equals(el.getLocalName())) { continue; } final Node algorithmsNode = ((Element) el).getElementsByTagName("Algorithms").item(0); if (algorithmsNode == null) { continue; } final Element[] algorithms = selectNodes(algorithmsNode.getFirstChild(), Init.CONF_NS, "Algorithm"); for (final Element element : algorithms) { final String algoClass = element.getAttributeNS(null, "AlgorithmClass"); if (!"Signature".equals(algoClass)) { continue; } final String uri = element.getAttributeNS(null, "URI"); final String name = element.getAttributeNS(null, "JCEName"); map.put(name, uri); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Mapping %s - %s", name, uri)); } } } } catch (ParserConfigurationException | SAXException | IOException | DOMException ex) { LOG.error(ex.getMessage(), ex); } }
From source file:org.alfresco.repo.web.scripts.bean.ADMRemoteStore.java
/** * Creates multiple XML documents encapsulated in a single one. * //from w ww .ja v a2 s .c o m * @param res WebScriptResponse * @param store String * @param in XML document containing multiple document contents to write */ @Override protected void createDocuments(WebScriptResponse res, String store, InputStream in) { try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document; document = documentBuilder.parse(in); Element docEl = document.getDocumentElement(); Transformer transformer = ADMRemoteStore.this.transformer.get(); for (Node n = docEl.getFirstChild(); n != null; n = n.getNextSibling()) { if (!(n instanceof Element)) { continue; } final String path = ((Element) n).getAttribute("path"); // Turn the first element child into a document Document doc = documentBuilder.newDocument(); Node child; for (child = n.getFirstChild(); child != null; child = child.getNextSibling()) { if (child instanceof Element) { doc.appendChild(doc.importNode(child, true)); break; } } ByteArrayOutputStream out = new ByteArrayOutputStream(512); transformer.transform(new DOMSource(doc), new StreamResult(out)); out.close(); writeDocument(path, new ByteArrayInputStream(out.toByteArray())); } } catch (AccessDeniedException ae) { res.setStatus(Status.STATUS_UNAUTHORIZED); throw ae; } catch (FileExistsException feeErr) { res.setStatus(Status.STATUS_CONFLICT); throw feeErr; } catch (Exception e) { // various annoying checked SAX/IO exceptions related to XML processing can be thrown // none of them should occur if the XML document is well formed logger.error(e); res.setStatus(Status.STATUS_INTERNAL_SERVER_ERROR); throw new AlfrescoRuntimeException(e.getMessage(), e); } }
From source file:org.apache.axis.handlers.MD5AttachHandler.java
public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: MD5AttachHandler::invoke"); try {/*w w w. j a va 2s . c o m*/ // log.debug("IN MD5"); Message msg = msgContext.getRequestMessage(); SOAPConstants soapConstants = msgContext.getSOAPConstants(); org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope(); org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody();//env.getBodyByName("ns1", "addedfile"); org.w3c.dom.Element sbElement = sbe.getAsDOM(); //get the first level accessor ie parameter org.w3c.dom.Node n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n; //Get the href associated with the attachment. String href = paramElement.getAttribute(soapConstants.getAttrHref()); org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils .getActivationDataHandler(ap); org.w3c.dom.Node timeNode = paramElement.getFirstChild(); long startTime = -1; if (timeNode != null && timeNode instanceof org.w3c.dom.Text) { String startTimeStr = ((org.w3c.dom.Text) timeNode).getData(); startTime = Long.parseLong(startTimeStr); } // log.debug("GOTIT"); long receivedTime = System.currentTimeMillis(); long elapsedTime = -1; // log.debug("startTime=" + startTime); // log.debug("receivedTime=" + receivedTime); if (startTime > 0) elapsedTime = receivedTime - startTime; String elapsedTimeStr = elapsedTime + ""; // log.debug("elapsedTimeStr=" + elapsedTimeStr); java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); java.io.InputStream attachmentStream = dh.getInputStream(); int bread = 0; byte[] buf = new byte[64 * 1024]; do { bread = attachmentStream.read(buf); if (bread > 0) { md.update(buf, 0, bread); } } while (bread > -1); attachmentStream.close(); buf = null; //Add the mime type to the digest. String contentType = dh.getContentType(); if (contentType != null && contentType.length() != 0) { md.update(contentType.getBytes("US-ASCII")); } sbe = env.getFirstBody(); sbElement = sbe.getAsDOM(); //get the first level accessor ie parameter n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; paramElement = (org.w3c.dom.Element) n; // paramElement.setAttribute(soapConstants.getAttrHref(), respHref); String MD5String = org.apache.axis.encoding.Base64.encode(md.digest()); String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String; // log.debug("senddata=" + senddata); paramElement.appendChild(paramElement.getOwnerDocument().createTextNode(senddata)); sbe = new org.apache.axis.message.SOAPBodyElement(sbElement); env.clearBody(); env.addBodyElement(sbe); msg = new Message(env); msgContext.setResponseMessage(msg); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); throw AxisFault.makeFault(e); } log.debug("Exit: MD5AttachHandler::invoke"); }
From source file:org.apache.cocoon.util.jxpath.DOMFactory.java
private void addDOMElement(Node parent, int index, String tag) { int pos = tag.indexOf(':'); String prefix = null;/*w w w. java 2 s . co m*/ if (pos != -1) { prefix = tag.substring(0, pos); } String uri = null; Node child = parent.getFirstChild(); int count = 0; while (child != null) { if (child.getNodeName().equals(tag)) { count++; } child = child.getNextSibling(); } Document doc = parent.getOwnerDocument(); if (doc != null) { uri = getNamespaceURI((Element) parent, prefix); } else { if (parent instanceof Document) { doc = (Document) parent; if (prefix != null) { throw new RuntimeException("Cannot map non-null prefix " + "when creating a document element"); } } else { // Shouldn't happen (must be a DocumentType object) throw new RuntimeException("Node of class " + parent.getClass().getName() + " has null owner document " + "but is not a Document"); } } // Keep inserting new elements until we have index + 1 of them while (count <= index) { Node newElement = doc.createElementNS(uri, tag); parent.appendChild(newElement); count++; } }