List of usage examples for org.w3c.dom NamedNodeMap getNamedItem
public Node getNamedItem(String name);
From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java
private Security loadSecurity(NodeList node) { Security security = new Security( new Integer(Integer.parseInt(((Node) node).getAttributes().getNamedItem("id").getNodeValue()))); //$NON-NLS-1$ for (int i = 0; i < node.getLength(); i++) { Node item = node.item(i); String nodeName = item.getNodeName(); Node value = item.getFirstChild(); if (value != null) { if (nodeName.equals("code")) //$NON-NLS-1$ security.setCode(value.getNodeValue()); else if (nodeName.equals("description")) //$NON-NLS-1$ security.setDescription(value.getNodeValue()); else if (nodeName.equals("currency")) //$NON-NLS-1$ security.setCurrency(Currency.getInstance(value.getNodeValue())); else if (nodeName.equals("comment")) //$NON-NLS-1$ security.setComment(value.getNodeValue()); }//from w ww. j a va 2s .c om if (nodeName.equals("dataCollector")) //$NON-NLS-1$ { security.setEnableDataCollector( new Boolean(((Node) item).getAttributes().getNamedItem("enable").getNodeValue()) //$NON-NLS-1$ .booleanValue()); NodeList nodeList = item.getChildNodes(); for (int q = 0; q < nodeList.getLength(); q++) { item = nodeList.item(q); nodeName = item.getNodeName(); value = item.getFirstChild(); if (nodeName.equals("begin")) //$NON-NLS-1$ { String[] s = value.getNodeValue().split(":"); //$NON-NLS-1$ security.setBeginTime(Integer.parseInt(s[0]) * 60 + Integer.parseInt(s[1])); } else if (nodeName.equals("end")) //$NON-NLS-1$ { String[] s = value.getNodeValue().split(":"); //$NON-NLS-1$ security.setEndTime(Integer.parseInt(s[0]) * 60 + Integer.parseInt(s[1])); } else if (nodeName.equals("weekdays")) //$NON-NLS-1$ security.setWeekDays(Integer.parseInt(value.getNodeValue())); else if (nodeName.equals("keepdays")) //$NON-NLS-1$ security.setKeepDays(Integer.parseInt(value.getNodeValue())); } } else if (nodeName.equalsIgnoreCase("feeds")) //$NON-NLS-1$ { NodeList nodeList = item.getChildNodes(); for (int q = 0; q < nodeList.getLength(); q++) { item = nodeList.item(q); nodeName = item.getNodeName(); value = item.getFirstChild(); if (nodeName.equals("quote")) //$NON-NLS-1$ { FeedSource feed = new FeedSource(); feed.setId(item.getAttributes().getNamedItem("id").getNodeValue()); //$NON-NLS-1$ Node attribute = item.getAttributes().getNamedItem("exchange"); //$NON-NLS-1$ if (attribute != null) feed.setExchange(attribute.getNodeValue()); if (value != null) feed.setSymbol(value.getNodeValue()); security.setQuoteFeed(feed); } else if (nodeName.equals("level2")) //$NON-NLS-1$ { FeedSource feed = new FeedSource(); feed.setId(item.getAttributes().getNamedItem("id").getNodeValue()); //$NON-NLS-1$ Node attribute = item.getAttributes().getNamedItem("exchange"); //$NON-NLS-1$ if (attribute != null) feed.setExchange(attribute.getNodeValue()); if (value != null) feed.setSymbol(value.getNodeValue()); security.setLevel2Feed(feed); } else if (nodeName.equals("history")) //$NON-NLS-1$ { FeedSource feed = new FeedSource(); feed.setId(item.getAttributes().getNamedItem("id").getNodeValue()); //$NON-NLS-1$ Node attribute = item.getAttributes().getNamedItem("exchange"); //$NON-NLS-1$ if (attribute != null) feed.setExchange(attribute.getNodeValue()); if (value != null) feed.setSymbol(value.getNodeValue()); security.setHistoryFeed(feed); } } } else if (nodeName.equalsIgnoreCase("tradeSource")) //$NON-NLS-1$ { TradeSource source = new TradeSource(); source.setTradingProviderId(item.getAttributes().getNamedItem("id").getNodeValue()); //$NON-NLS-1$ Node attribute = item.getAttributes().getNamedItem("exchange"); //$NON-NLS-1$ if (attribute != null) source.setExchange(attribute.getNodeValue()); NodeList quoteList = item.getChildNodes(); for (int q = 0; q < quoteList.getLength(); q++) { item = quoteList.item(q); nodeName = item.getNodeName(); value = item.getFirstChild(); if (value != null) { if (nodeName.equalsIgnoreCase("symbol")) //$NON-NLS-1$ source.setSymbol(value.getNodeValue()); else if (nodeName.equalsIgnoreCase("account")) //$NON-NLS-1$ source.setAccountId(new Integer(value.getNodeValue())); else if (nodeName.equalsIgnoreCase("quantity")) //$NON-NLS-1$ source.setQuantity(Integer.parseInt(value.getNodeValue())); } } security.setTradeSource(source); } else if (nodeName.equalsIgnoreCase("quote")) //$NON-NLS-1$ { Quote quote = new Quote(); NodeList quoteList = item.getChildNodes(); for (int q = 0; q < quoteList.getLength(); q++) { item = quoteList.item(q); nodeName = item.getNodeName(); value = item.getFirstChild(); if (value != null) { if (nodeName.equalsIgnoreCase("date")) //$NON-NLS-1$ { try { quote.setDate(dateTimeFormat.parse(value.getNodeValue())); } catch (Exception e) { log.warn(e.toString()); } } else if (nodeName.equalsIgnoreCase("last")) //$NON-NLS-1$ quote.setLast(Double.parseDouble(value.getNodeValue())); else if (nodeName.equalsIgnoreCase("bid")) //$NON-NLS-1$ quote.setBid(Double.parseDouble(value.getNodeValue())); else if (nodeName.equalsIgnoreCase("ask")) //$NON-NLS-1$ quote.setAsk(Double.parseDouble(value.getNodeValue())); else if (nodeName.equalsIgnoreCase("bidSize")) //$NON-NLS-1$ quote.setBidSize(Integer.parseInt(value.getNodeValue())); else if (nodeName.equalsIgnoreCase("askSize")) //$NON-NLS-1$ quote.setAskSize(Integer.parseInt(value.getNodeValue())); else if (nodeName.equalsIgnoreCase("volume")) //$NON-NLS-1$ quote.setVolume(Integer.parseInt(value.getNodeValue())); } } security.setQuote(quote); } else if (nodeName.equalsIgnoreCase("data")) //$NON-NLS-1$ { NodeList dataList = item.getChildNodes(); for (int q = 0; q < dataList.getLength(); q++) { item = dataList.item(q); nodeName = item.getNodeName(); value = item.getFirstChild(); if (value != null) { if (nodeName.equalsIgnoreCase("open")) //$NON-NLS-1$ security.setOpen(new Double(Double.parseDouble(value.getNodeValue()))); else if (nodeName.equalsIgnoreCase("high")) //$NON-NLS-1$ security.setHigh(new Double(Double.parseDouble(value.getNodeValue()))); else if (nodeName.equalsIgnoreCase("low")) //$NON-NLS-1$ security.setLow(new Double(Double.parseDouble(value.getNodeValue()))); else if (nodeName.equalsIgnoreCase("close")) //$NON-NLS-1$ security.setClose(new Double(Double.parseDouble(value.getNodeValue()))); } } } else if (nodeName.equalsIgnoreCase("split")) //$NON-NLS-1$ { NamedNodeMap attributes = item.getAttributes(); Split split = new Split(); try { split.setDate(dateTimeFormat.parse(attributes.getNamedItem("date").getNodeValue())); //$NON-NLS-1$ split.setFromQuantity(Integer.parseInt(attributes.getNamedItem("fromQuantity").getNodeValue())); //$NON-NLS-1$ split.setToQuantity(Integer.parseInt(attributes.getNamedItem("toQuantity").getNodeValue())); //$NON-NLS-1$ security.getSplits().add(split); } catch (Exception e) { log.error(e.toString()); } } else if (nodeName.equalsIgnoreCase("dividend")) //$NON-NLS-1$ { NamedNodeMap attributes = item.getAttributes(); Dividend dividend = new Dividend(); try { dividend.setDate(dateTimeFormat.parse(attributes.getNamedItem("date").getNodeValue())); //$NON-NLS-1$ dividend.setValue( new Double(Double.parseDouble(attributes.getNamedItem("value").getNodeValue())) //$NON-NLS-1$ .doubleValue()); security.getDividends().add(dividend); } catch (Exception e) { log.error(e.toString()); } } } security.clearChanged(); security.getQuoteMonitor().clearChanged(); security.getLevel2Monitor().clearChanged(); securitiesMap.put(security.getId(), security); return security; }
From source file:com.ephesoft.dcma.batch.service.BatchSchemaServiceImpl.java
/** * Method extracted to be reused for Ephesoft Web Services. * //from ww w.j a v a 2s. co m * @param actualFolderLocation * @param outputFilePath * @param pageID * @param pathOfHOCRFile * @param hocrPage * @return FileInputStream * @throws IOException * @throws TransformerException * @throws XPathExpressionException * @throws SAXException * @throws ParserConfigurationException */ private FileInputStream hocrGenerationInternal(final String actualFolderLocation, final String outputFilePath, final String pageID, final String pathOfHOCRFile, final HocrPage hocrPage) throws XPathExpressionException, TransformerException, IOException, ParserConfigurationException, SAXException { XMLUtil.htmlOutputStream(pathOfHOCRFile, outputFilePath); OCREngineUtil.formatHOCRForTesseract(outputFilePath, actualFolderLocation, pageID); final FileInputStream inputStream = new FileInputStream(outputFilePath); final org.w3c.dom.Document doc = XMLUtil.createDocumentFrom(inputStream); final NodeList titleNodeList = doc.getElementsByTagName(BatchConstants.TITLE); if (null != titleNodeList) { for (int index = 0; index < titleNodeList.getLength(); index++) { final Node node = titleNodeList.item(index); final NodeList childNodeList = node.getChildNodes(); final Node nodeChild = childNodeList.item(BatchConstants.ZERO); if (null != nodeChild) { final String value = nodeChild.getNodeValue(); if (value != null) { hocrPage.setTitle(value); break; } } } } final NodeList spanNodeList = doc.getElementsByTagName("span"); final Spans spans = new Spans(); hocrPage.setSpans(spans); final List<Span> spanList = spans.getSpan(); if (null != spanNodeList) { final StringBuilder hocrContent = new StringBuilder(); for (int index = BatchConstants.ZERO; index < spanNodeList.getLength(); index++) { final Node node = spanNodeList.item(index); final NodeList childNodeList = node.getChildNodes(); final Node nodeChild = childNodeList.item(BatchConstants.ZERO); final Span span = new Span(); if (null != nodeChild) { final String value = nodeChild.getNodeValue(); span.setValue(value); hocrContent.append(value); hocrContent.append(BatchConstants.SPACE); } spanList.add(span); final NamedNodeMap map = node.getAttributes(); final Node nMap = map.getNamedItem(BatchConstants.TITLE); Coordinates hocrCoordinates = null; hocrCoordinates = getHOCRCoordinates(nMap, hocrCoordinates); if (null == hocrCoordinates) { hocrCoordinates = new Coordinates(); hocrCoordinates.setX0(BigInteger.ZERO); hocrCoordinates.setX1(BigInteger.ZERO); hocrCoordinates.setY0(BigInteger.ZERO); hocrCoordinates.setY1(BigInteger.ZERO); } span.setCoordinates(hocrCoordinates); } hocrPage.setHocrContent(hocrContent.toString()); } return inputStream; }
From source file:com.ephesoft.dcma.batch.service.BatchSchemaServiceImpl.java
/** * This API is used to generate the HocrPage object for input hocr file. * //from w w w . j a v a 2 s . c o m * @param pageName {@link String} * @param pathOfHOCRFile {@link String} * @param outputFilePath {@link String} * @param batchClassIdentifier {@link String} * @param ocrEngineName {@link String} * @return {@link HocrPage} */ @Override public HocrPage generateHocrPage(final String pageName, final String pathOfHOCRFile, final String outputFilePath, final String batchClassIdentifier, final String ocrEngineName) { if (null == pathOfHOCRFile || null == outputFilePath) { return null; } final BatchPluginConfiguration[] pluginConfiguration = batchClassPluginPropertiesService .getPluginProperties(batchClassIdentifier, TESSERACT_HOCR_PLUGIN, TesseractVersionProperty.TESSERACT_VERSIONS); String tesseractVersion = BatchConstants.EMPTY; if (pluginConfiguration != null && pluginConfiguration.length > BatchConstants.ZERO && pluginConfiguration[BatchConstants.ZERO].getValue() != null && pluginConfiguration[BatchConstants.ZERO].getValue().length() > BatchConstants.ZERO) { tesseractVersion = pluginConfiguration[BatchConstants.ZERO].getValue(); } final HocrPage hocrPage = new HocrPage(); hocrPage.setPageID(pageName); FileInputStream inputStream = null; try { if (ocrEngineName.equalsIgnoreCase(IUtilCommonConstants.TESSERACT_HOCR_PLUGIN) && tesseractVersion .equalsIgnoreCase(TesseractVersionProperty.TESSERACT_VERSION_3.getPropertyKey())) { XMLUtil.htmlOutputStream(pathOfHOCRFile, outputFilePath); final String actualFolderLocation = new File(outputFilePath).getParent(); OCREngineUtil.formatHOCRForTesseract(outputFilePath, actualFolderLocation, pageName); } else { XMLUtil.htmlOutputStream(pathOfHOCRFile, outputFilePath); } inputStream = new FileInputStream(outputFilePath); final org.w3c.dom.Document doc = XMLUtil.createDocumentFrom(inputStream); final NodeList titleNodeList = doc.getElementsByTagName(BatchConstants.TITLE); if (null != titleNodeList) { for (int index = BatchConstants.ZERO; index < titleNodeList.getLength(); index++) { final Node node = titleNodeList.item(index); final NodeList childNodeList = node.getChildNodes(); final Node nodeChild = childNodeList.item(BatchConstants.ZERO); if (null != nodeChild) { final String value = nodeChild.getNodeValue(); if (value != null) { hocrPage.setTitle(value); break; } } } } final NodeList spanNodeList = doc.getElementsByTagName("span"); final Spans spans = new Spans(); hocrPage.setSpans(spans); final List<Span> spanList = spans.getSpan(); if (null != spanNodeList) { final StringBuilder hocrContent = new StringBuilder(); for (int index = 0; index < spanNodeList.getLength(); index++) { final Node node = spanNodeList.item(index); final NodeList childNodeList = node.getChildNodes(); final Node nodeChild = childNodeList.item(BatchConstants.ZERO); final Span span = new Span(); if (null != nodeChild) { final String value = nodeChild.getNodeValue(); span.setValue(value); hocrContent.append(value); hocrContent.append(BatchConstants.SPACE); } spanList.add(span); final NamedNodeMap map = node.getAttributes(); final Node nMap = map.getNamedItem(BatchConstants.TITLE); Coordinates hocrCoordinates = null; hocrCoordinates = getHOCRCoordinates(nMap, hocrCoordinates); if (null == hocrCoordinates) { hocrCoordinates = new Coordinates(); hocrCoordinates.setX0(BigInteger.ZERO); hocrCoordinates.setX1(BigInteger.ZERO); hocrCoordinates.setY0(BigInteger.ZERO); hocrCoordinates.setY1(BigInteger.ZERO); } span.setCoordinates(hocrCoordinates); } hocrPage.setHocrContent(hocrContent.toString()); } } catch (final IOException e) { LOGGER.error(e.getMessage(), e); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(inputStream); } return hocrPage; }
From source file:com.portfolio.rest.RestServicePortfolio.java
@Path("/nodes/node/{node-id}/rights") @POST/* ww w . j av a2 s . c o m*/ @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Consumes(MediaType.APPLICATION_XML) public String postNodeRights(String xmlNode, @CookieParam("user") String user, @CookieParam("credential") String token, @QueryParam("group") int groupId, @PathParam("node-id") String nodeUuid, @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest, @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId) { UserInfo ui = checkCredential(httpServletRequest, user, token, null); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(new ByteArrayInputStream(xmlNode.getBytes("UTF-8"))); XPath xPath = XPathFactory.newInstance().newXPath(); String xpathRole = "//role"; XPathExpression findRole = xPath.compile(xpathRole); NodeList roles = (NodeList) findRole.evaluate(doc, 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 = "Y".equals(val) ? true : false; val = rights.getNamedItem("WR").getNodeValue(); if (val != null) noderight.write = "Y".equals(val) ? true : false; val = rights.getNamedItem("DL").getNodeValue(); if (val != null) noderight.delete = "Y".equals(val) ? true : false; val = rights.getNamedItem("SB").getNodeValue(); if (val != null) noderight.submit = "Y".equals(val) ? true : false; // change right dataProvider.postRights(ui.userId, nodeUuid, rolename, noderight); } else if ("action".equals(right.getNodeName())) // Using an action on node { // reset right dataProvider.postMacroOnNode(ui.userId, nodeUuid, "reset"); } } // returnValue = dataProvider.postRRGCreate(ui.userId, xmlNode); logRestRequest(httpServletRequest, xmlNode, "Change rights", Status.OK.getStatusCode()); } catch (RestWebApplicationException ex) { throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString()); } catch (NullPointerException ex) { logRestRequest(httpServletRequest, null, null, Status.NOT_FOUND.getStatusCode()); throw new RestWebApplicationException(Status.NOT_FOUND, "Node " + nodeUuid + " not found"); } catch (Exception ex) { ex.printStackTrace(); logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex), Status.INTERNAL_SERVER_ERROR.getStatusCode()); throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } finally { dataProvider.disconnect(); } return ""; }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Gets the last modification date from the Resource. * //w w w . j av a 2 s. c o m * @param resource * The Resource. * @return last-modification-date * @throws Exception * Thrown if anything fails. */ public String getTheLastModificationDate(final Document resource) throws Exception { // get last-modification-date NamedNodeMap atts = resource.getDocumentElement().getAttributes(); Node lastModificationDateNode = atts.getNamedItem("last-modification-date"); return (lastModificationDateNode.getNodeValue()); }
From source file:de.escidoc.core.test.EscidocTestBase.java
public void assertRdfList(final Document xmlDoc, final String objectTypeUri, final String orderByPropertyUri, final boolean descending, final int limit, final int offset) throws Exception { selectSingleNodeAsserted(xmlDoc, "/RDF"); selectSingleNodeAsserted(xmlDoc, "/RDF/Description"); NodeList descriptions = selectNodeList(xmlDoc, "/RDF/Description"); if (limit != 0) { assertOrderNotAfter(descriptions.getLength(), limit); }//from w ww. ja v a 2 s . co m for (int i = 0; i < descriptions.getLength(); i++) { NodeList nl = selectNodeList(descriptions.item(i), "type"); boolean foundTypeObjectTypeUri = false; for (int j = 0; j < nl.getLength(); j++) { Node n = nl.item(j); NamedNodeMap nnm = n.getAttributes(); Node att = nnm.getNamedItem("rdf:resource"); String uri = att.getNodeValue(); if (uri.equals(objectTypeUri)) { foundTypeObjectTypeUri = true; } } if (!foundTypeObjectTypeUri) { String about = selectSingleNode(descriptions.item(i), "@about").getNodeValue(); fail("Could not find type element refering " + objectTypeUri + " in RDF description of " + about + "."); } } if (orderByPropertyUri != null) { String localName = orderByPropertyUri.substring(orderByPropertyUri.lastIndexOf('/') + 1); Node orderNodeA = null; Node orderNodeB = null; // init order node A NodeList nl = selectNodeList(descriptions.item(0), localName); for (int j = 0; j < nl.getLength(); j++) { // FIXME compare with namespace orderNodeA = nl.item(j); } for (int i = 1; i < descriptions.getLength(); i++) { nl = selectNodeList(descriptions.item(i), localName); for (int j = 0; j < nl.getLength(); j++) { // FIXME compare with namespace // String curNsUri = nl.item(j).getNamespaceURI(); // if (nsUri.equals(curNsUri)) { orderNodeB = nl.item(j); // } } if (descending) { assertOrderNotAfter(orderNodeB.getTextContent(), orderNodeA.getTextContent()); } else { assertOrderNotAfter(orderNodeA.getTextContent(), orderNodeB.getTextContent()); } orderNodeA = orderNodeB; } } else { String orderValueXPath = "@about"; // "/Description/" // + orderByPropertyUri.substring(orderByPropertyUri // .lastIndexOf('/') + 1); for (int i = 1; i < descriptions.getLength(); i++) { int a, b; if (descending) { a = i; b = i - 1; } else { a = i - 1; b = i; } String lower = selectSingleNodeAsserted(descriptions.item(a), orderValueXPath).getNodeValue(); String higher = selectSingleNodeAsserted(descriptions.item(b), orderValueXPath).getNodeValue(); assertOrderNotAfter(lower, higher); } } }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Gets the objid attribute of the element selected in the provided node.<br> * It tries to get the objid attribute of the selected node. If this fails, it tries to get the xlink:href * attribute. If both fails, an assertion exception is "thrown". * /*from w w w . j av a 2 s .co m*/ * @param node * The node to select an element from. * @param xPath * The xpath to select the element in the provided node. * @return Returns the attribute value. * @throws Exception * If anything fails. */ public String getObjidValue(final Node node, final String xPath) throws Exception { Node selected = selectSingleNode(node, xPath); assertNotNull("No Element selected to retrieve the object id from", selected); NamedNodeMap attributes = selected.getAttributes(); assertNotNull("Selected node has no attributes (not an element?) ", attributes); Node objidAttr = attributes.getNamedItem(NAME_OBJID); if (objidAttr != null) { return objidAttr.getTextContent(); } else { objidAttr = selectSingleNode(selected, "." + PART_XLINK_HREF); assertNotNull("Selected node neither has an objid " + "attribute nor an xlink href attribute", objidAttr); return getObjidFromHref(objidAttr.getTextContent()); } }
From source file:com.portfolio.rest.RestServicePortfolio.java
/********************************************************/ @Path("/rights") @POST//from ww w . ja v a 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:de.escidoc.core.test.EscidocTestBase.java
/** * Assert XML content is equal.<br/> * <p/>//w w w . j a v a 2 s. c om * This methods compares the attributes (if any exist) and either recursively compares the child elements (if any * exists) or the text content.<br/> * Therefore, mixed content is NOT supported by this method. * * @param messageIn * The message printed if assertion fails. * @param expected * The expected XML content. * @param toBeAsserted * The XML content to be compared with the expected content. * @throws Exception * If anything fails. */ public static void assertXmlEquals(final String messageIn, final Node expected, final Node toBeAsserted) throws Exception { // Assert both nodes are null or both nodes are not null if (expected == null) { assertNull(messageIn + "Unexpected node. ", toBeAsserted); return; } assertNotNull(messageIn + " Expected node. ", toBeAsserted); if (expected.equals(toBeAsserted)) { return; } String nodeName = getLocalName(expected); String message = messageIn; if (!message.contains("-- Asserting ")) { message = message + "-- Asserting " + nodeName + ". "; } else { message = message + "/" + nodeName; } // assert both nodes are nodes of the same node type // if thedocument container xslt directive than is the nodeName // "#document" is here compared assertEquals(message + " Type of nodes are different", expected.getNodeType(), toBeAsserted.getNodeType()); if (expected.getNodeType() == Node.TEXT_NODE) { assertEquals(message + " Text nodes are different. ", expected.getTextContent().trim(), toBeAsserted.getTextContent().trim()); } // assert attributes NamedNodeMap expectedAttributes = expected.getAttributes(); NamedNodeMap toBeAssertedAttributes = toBeAsserted.getAttributes(); if (expectedAttributes == null) { assertNull(message + " Unexpected attributes. [" + nodeName + "]", toBeAssertedAttributes); } else { assertNotNull(message + " Expected attributes. ", toBeAssertedAttributes); final int expectedNumberAttributes = expectedAttributes.getLength(); for (int i = 0; i < expectedNumberAttributes; i++) { Node expectedAttribute = expectedAttributes.item(i); String expectedAttributeNamespace = expectedAttribute.getNamespaceURI(); Node toBeAssertedAttribute = null; if (expectedAttributeNamespace != null) { final String localName = expectedAttribute.getLocalName(); toBeAssertedAttribute = toBeAssertedAttributes.getNamedItemNS(expectedAttributeNamespace, localName); assertNotNull(message + " Expected attribute " + expectedAttribute.getNodeName(), toBeAssertedAttribute); } else { // not namespace aware parsed. Attributes may have different // prefixes which are now part of their node name. // To compare expected and to be asserted attribute, it is // first it is tried to find the appropriate to be asserted // attribute by the node name. If this fails, xpath // selection is used after extracting the expected // attribute name final String expectedAttributeNodeName = expectedAttribute.getNodeName(); toBeAssertedAttribute = toBeAssertedAttributes.getNamedItem(expectedAttributeNodeName); if (toBeAssertedAttribute == null) { final String attributeName = getLocalName(expectedAttribute); final String attributeXpath = "@" + attributeName; toBeAssertedAttribute = selectSingleNode(toBeAsserted, attributeXpath); } assertNotNull(message + " Expected attribute " + expectedAttributeNodeName, toBeAssertedAttribute); } assertEquals(message + " Attribute value mismatch [" + expectedAttribute.getNodeName() + "] ", expectedAttribute.getTextContent(), toBeAssertedAttribute.getTextContent()); } } // As mixed content (text + child elements) is not supported, // either the child elements or the text content have to be asserted. // Therefore, it is first tried to assert the children. // After that it is checked if children have been found. If this is not // the case, the text content is compared. NodeList expectedChildren = expected.getChildNodes(); NodeList toBeAssertedChildren = toBeAsserted.getChildNodes(); int expectedNumberElementNodes = 0; int toBeAssertedNumberElementNodes = 0; List<Node> previouslyAssertedChildren = new ArrayList<Node>(); for (int i = 0; i < expectedChildren.getLength(); i++) { Node expectedChild = expectedChildren.item(i); if (expectedChild.getNodeType() == Node.ELEMENT_NODE) { expectedNumberElementNodes++; String expectedChildName = getLocalName(expectedChild); String expectedUri = expectedChild.getNamespaceURI(); boolean expectedElementAsserted = false; for (int j = 0; j < toBeAssertedChildren.getLength(); j++) { final Node toBeAssertedChild = toBeAssertedChildren.item(j); // prevent previously asserted children from being // asserted again if (previouslyAssertedChildren.contains(toBeAssertedChild)) { continue; } if (toBeAssertedChild.getNodeType() == Node.ELEMENT_NODE && expectedChildName.equals(getLocalName(toBeAssertedChild)) && (expectedUri == null || expectedUri.equals(toBeAssertedChild.getNamespaceURI()))) { expectedElementAsserted = true; toBeAssertedNumberElementNodes++; assertXmlEquals(message, expectedChild, toBeAssertedChild); // add asserted child to list of asserted children to // prevent it from being asserted again. previouslyAssertedChildren.add(toBeAssertedChild); break; } } if (!expectedElementAsserted) { fail(new StringBuffer(message).append(" Did not found expected corresponding element [") .append(nodeName).append(", ").append(expectedChildName).append(", ").append(i) .append("]").toString()); } } } // check if any element node in toBeAssertedChildren exists // that has not been asserted. In this case, this element node // is unexpected! for (int i = 0; i < toBeAssertedChildren.getLength(); i++) { Node toBeAssertedChild = toBeAssertedChildren.item(i); // prevent previously asserted children from being // asserted again if (previouslyAssertedChildren.contains(toBeAssertedChild)) { continue; } if (toBeAssertedChild.getNodeType() == Node.ELEMENT_NODE) { fail(new StringBuffer(message).append("Found unexpected element node [").append(nodeName) .append(", ").append(getLocalName(toBeAssertedChild)).append(", ").append(i).append("]") .toString()); } } // if no children have been found, text content must be compared if (expectedNumberElementNodes == 0 && toBeAssertedNumberElementNodes == 0) { String expectedContent = expected.getTextContent(); String toBeAssertedContent = toBeAsserted.getTextContent(); assertEquals(message, expectedContent, toBeAssertedContent); } }